File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1289: download - view: text, annotated - select for diffs
Tue Jun 16 20:24:59 2015 UTC (9 years, 1 month ago) by damieng
Branches: MAIN
CVS tags: HEAD
further bug fixes, optimizations and cleanup for searches

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1289 2015/06/16 20:24:59 damieng 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( sleep 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 = 20;     # 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(0.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(0.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 1;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  853:                                              $try_server));
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     next unless (&spare_can_host($udom,$uint_dom,
  865:                                                  $remotesessions,$try_server));
  866: 	            ($spare_server, $lowest_load) =
  867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  868:                 }
  869: 	    }
  870:         }
  871:     }
  872: 
  873:     if (!$want_server_name) {
  874:         my $protocol = 'http';
  875:         if ($protocol{$spare_server} eq 'https') {
  876:             $protocol = $protocol{$spare_server};
  877:         }
  878:         if (defined($spare_server)) {
  879:             my $hostname = &hostname($spare_server);
  880:             if (defined($hostname)) {
  881: 	        $spare_server = $protocol.'://'.$hostname;
  882:             }
  883:         }
  884:     }
  885:     return $spare_server;
  886: }
  887: 
  888: sub compare_server_load {
  889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  890: 
  891:     if ($required) {
  892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  895:         if (($major eq '' && $minor eq '') ||
  896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  897:             return ($spare_server,$lowest_load);
  898:         }
  899:     }
  900: 
  901:     my $loadans     = &reply('load',    $try_server);
  902:     my $userloadans = &reply('userload',$try_server);
  903: 
  904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  906:     }
  907: 
  908:     my $load;
  909:     if ($loadans =~ /\d/) {
  910: 	if ($userloadans =~ /\d/) {
  911: 	    #both are numbers, pick the bigger one
  912: 	    $load = ($loadans > $userloadans) ? $loadans 
  913: 		                              : $userloadans;
  914: 	} else {
  915: 	    $load = $loadans;
  916: 	}
  917:     } else {
  918: 	$load = $userloadans;
  919:     }
  920: 
  921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  922: 	$spare_server = $try_server;
  923: 	$lowest_load  = $load;
  924:     }
  925:     return ($spare_server,$lowest_load);
  926: }
  927: 
  928: # --------------------------- ask offload servers if user already has a session
  929: sub find_existing_session {
  930:     my ($udom,$uname) = @_;
  931:     my $spareshash = &this_host_spares($udom);
  932:     if (ref($spareshash) eq 'HASH') {
  933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  941:             }
  942:         }
  943:     }
  944:     return;
  945: }
  946: 
  947: # -------------------------------- ask if server already has a session for user
  948: sub has_user_session {
  949:     my ($lonid,$udom,$uname) = @_;
  950:     my $result = &reply(join(':','userhassession',
  951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  952:     return 1 if ($result eq 'ok');
  953: 
  954:     return 0;
  955: }
  956: 
  957: # --------- determine least loaded server in a user's domain which allows login
  958: 
  959: sub choose_server {
  960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  962:     my %servers = &get_servers($udom);
  963:     my $lowest_load = 30000;
  964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  965:     if ($skiploadbal) {
  966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  967:         unless (defined($cached)) {
  968:             my $cachetime = 60*60*24;
  969:             my %domconfig =
  970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  973:                                            $cachetime);
  974:             }
  975:         }
  976:     }
  977:     foreach my $lonhost (keys(%servers)) {
  978:         if ($skiploadbal) {
  979:             if (ref($balancers) eq 'HASH') {
  980:                 next if (exists($balancers->{$lonhost}));
  981:             }
  982:         }   
  983:         my $loginvia;
  984:         if ($checkloginvia) {
  985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  986:             if ($loginvia) {
  987:                 my ($server,$path) = split(/:/,$loginvia);
  988:                 ($login_host, $lowest_load) =
  989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  990:                 if ($login_host eq $server) {
  991:                     $portal_path = $path;
  992:                     $isredirect = 1;
  993:                 }
  994:             } else {
  995:                 ($login_host, $lowest_load) =
  996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  997:                 if ($login_host eq $lonhost) {
  998:                     $portal_path = '';
  999:                     $isredirect = ''; 
 1000:                 }
 1001:             }
 1002:         } else {
 1003:             ($login_host, $lowest_load) =
 1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1005:         }
 1006:     }
 1007:     if ($login_host ne '') {
 1008:         $hostname = &hostname($login_host);
 1009:     }
 1010:     return ($login_host,$hostname,$portal_path,$isredirect);
 1011: }
 1012: 
 1013: # --------------------------------------------- Try to change a user's password
 1014: 
 1015: sub changepass {
 1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1017:     $currentpass = &escape($currentpass);
 1018:     $newpass     = &escape($newpass);
 1019:     my $lonhost = $perlvar{'lonHostID'};
 1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1021: 		       $server);
 1022:     if (! $answer) {
 1023: 	&logthis("No reply on password change request to $server ".
 1024: 		 "by $uname in domain $udom.");
 1025:     } elsif ($answer =~ "^ok") {
 1026:         &logthis("$uname in $udom successfully changed their password ".
 1027: 		 "on $server.");
 1028:     } elsif ($answer =~ "^pwchange_failure") {
 1029: 	&logthis("$uname in $udom was unable to change their password ".
 1030: 		 "on $server.  The action was blocked by either lcpasswd ".
 1031: 		 "or pwchange");
 1032:     } elsif ($answer =~ "^non_authorized") {
 1033:         &logthis("$uname in $udom did not get their password correct when ".
 1034: 		 "attempting to change it on $server.");
 1035:     } elsif ($answer =~ "^auth_mode_error") {
 1036:         &logthis("$uname in $udom attempted to change their password despite ".
 1037: 		 "not being locally or internally authenticated on $server.");
 1038:     } elsif ($answer =~ "^unknown_user") {
 1039:         &logthis("$uname in $udom attempted to change their password ".
 1040: 		 "on $server but were unable to because $server is not ".
 1041: 		 "their home server.");
 1042:     } elsif ($answer =~ "^refused") {
 1043: 	&logthis("$server refused to change $uname in $udom password because ".
 1044: 		 "it was sent an unencrypted request to change the password.");
 1045:     } elsif ($answer =~ "invalid_client") {
 1046:         &logthis("$server refused to change $uname in $udom password because ".
 1047:                  "it was a reset by e-mail originating from an invalid server.");
 1048:     }
 1049:     return $answer;
 1050: }
 1051: 
 1052: # ----------------------- Try to determine user's current authentication scheme
 1053: 
 1054: sub queryauthenticate {
 1055:     my ($uname,$udom)=@_;
 1056:     my $uhome=&homeserver($uname,$udom);
 1057:     if (!$uhome) {
 1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1059: 	return 'no_host';
 1060:     }
 1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1064:     }
 1065:     return $answer;
 1066: }
 1067: 
 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
 1069: 
 1070: sub authenticate {
 1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1072:     $upass=&escape($upass);
 1073:     $uname= &LONCAPA::clean_username($uname);
 1074:     my $uhome=&homeserver($uname,$udom,1);
 1075:     my $newhome;
 1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1077: # Maybe the machine was offline and only re-appeared again recently?
 1078:         &reconlonc();
 1079: # One more
 1080: 	$uhome=&homeserver($uname,$udom,1);
 1081:         if (($uhome eq 'no_host') && $checkdefauth) {
 1082:             if (defined(&domain($udom,'primary'))) {
 1083:                 $newhome=&domain($udom,'primary');
 1084:             }
 1085:             if ($newhome ne '') {
 1086:                 $uhome = $newhome;
 1087:             }
 1088:         }
 1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1091: 	    return 'no_host';
 1092:         }
 1093:     }
 1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1095:     if ($answer eq 'authorized') {
 1096:         if ($newhome) {
 1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1098:             return 'no_account_on_host'; 
 1099:         } else {
 1100:             &logthis("User $uname at $udom authorized by $uhome");
 1101:             return $uhome;
 1102:         }
 1103:     }
 1104:     if ($answer eq 'non_authorized') {
 1105: 	&logthis("User $uname at $udom rejected by $uhome");
 1106: 	return 'no_host'; 
 1107:     }
 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1109:     return 'no_host';
 1110: }
 1111: 
 1112: sub can_host_session {
 1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1114:     my $canhost = 1;
 1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1116:     if (ref($remotesessions) eq 'HASH') {
 1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1119:                 $canhost = 0;
 1120:             } else {
 1121:                 $canhost = 1;
 1122:             }
 1123:         }
 1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1126:                 $canhost = 1;
 1127:             } else {
 1128:                 $canhost = 0;
 1129:             }
 1130:         }
 1131:         if ($canhost) {
 1132:             if ($remotesessions->{'version'} ne '') {
 1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1134:                 if ($reqmajor ne '' && $reqminor ne '') {
 1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1136:                         my $major = $1;
 1137:                         my $minor = $2;
 1138:                         if (($major < $reqmajor ) ||
 1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1140:                             $canhost = 0;
 1141:                         }
 1142:                     } else {
 1143:                         $canhost = 0;
 1144:                     }
 1145:                 }
 1146:             }
 1147:         }
 1148:     }
 1149:     if ($canhost) {
 1150:         if (ref($hostedsessions) eq 'HASH') {
 1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1154:                 if (($uint_dom ne '') && 
 1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1156:                     $canhost = 0;
 1157:                 } else {
 1158:                     $canhost = 1;
 1159:                 }
 1160:             }
 1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1162:                 if (($uint_dom ne '') && 
 1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1164:                     $canhost = 1;
 1165:                 } else {
 1166:                     $canhost = 0;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return $canhost;
 1172: }
 1173: 
 1174: sub spare_can_host {
 1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1176:     my $canhost=1;
 1177:     my $try_server_hostname = &hostname($try_server);
 1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1179:     my $serverhomedom = &host_domain($serverhomeID);
 1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1183:             $canhost = 0;
 1184:         }
 1185:     }
 1186:     if (($canhost) && ($uint_dom)) {
 1187:         my @intdoms;
 1188:         my $internet_names = &get_internet_names($try_server);
 1189:         if (ref($internet_names) eq 'ARRAY') {
 1190:             @intdoms = @{$internet_names};
 1191:         }
 1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1195:                                          $remotesessions,
 1196:                                          $defdomdefaults{'hostedsessions'});
 1197:         }
 1198:     }
 1199:     return $canhost;
 1200: }
 1201: 
 1202: sub this_host_spares {
 1203:     my ($dom) = @_;
 1204:     my ($dom_in_use,$lonhost_in_use,$result);
 1205:     my @hosts = &current_machine_ids();
 1206:     foreach my $lonhost (@hosts) {
 1207:         if (&host_domain($lonhost) eq $dom) {
 1208:             $dom_in_use = $dom;
 1209:             $lonhost_in_use = $lonhost;
 1210:             last;
 1211:         }
 1212:     }
 1213:     if ($dom_in_use ne '') {
 1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1215:     }
 1216:     if (ref($result) ne 'HASH') {
 1217:         $lonhost_in_use = $perlvar{'lonHostID'};
 1218:         $dom_in_use = &host_domain($lonhost_in_use);
 1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1220:         if (ref($result) ne 'HASH') {
 1221:             $result = \%spareid;
 1222:         }
 1223:     }
 1224:     return $result;
 1225: }
 1226: 
 1227: sub spares_for_offload  {
 1228:     my ($dom_in_use,$lonhost_in_use) = @_;
 1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1230:     if (defined($cached)) {
 1231:         return $result;
 1232:     } else {
 1233:         my $cachetime = 60*60*24;
 1234:         my %domconfig =
 1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1240:                 }
 1241:             }
 1242:         }
 1243:     }
 1244:     return;
 1245: }
 1246: 
 1247: sub get_lonbalancer_config {
 1248:     my ($servers) = @_;
 1249:     my ($currbalancer,$currtargets);
 1250:     if (ref($servers) eq 'HASH') {
 1251:         foreach my $server (keys(%{$servers})) {
 1252:             my %what = (
 1253:                          spareid => 1,
 1254:                          perlvar => 1,
 1255:                        );
 1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1257:             if ($result eq 'ok') {
 1258:                 if (ref($returnhash) eq 'HASH') {
 1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1261:                             $currbalancer = $server;
 1262:                             $currtargets = {};
 1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1266:                                 }
 1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1269:                                 }
 1270:                             }
 1271:                             last;
 1272:                         }
 1273:                     }
 1274:                 }
 1275:             }
 1276:         }
 1277:     }
 1278:     return ($currbalancer,$currtargets);
 1279: }
 1280: 
 1281: sub check_loadbalancing {
 1282:     my ($uname,$udom) = @_;
 1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1284:         $rule_in_effect,$offloadto,$otherserver);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my @hosts = &current_machine_ids();
 1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1290:     my $serverhomedom = &host_domain($lonhost);
 1291: 
 1292:     my $cachetime = 60*60*24;
 1293: 
 1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1295:         $dom_in_use = $udom;
 1296:         $homeintdom = 1;
 1297:     } else {
 1298:         $dom_in_use = $serverhomedom;
 1299:     }
 1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1301:     unless (defined($cached)) {
 1302:         my %domconfig =
 1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1306:         }
 1307:     }
 1308:     if (ref($result) eq 'HASH') {
 1309:         ($is_balancer,$currtargets,$currrules) = 
 1310:             &check_balancer_result($result,@hosts);
 1311:         if ($is_balancer) {
 1312:             if (ref($currrules) eq 'HASH') {
 1313:                 if ($homeintdom) {
 1314:                     if ($uname ne '') {
 1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1321:                             }
 1322:                         }
 1323:                         if ($rule_in_effect eq '') {
 1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1325:                             if ($userenv{'inststatus'} ne '') {
 1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1327:                                 my ($othertitle,$usertypes,$types) =
 1328:                                     &Apache::loncommon::sorted_inst_types($udom);
 1329:                                 if (ref($types) eq 'ARRAY') {
 1330:                                     foreach my $type (@{$types}) {
 1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1332:                                             if (exists($currrules->{$type})) {
 1333:                                                 $rule_in_effect = $currrules->{$type};
 1334:                                             }
 1335:                                         }
 1336:                                     }
 1337:                                 }
 1338:                             } else {
 1339:                                 if (exists($currrules->{'default'})) {
 1340:                                     $rule_in_effect = $currrules->{'default'};
 1341:                                 }
 1342:                             }
 1343:                         }
 1344:                     } else {
 1345:                         if (exists($currrules->{'default'})) {
 1346:                             $rule_in_effect = $currrules->{'default'};
 1347:                         }
 1348:                     }
 1349:                 } else {
 1350:                     if ($currrules->{'_LC_external'} ne '') {
 1351:                         $rule_in_effect = $currrules->{'_LC_external'};
 1352:                     }
 1353:                 }
 1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1355:                                                        $uname,$udom);
 1356:             }
 1357:         }
 1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1360:         unless (defined($cached)) {
 1361:             my %domconfig =
 1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1365:             }
 1366:         }
 1367:         if (ref($result) eq 'HASH') {
 1368:             ($is_balancer,$currtargets,$currrules) = 
 1369:                 &check_balancer_result($result,@hosts);
 1370:             if ($is_balancer) {
 1371:                 if (ref($currrules) eq 'HASH') {
 1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1374:                     }
 1375:                 }
 1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1377:                                                        $uname,$udom);
 1378:             }
 1379:         } else {
 1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1381:                 $is_balancer = 1;
 1382:                 $offloadto = &this_host_spares($dom_in_use);
 1383:             }
 1384:         }
 1385:     } else {
 1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1387:             $is_balancer = 1;
 1388:             $offloadto = &this_host_spares($dom_in_use);
 1389:         }
 1390:     }
 1391:     if ($is_balancer) {
 1392:         my $lowest_load = 30000;
 1393:         if (ref($offloadto) eq 'HASH') {
 1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1396:                     ($otherserver,$lowest_load) =
 1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1398:                 }
 1399:             }
 1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1401: 
 1402:             if (!$found_server) {
 1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1405:                         ($otherserver,$lowest_load) =
 1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1407:                     }
 1408:                 }
 1409:             }
 1410:         } elsif (ref($offloadto) eq 'ARRAY') {
 1411:             if (@{$offloadto} == 1) {
 1412:                 $otherserver = $offloadto->[0];
 1413:             } elsif (@{$offloadto} > 1) {
 1414:                 foreach my $try_server (@{$offloadto}) {
 1415:                     ($otherserver,$lowest_load) =
 1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1417:                 }
 1418:             }
 1419:         }
 1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1421:             $is_balancer = 0;
 1422:             if ($uname ne '' && $udom ne '') {
 1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1424:                     
 1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1426:                              'user.loadbalcheck.time' => time});
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return ($is_balancer,$otherserver);
 1432: }
 1433: 
 1434: sub check_balancer_result {
 1435:     my ($result,@hosts) = @_;
 1436:     my ($is_balancer,$currtargets,$currrules);
 1437:     if (ref($result) eq 'HASH') {
 1438:         if ($result->{'lonhost'} ne '') {
 1439:             my $currbalancer = $result->{'lonhost'};
 1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1441:                 $is_balancer = 1;
 1442:                 $currtargets = $result->{'targets'};
 1443:                 $currrules = $result->{'rules'};
 1444:             }
 1445:         } else {
 1446:             foreach my $key (keys(%{$result})) {
 1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1448:                     (ref($result->{$key}) eq 'HASH')) {
 1449:                     $is_balancer = 1;
 1450:                     $currrules = $result->{$key}{'rules'};
 1451:                     $currtargets = $result->{$key}{'targets'};
 1452:                     last;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     return ($is_balancer,$currtargets,$currrules);
 1458: }
 1459: 
 1460: sub get_loadbalancer_targets {
 1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1462:     my $offloadto;
 1463:     if ($rule_in_effect eq 'none') {
 1464:         return [$perlvar{'lonHostID'}];
 1465:     } elsif ($rule_in_effect eq '') {
 1466:         $offloadto = $currtargets;
 1467:     } else {
 1468:         if ($rule_in_effect eq 'homeserver') {
 1469:             my $homeserver = &homeserver($uname,$udom);
 1470:             if ($homeserver ne 'no_host') {
 1471:                 $offloadto = [$homeserver];
 1472:             }
 1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1474:             my %domconfig =
 1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1480:                     }
 1481:                 }
 1482:             } else {
 1483:                 my %servers = &internet_dom_servers($udom);
 1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1485:                 if (&hostname($remotebalancer) ne '') {
 1486:                     $offloadto = [$remotebalancer];
 1487:                 }
 1488:             }
 1489:         } elsif (&hostname($rule_in_effect) ne '') {
 1490:             $offloadto = [$rule_in_effect];
 1491:         }
 1492:     }
 1493:     return $offloadto;
 1494: }
 1495: 
 1496: sub internet_dom_servers {
 1497:     my ($dom) = @_;
 1498:     my (%uniqservers,%servers);
 1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1500:     my @machinedoms = &machine_domains($primaryserver);
 1501:     foreach my $mdom (@machinedoms) {
 1502:         my %currservers = %servers;
 1503:         my %server = &get_servers($mdom);
 1504:         %servers = (%currservers,%server);
 1505:     }
 1506:     my %by_hostname;
 1507:     foreach my $id (keys(%servers)) {
 1508:         push(@{$by_hostname{$servers{$id}}},$id);
 1509:     }
 1510:     foreach my $hostname (sort(keys(%by_hostname))) {
 1511:         if (@{$by_hostname{$hostname}} > 1) {
 1512:             my $match = 0;
 1513:             foreach my $id (@{$by_hostname{$hostname}}) {
 1514:                 if (&host_domain($id) eq $dom) {
 1515:                     $uniqservers{$id} = $hostname;
 1516:                     $match = 1;
 1517:                 }
 1518:             }
 1519:             unless ($match) {
 1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1521:             }
 1522:         } else {
 1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1524:         }
 1525:     }
 1526:     return %uniqservers;
 1527: }
 1528: 
 1529: # ---------------------- Find the homebase for a user from domain's lib servers
 1530: 
 1531: my %homecache;
 1532: sub homeserver {
 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
 1534:     my $index="$uname:$udom";
 1535: 
 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1537: 
 1538:     my %servers = &get_servers($udom,'library');
 1539:     foreach my $tryserver (keys(%servers)) {
 1540:         next if ($ignoreBadCache ne 'true' && 
 1541: 		 exists($badServerCache{$tryserver}));
 1542: 
 1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1544: 	if ($answer eq 'found') {
 1545: 	    delete($badServerCache{$tryserver}); 
 1546: 	    return $homecache{$index}=$tryserver;
 1547: 	} elsif ($answer eq 'no_host') {
 1548: 	    $badServerCache{$tryserver}=1;
 1549: 	}
 1550:     }    
 1551:     return 'no_host';
 1552: }
 1553: 
 1554: # ------------------------------------- Find the usernames behind a list of IDs
 1555: 
 1556: sub idget {
 1557:     my ($udom,@ids)=@_;
 1558:     my %returnhash=();
 1559:     
 1560:     my %servers = &get_servers($udom,'library');
 1561:     foreach my $tryserver (keys(%servers)) {
 1562: 	my $idlist=join('&',@ids);
 1563: 	$idlist=~tr/A-Z/a-z/; 
 1564: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1565: 	my @answer=();
 1566: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1567: 	    @answer=split(/\&/,$reply);
 1568: 	}                    ;
 1569: 	my $i;
 1570: 	for ($i=0;$i<=$#ids;$i++) {
 1571: 	    if ($answer[$i]) {
 1572: 		$returnhash{$ids[$i]}=$answer[$i];
 1573: 	    } 
 1574: 	}
 1575:     } 
 1576:     return %returnhash;
 1577: }
 1578: 
 1579: # ------------------------------------- Find the IDs behind a list of usernames
 1580: 
 1581: sub idrget {
 1582:     my ($udom,@unames)=@_;
 1583:     my %returnhash=();
 1584:     foreach my $uname (@unames) {
 1585:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1586:     }
 1587:     return %returnhash;
 1588: }
 1589: 
 1590: # ------------------------------- Store away a list of names and associated IDs
 1591: 
 1592: sub idput {
 1593:     my ($udom,%ids)=@_;
 1594:     my %servers=();
 1595:     foreach my $uname (keys(%ids)) {
 1596: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1597:         my $uhom=&homeserver($uname,$udom);
 1598:         if ($uhom ne 'no_host') {
 1599:             my $id=&escape($ids{$uname});
 1600:             $id=~tr/A-Z/a-z/;
 1601:             my $esc_unam=&escape($uname);
 1602: 	    if ($servers{$uhom}) {
 1603: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1604:             } else {
 1605:                 $servers{$uhom}=$id.'='.$esc_unam;
 1606:             }
 1607:         }
 1608:     }
 1609:     foreach my $server (keys(%servers)) {
 1610:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1611:     }
 1612: }
 1613: 
 1614: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1615: 
 1616: sub iddel {
 1617:     my ($udom,$idshashref,$uhome)=@_;
 1618:     my %result=();
 1619:     unless (ref($idshashref) eq 'HASH') {
 1620:         return %result;
 1621:     }
 1622:     my %servers=();
 1623:     while (my ($id,$uname) = each(%{$idshashref})) {
 1624:         my $uhom;
 1625:         if ($uhome) {
 1626:             $uhom = $uhome;
 1627:         } else {
 1628:             $uhom=&homeserver($uname,$udom);
 1629:         }
 1630:         if ($uhom ne 'no_host') {
 1631:             if ($servers{$uhom}) {
 1632:                 $servers{$uhom}.='&'.&escape($id);
 1633:             } else {
 1634:                 $servers{$uhom}=&escape($id);
 1635:             }
 1636:         }
 1637:     }
 1638:     foreach my $server (keys(%servers)) {
 1639:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1640:     }
 1641:     return %result;
 1642: }
 1643: 
 1644: # ------------------------------dump from db file owned by domainconfig user
 1645: sub dump_dom {
 1646:     my ($namespace, $udom, $regexp) = @_;
 1647: 
 1648:     $udom ||= $env{'user.domain'};
 1649: 
 1650:     return () unless $udom;
 1651: 
 1652:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1653: }
 1654: 
 1655: # ------------------------------------------ get items from domain db files   
 1656: 
 1657: sub get_dom {
 1658:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1659:     return if ($udom eq 'public');
 1660:     my $items='';
 1661:     foreach my $item (@$storearr) {
 1662:         $items.=&escape($item).'&';
 1663:     }
 1664:     $items=~s/\&$//;
 1665:     if (!$udom) {
 1666:         $udom=$env{'user.domain'};
 1667:         return if ($udom eq 'public');
 1668:         if (defined(&domain($udom,'primary'))) {
 1669:             $uhome=&domain($udom,'primary');
 1670:         } else {
 1671:             undef($uhome);
 1672:         }
 1673:     } else {
 1674:         if (!$uhome) {
 1675:             if (defined(&domain($udom,'primary'))) {
 1676:                 $uhome=&domain($udom,'primary');
 1677:             }
 1678:         }
 1679:     }
 1680:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1681:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1682:         my %returnhash;
 1683:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1684:             return %returnhash;
 1685:         }
 1686:         my @pairs=split(/\&/,$rep);
 1687:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1688:             return @pairs;
 1689:         }
 1690:         my $i=0;
 1691:         foreach my $item (@$storearr) {
 1692:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1693:             $i++;
 1694:         }
 1695:         return %returnhash;
 1696:     } else {
 1697:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1698:     }
 1699: }
 1700: 
 1701: # -------------------------------------------- put items in domain db files 
 1702: 
 1703: sub put_dom {
 1704:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1705:     if (!$udom) {
 1706:         $udom=$env{'user.domain'};
 1707:         if (defined(&domain($udom,'primary'))) {
 1708:             $uhome=&domain($udom,'primary');
 1709:         } else {
 1710:             undef($uhome);
 1711:         }
 1712:     } else {
 1713:         if (!$uhome) {
 1714:             if (defined(&domain($udom,'primary'))) {
 1715:                 $uhome=&domain($udom,'primary');
 1716:             }
 1717:         }
 1718:     } 
 1719:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1720:         my $items='';
 1721:         foreach my $item (keys(%$storehash)) {
 1722:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1723:         }
 1724:         $items=~s/\&$//;
 1725:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1726:     } else {
 1727:         &logthis("put_dom failed - no homeserver and/or domain");
 1728:     }
 1729: }
 1730: 
 1731: # --------------------- newput for items in db file owned by domainconfig user
 1732: sub newput_dom {
 1733:     my ($namespace,$storehash,$udom) = @_;
 1734:     my $result;
 1735:     if (!$udom) {
 1736:         $udom=$env{'user.domain'};
 1737:     }
 1738:     if ($udom) {
 1739:         my $uname = &get_domainconfiguser($udom);
 1740:         $result = &newput($namespace,$storehash,$udom,$uname);
 1741:     }
 1742:     return $result;
 1743: }
 1744: 
 1745: # --------------------- delete for items in db file owned by domainconfig user
 1746: sub del_dom {
 1747:     my ($namespace,$storearr,$udom)=@_;
 1748:     if (ref($storearr) eq 'ARRAY') {
 1749:         if (!$udom) {
 1750:             $udom=$env{'user.domain'};
 1751:         }
 1752:         if ($udom) {
 1753:             my $uname = &get_domainconfiguser($udom); 
 1754:             return &del($namespace,$storearr,$udom,$uname);
 1755:         }
 1756:     }
 1757: }
 1758: 
 1759: # ----------------------------------construct domainconfig user for a domain 
 1760: sub get_domainconfiguser {
 1761:     my ($udom) = @_;
 1762:     return $udom.'-domainconfig';
 1763: }
 1764: 
 1765: sub retrieve_inst_usertypes {
 1766:     my ($udom) = @_;
 1767:     my (%returnhash,@order);
 1768:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1769:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1770:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1771:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1772:     } else {
 1773:         if (defined(&domain($udom,'primary'))) {
 1774:             my $uhome=&domain($udom,'primary');
 1775:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1776:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1777:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1778:                 return (\%returnhash,\@order);
 1779:             }
 1780:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1781:             my @pairs=split(/\&/,$hashitems);
 1782:             foreach my $item (@pairs) {
 1783:                 my ($key,$value)=split(/=/,$item,2);
 1784:                 $key = &unescape($key);
 1785:                 next if ($key =~ /^error: 2 /);
 1786:                 $returnhash{$key}=&thaw_unescape($value);
 1787:             }
 1788:             my @esc_order = split(/\&/,$orderitems);
 1789:             foreach my $item (@esc_order) {
 1790:                 push(@order,&unescape($item));
 1791:             }
 1792:         } else {
 1793:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1794:         }
 1795:         return (\%returnhash,\@order);
 1796:     }
 1797: }
 1798: 
 1799: sub is_domainimage {
 1800:     my ($url) = @_;
 1801:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1802:         if (&domain($1) ne '') {
 1803:             return '1';
 1804:         }
 1805:     }
 1806:     return;
 1807: }
 1808: 
 1809: sub inst_directory_query {
 1810:     my ($srch) = @_;
 1811:     my $udom = $srch->{'srchdomain'};
 1812:     my %results;
 1813:     my $homeserver = &domain($udom,'primary');
 1814:     my $outcome;
 1815:     if ($homeserver ne '') {
 1816: 	my $queryid=&reply("querysend:instdirsearch:".
 1817: 			   &escape($srch->{'srchby'}).':'.
 1818: 			   &escape($srch->{'srchterm'}).':'.
 1819: 			   &escape($srch->{'srchtype'}),$homeserver);
 1820: 	my $host=&hostname($homeserver);
 1821: 	if ($queryid !~/^\Q$host\E\_/) {
 1822: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1823: 	    return;
 1824: 	}
 1825: 	my $response = &get_query_reply($queryid);
 1826: 	my $maxtries = 5;
 1827: 	my $tries = 1;
 1828: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1829: 	    $response = &get_query_reply($queryid);
 1830: 	    $tries ++;
 1831: 	}
 1832: 
 1833:         if (!&error($response) && $response ne 'refused') {
 1834:             if ($response eq 'unavailable') {
 1835:                 $outcome = $response;
 1836:             } else {
 1837:                 $outcome = 'ok';
 1838:                 my @matches = split(/\n/,$response);
 1839:                 foreach my $match (@matches) {
 1840:                     my ($key,$value) = split(/=/,$match);
 1841:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1842:                 }
 1843:             }
 1844:         }
 1845:     }
 1846:     return ($outcome,%results);
 1847: }
 1848: 
 1849: sub usersearch {
 1850:     my ($srch) = @_;
 1851:     my $dom = $srch->{'srchdomain'};
 1852:     my %results;
 1853:     my %libserv = &all_library();
 1854:     my $query = 'usersearch';
 1855:     foreach my $tryserver (keys(%libserv)) {
 1856:         if (&host_domain($tryserver) eq $dom) {
 1857:             my $host=&hostname($tryserver);
 1858:             my $queryid=
 1859:                 &reply("querysend:".&escape($query).':'.
 1860:                        &escape($srch->{'srchby'}).':'.
 1861:                        &escape($srch->{'srchtype'}).':'.
 1862:                        &escape($srch->{'srchterm'}),$tryserver);
 1863:             if ($queryid !~/^\Q$host\E\_/) {
 1864:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1865:                 next;
 1866:             }
 1867:             my $reply = &get_query_reply($queryid);
 1868:             my $maxtries = 1;
 1869:             my $tries = 1;
 1870:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1871:                 $reply = &get_query_reply($queryid);
 1872:                 $tries ++;
 1873:             }
 1874:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1875:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1876:             } else {
 1877:                 my @matches;
 1878:                 if ($reply =~ /\n/) {
 1879:                     @matches = split(/\n/,$reply);
 1880:                 } else {
 1881:                     @matches = split(/\&/,$reply);
 1882:                 }
 1883:                 foreach my $match (@matches) {
 1884:                     my ($uname,$udom,%userhash);
 1885:                     foreach my $entry (split(/:/,$match)) {
 1886:                         my ($key,$value) =
 1887:                             map {&unescape($_);} split(/=/,$entry);
 1888:                         $userhash{$key} = $value;
 1889:                         if ($key eq 'username') {
 1890:                             $uname = $value;
 1891:                         } elsif ($key eq 'domain') {
 1892:                             $udom = $value;
 1893:                         }
 1894:                     }
 1895:                     $results{$uname.':'.$udom} = \%userhash;
 1896:                 }
 1897:             }
 1898:         }
 1899:     }
 1900:     return %results;
 1901: }
 1902: 
 1903: sub get_instuser {
 1904:     my ($udom,$uname,$id) = @_;
 1905:     my $homeserver = &domain($udom,'primary');
 1906:     my ($outcome,%results);
 1907:     if ($homeserver ne '') {
 1908:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1909:                            &escape($id).':'.&escape($udom),$homeserver);
 1910:         my $host=&hostname($homeserver);
 1911:         if ($queryid !~/^\Q$host\E\_/) {
 1912:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1913:             return;
 1914:         }
 1915:         my $response = &get_query_reply($queryid);
 1916:         my $maxtries = 5;
 1917:         my $tries = 1;
 1918:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1919:             $response = &get_query_reply($queryid);
 1920:             $tries ++;
 1921:         }
 1922:         if (!&error($response) && $response ne 'refused') {
 1923:             if ($response eq 'unavailable') {
 1924:                 $outcome = $response;
 1925:             } else {
 1926:                 $outcome = 'ok';
 1927:                 my @matches = split(/\n/,$response);
 1928:                 foreach my $match (@matches) {
 1929:                     my ($key,$value) = split(/=/,$match);
 1930:                     $results{&unescape($key)} = &thaw_unescape($value);
 1931:                 }
 1932:             }
 1933:         }
 1934:     }
 1935:     my %userinfo;
 1936:     if (ref($results{$uname}) eq 'HASH') {
 1937:         %userinfo = %{$results{$uname}};
 1938:     } 
 1939:     return ($outcome,%userinfo);
 1940: }
 1941: 
 1942: sub inst_rulecheck {
 1943:     my ($udom,$uname,$id,$item,$rules) = @_;
 1944:     my %returnhash;
 1945:     if ($udom ne '') {
 1946:         if (ref($rules) eq 'ARRAY') {
 1947:             @{$rules} = map {&escape($_);} (@{$rules});
 1948:             my $rulestr = join(':',@{$rules});
 1949:             my $homeserver=&domain($udom,'primary');
 1950:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1951:                 my $response;
 1952:                 if ($item eq 'username') {                
 1953:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1954:                                               ':'.&escape($uname).':'.$rulestr,
 1955:                                               $homeserver));
 1956:                 } elsif ($item eq 'id') {
 1957:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1958:                                               ':'.&escape($id).':'.$rulestr,
 1959:                                               $homeserver));
 1960:                 } elsif ($item eq 'selfcreate') {
 1961:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1962:                                                &escape($udom).':'.&escape($uname).
 1963:                                               ':'.$rulestr,$homeserver));
 1964:                 }
 1965:                 if ($response ne 'refused') {
 1966:                     my @pairs=split(/\&/,$response);
 1967:                     foreach my $item (@pairs) {
 1968:                         my ($key,$value)=split(/=/,$item,2);
 1969:                         $key = &unescape($key);
 1970:                         next if ($key =~ /^error: 2 /);
 1971:                         $returnhash{$key}=&thaw_unescape($value);
 1972:                     }
 1973:                 }
 1974:             }
 1975:         }
 1976:     }
 1977:     return %returnhash;
 1978: }
 1979: 
 1980: sub inst_userrules {
 1981:     my ($udom,$check) = @_;
 1982:     my (%ruleshash,@ruleorder);
 1983:     if ($udom ne '') {
 1984:         my $homeserver=&domain($udom,'primary');
 1985:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1986:             my $response;
 1987:             if ($check eq 'id') {
 1988:                 $response=&reply('instidrules:'.&escape($udom),
 1989:                                  $homeserver);
 1990:             } elsif ($check eq 'email') {
 1991:                 $response=&reply('instemailrules:'.&escape($udom),
 1992:                                  $homeserver);
 1993:             } else {
 1994:                 $response=&reply('instuserrules:'.&escape($udom),
 1995:                                  $homeserver);
 1996:             }
 1997:             if (($response ne 'refused') && ($response ne 'error') && 
 1998:                 ($response ne 'unknown_cmd') && 
 1999:                 ($response ne 'no_such_host')) {
 2000:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2001:                 my @pairs=split(/\&/,$hashitems);
 2002:                 foreach my $item (@pairs) {
 2003:                     my ($key,$value)=split(/=/,$item,2);
 2004:                     $key = &unescape($key);
 2005:                     next if ($key =~ /^error: 2 /);
 2006:                     $ruleshash{$key}=&thaw_unescape($value);
 2007:                 }
 2008:                 my @esc_order = split(/\&/,$orderitems);
 2009:                 foreach my $item (@esc_order) {
 2010:                     push(@ruleorder,&unescape($item));
 2011:                 }
 2012:             }
 2013:         }
 2014:     }
 2015:     return (\%ruleshash,\@ruleorder);
 2016: }
 2017: 
 2018: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2019: 
 2020: sub get_domain_defaults {
 2021:     my ($domain,$ignore_cache) = @_;
 2022:     return if (($domain eq '') || ($domain eq 'public'));
 2023:     my $cachetime = 60*60*24;
 2024:     unless ($ignore_cache) {
 2025:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2026:         if (defined($cached)) {
 2027:             if (ref($result) eq 'HASH') {
 2028:                 return %{$result};
 2029:             }
 2030:         }
 2031:     }
 2032:     my %domdefaults;
 2033:     my %domconfig =
 2034:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2035:                                   'requestcourses','inststatus',
 2036:                                   'coursedefaults','usersessions',
 2037:                                   'requestauthor','selfenrollment',
 2038:                                   'coursecategories'],$domain);
 2039:     my @coursetypes = ('official','unofficial','community','textbook');
 2040:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2041:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2042:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2043:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2044:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2045:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2046:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2047:     } else {
 2048:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2049:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2050:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2051:     }
 2052:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2053:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2054:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2055:         } else {
 2056:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2057:         }
 2058:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2059:         foreach my $item (@usertools) {
 2060:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2061:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2062:             }
 2063:         }
 2064:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2065:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2066:         }
 2067:     }
 2068:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2069:         foreach my $item ('official','unofficial','community','textbook') {
 2070:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2071:         }
 2072:     }
 2073:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2074:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2075:     }
 2076:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2077:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2078:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2079:         }
 2080:     }
 2081:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2082:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2083:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2084:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2085:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2086:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2087:         }
 2088:         foreach my $type (@coursetypes) {
 2089:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2090:                 unless ($type eq 'community') {
 2091:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2092:                 }
 2093:             }
 2094:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2095:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2096:             }
 2097:             if ($domdefaults{'postsubmit'} eq 'on') {
 2098:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2099:                     $domdefaults{$type.'postsubtimeout'} = 
 2100:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2101:                 }
 2102:             }
 2103:         }
 2104:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2105:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2106:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2107:                 if (@clonecodes) {
 2108:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2109:                 }
 2110:             }
 2111:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2112:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2113:         }
 2114:     }
 2115:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2116:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2117:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2118:         }
 2119:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2120:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2121:         }
 2122:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2123:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2124:         }
 2125:     }
 2126:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2127:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2128:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2129:                             'approval','limit');
 2130:             foreach my $type (@coursetypes) {
 2131:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2132:                     my @mgrdc = ();
 2133:                     foreach my $item (@settings) {
 2134:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2135:                             push(@mgrdc,$item);
 2136:                         }
 2137:                     }
 2138:                     if (@mgrdc) {
 2139:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2140:                     }
 2141:                 }
 2142:             }
 2143:         }
 2144:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2145:             foreach my $type (@coursetypes) {
 2146:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2147:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2148:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2149:                     }
 2150:                 }
 2151:             }
 2152:         }
 2153:     }
 2154:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2155:         $domdefaults{'catauth'} = 'std';
 2156:         $domdefaults{'catunauth'} = 'std';
 2157:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2158:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2159:         }
 2160:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2161:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2162:         }
 2163:     }
 2164:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2165:     return %domdefaults;
 2166: }
 2167: 
 2168: # --------------------------------------------------- Assign a key to a student
 2169: 
 2170: sub assign_access_key {
 2171: #
 2172: # a valid key looks like uname:udom#comments
 2173: # comments are being appended
 2174: #
 2175:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2176:     $kdom=
 2177:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2178:     $knum=
 2179:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2180:     $cdom=
 2181:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2182:     $cnum=
 2183:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2184:     $udom=$env{'user.name'} unless (defined($udom));
 2185:     $uname=$env{'user.domain'} unless (defined($uname));
 2186:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2187:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2188:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2189:                                                   # assigned to this person
 2190:                                                   # - this should not happen,
 2191:                                                   # unless something went wrong
 2192:                                                   # the first time around
 2193: # ready to assign
 2194:         $logentry=$1.'; '.$logentry;
 2195:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2196:                                                  $kdom,$knum) eq 'ok') {
 2197: # key now belongs to user
 2198: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2199:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2200:                 &appenv({'environment.'.$envkey => $ckey});
 2201:                 return 'ok';
 2202:             } else {
 2203:                 return 
 2204:   'error: Count not permanently assign key, will need to be re-entered later.';
 2205: 	    }
 2206:         } else {
 2207:             return 'error: Could not assign key, try again later.';
 2208:         }
 2209:     } elsif (!$existing{$ckey}) {
 2210: # the key does not exist
 2211: 	return 'error: The key does not exist';
 2212:     } else {
 2213: # the key is somebody else's
 2214: 	return 'error: The key is already in use';
 2215:     }
 2216: }
 2217: 
 2218: # ------------------------------------------ put an additional comment on a key
 2219: 
 2220: sub comment_access_key {
 2221: #
 2222: # a valid key looks like uname:udom#comments
 2223: # comments are being appended
 2224: #
 2225:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2226:     $cdom=
 2227:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2228:     $cnum=
 2229:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2230:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2231:     if ($existing{$ckey}) {
 2232:         $existing{$ckey}.='; '.$logentry;
 2233: # ready to assign
 2234:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2235:                                                  $cdom,$cnum) eq 'ok') {
 2236: 	    return 'ok';
 2237:         } else {
 2238: 	    return 'error: Count not store comment.';
 2239:         }
 2240:     } else {
 2241: # the key does not exist
 2242: 	return 'error: The key does not exist';
 2243:     }
 2244: }
 2245: 
 2246: # ------------------------------------------------------ Generate a set of keys
 2247: 
 2248: sub generate_access_keys {
 2249:     my ($number,$cdom,$cnum,$logentry)=@_;
 2250:     $cdom=
 2251:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2252:     $cnum=
 2253:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2254:     unless (&allowed('mky',$cdom)) { return 0; }
 2255:     unless (($cdom) && ($cnum)) { return 0; }
 2256:     if ($number>10000) { return 0; }
 2257:     sleep(2); # make sure don't get same seed twice
 2258:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2259:     my $total=0;
 2260:     for (my $i=1;$i<=$number;$i++) {
 2261:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2262:                   sprintf("%lx",int(100000*rand)).'-'.
 2263:                   sprintf("%lx",int(100000*rand));
 2264:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2265:        $newkey=~s/0/h/g; # and also 0 and O
 2266:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2267:        if ($existing{$newkey}) {
 2268:            $i--;
 2269:        } else {
 2270: 	  if (&put('accesskeys',
 2271:               { $newkey => '# generated '.localtime().
 2272:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2273:                            '; '.$logentry },
 2274: 		   $cdom,$cnum) eq 'ok') {
 2275:               $total++;
 2276: 	  }
 2277:        }
 2278:     }
 2279:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2280:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2281:     return $total;
 2282: }
 2283: 
 2284: # ------------------------------------------------------- Validate an accesskey
 2285: 
 2286: sub validate_access_key {
 2287:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2288:     $cdom=
 2289:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2290:     $cnum=
 2291:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2292:     $udom=$env{'user.domain'} unless (defined($udom));
 2293:     $uname=$env{'user.name'} unless (defined($uname));
 2294:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2295:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2296: }
 2297: 
 2298: # ------------------------------------- Find the section of student in a course
 2299: sub devalidate_getsection_cache {
 2300:     my ($udom,$unam,$courseid)=@_;
 2301:     my $hashid="$udom:$unam:$courseid";
 2302:     &devalidate_cache_new('getsection',$hashid);
 2303: }
 2304: 
 2305: sub courseid_to_courseurl {
 2306:     my ($courseid) = @_;
 2307:     #already url style courseid
 2308:     return $courseid if ($courseid =~ m{^/});
 2309: 
 2310:     if (exists($env{'course.'.$courseid.'.num'})) {
 2311: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2312: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2313: 	return "/$cdom/$cnum";
 2314:     }
 2315: 
 2316:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2317:     if (exists($courseinfo{'num'})) {
 2318: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2319:     }
 2320: 
 2321:     return undef;
 2322: }
 2323: 
 2324: sub getsection {
 2325:     my ($udom,$unam,$courseid)=@_;
 2326:     my $cachetime=1800;
 2327: 
 2328:     my $hashid="$udom:$unam:$courseid";
 2329:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2330:     if (defined($cached)) { return $result; }
 2331: 
 2332:     my %Pending; 
 2333:     my %Expired;
 2334:     #
 2335:     # Each role can either have not started yet (pending), be active, 
 2336:     #    or have expired.
 2337:     #
 2338:     # If there is an active role, we are done.
 2339:     #
 2340:     # If there is more than one role which has not started yet, 
 2341:     #     choose the one which will start sooner
 2342:     # If there is one role which has not started yet, return it.
 2343:     #
 2344:     # If there is more than one expired role, choose the one which ended last.
 2345:     # If there is a role which has expired, return it.
 2346:     #
 2347:     $courseid = &courseid_to_courseurl($courseid);
 2348:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2349:     foreach my $key (keys(%roleshash)) {
 2350:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2351:         my $section=$1;
 2352:         if ($key eq $courseid.'_st') { $section=''; }
 2353:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2354:         my $now=time;
 2355:         if (defined($end) && $end && ($now > $end)) {
 2356:             $Expired{$end}=$section;
 2357:             next;
 2358:         }
 2359:         if (defined($start) && $start && ($now < $start)) {
 2360:             $Pending{$start}=$section;
 2361:             next;
 2362:         }
 2363:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2364:     }
 2365:     #
 2366:     # Presumedly there will be few matching roles from the above
 2367:     # loop and the sorting time will be negligible.
 2368:     if (scalar(keys(%Pending))) {
 2369:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2370:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2371:     } 
 2372:     if (scalar(keys(%Expired))) {
 2373:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2374:         my $time = pop(@sorted);
 2375:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2376:     }
 2377:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2378: }
 2379: 
 2380: sub save_cache {
 2381:     &purge_remembered();
 2382:     #&Apache::loncommon::validate_page();
 2383:     undef(%env);
 2384:     undef($env_loaded);
 2385: }
 2386: 
 2387: my $to_remember=-1;
 2388: my %remembered;
 2389: my %accessed;
 2390: my $kicks=0;
 2391: my $hits=0;
 2392: sub make_key {
 2393:     my ($name,$id) = @_;
 2394:     if (length($id) > 65 
 2395: 	&& length(&escape($id)) > 200) {
 2396: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2397:     }
 2398:     return &escape($name.':'.$id);
 2399: }
 2400: 
 2401: sub devalidate_cache_new {
 2402:     my ($name,$id,$debug) = @_;
 2403:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2404:     $id=&make_key($name,$id);
 2405:     $memcache->delete($id);
 2406:     delete($remembered{$id});
 2407:     delete($accessed{$id});
 2408: }
 2409: 
 2410: sub is_cached_new {
 2411:     my ($name,$id,$debug) = @_;
 2412:     $id=&make_key($name,$id);
 2413:     if (exists($remembered{$id})) {
 2414: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2415: 	$accessed{$id}=[&gettimeofday()];
 2416: 	$hits++;
 2417: 	return ($remembered{$id},1);
 2418:     }
 2419:     my $value = $memcache->get($id);
 2420:     if (!(defined($value))) {
 2421: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2422: 	return (undef,undef);
 2423:     }
 2424:     if ($value eq '__undef__') {
 2425: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2426: 	$value=undef;
 2427:     }
 2428:     &make_room($id,$value,$debug);
 2429:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2430:     return ($value,1);
 2431: }
 2432: 
 2433: sub do_cache_new {
 2434:     my ($name,$id,$value,$time,$debug) = @_;
 2435:     $id=&make_key($name,$id);
 2436:     my $setvalue=$value;
 2437:     if (!defined($setvalue)) {
 2438: 	$setvalue='__undef__';
 2439:     }
 2440:     if (!defined($time) ) {
 2441: 	$time=600;
 2442:     }
 2443:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2444:     my $result = $memcache->set($id,$setvalue,$time);
 2445:     if (! $result) {
 2446: 	&logthis("caching of id -> $id  failed");
 2447: 	$memcache->disconnect_all();
 2448:     }
 2449:     # need to make a copy of $value
 2450:     &make_room($id,$value,$debug);
 2451:     return $value;
 2452: }
 2453: 
 2454: sub make_room {
 2455:     my ($id,$value,$debug)=@_;
 2456: 
 2457:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2458:                                     : $value;
 2459:     if ($to_remember<0) { return; }
 2460:     $accessed{$id}=[&gettimeofday()];
 2461:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2462:     my $to_kick;
 2463:     my $max_time=0;
 2464:     foreach my $other (keys(%accessed)) {
 2465: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2466: 	    $to_kick=$other;
 2467: 	    $max_time=&tv_interval($accessed{$other});
 2468: 	}
 2469:     }
 2470:     delete($remembered{$to_kick});
 2471:     delete($accessed{$to_kick});
 2472:     $kicks++;
 2473:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2474:     return;
 2475: }
 2476: 
 2477: sub purge_remembered {
 2478:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2479:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2480:     undef(%remembered);
 2481:     undef(%accessed);
 2482: }
 2483: # ------------------------------------- Read an entry from a user's environment
 2484: 
 2485: sub userenvironment {
 2486:     my ($udom,$unam,@what)=@_;
 2487:     my $items;
 2488:     foreach my $item (@what) {
 2489:         $items.=&escape($item).'&';
 2490:     }
 2491:     $items=~s/\&$//;
 2492:     my %returnhash=();
 2493:     my $uhome = &homeserver($unam,$udom);
 2494:     unless ($uhome eq 'no_host') {
 2495:         my @answer=split(/\&/, 
 2496:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2497:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2498:             return %returnhash;
 2499:         }
 2500:         my $i;
 2501:         for ($i=0;$i<=$#what;$i++) {
 2502: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2503:         }
 2504:     }
 2505:     return %returnhash;
 2506: }
 2507: 
 2508: # ---------------------------------------------------------- Get a studentphoto
 2509: sub studentphoto {
 2510:     my ($udom,$unam,$ext) = @_;
 2511:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2512:     if (defined($env{'request.course.id'})) {
 2513:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2514:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2515:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2516:             } else {
 2517:                 my ($result,$perm_reqd)=
 2518: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2519:                 if ($result eq 'ok') {
 2520:                     if (!($perm_reqd eq 'yes')) {
 2521:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2522:                     }
 2523:                 }
 2524:             }
 2525:         }
 2526:     } else {
 2527:         my ($result,$perm_reqd) = 
 2528: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2529:         if ($result eq 'ok') {
 2530:             if (!($perm_reqd eq 'yes')) {
 2531:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2532:             }
 2533:         }
 2534:     }
 2535:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2536: }
 2537: 
 2538: sub retrievestudentphoto {
 2539:     my ($udom,$unam,$ext,$type) = @_;
 2540:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2541:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2542:     if ($ret eq 'ok') {
 2543:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2544:         if ($type eq 'thumbnail') {
 2545:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2546:         }
 2547:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2548:         return $tokenurl;
 2549:     } else {
 2550:         if ($type eq 'thumbnail') {
 2551:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2552:         } else { 
 2553:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2554:         }
 2555:     }
 2556: }
 2557: 
 2558: # -------------------------------------------------------------------- New chat
 2559: 
 2560: sub chatsend {
 2561:     my ($newentry,$anon,$group)=@_;
 2562:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2563:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2564:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2565:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2566: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2567: 		   &escape($newentry)).':'.$group,$chome);
 2568: }
 2569: 
 2570: # ------------------------------------------ Find current version of a resource
 2571: 
 2572: sub getversion {
 2573:     my $fname=&clutter(shift);
 2574:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2575:     return &currentversion(&filelocation('',$fname));
 2576: }
 2577: 
 2578: sub currentversion {
 2579:     my $fname=shift;
 2580:     my $author=$fname;
 2581:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2582:     my ($udom,$uname)=split(/\//,$author);
 2583:     my $home=&homeserver($uname,$udom);
 2584:     if ($home eq 'no_host') { 
 2585:         return -1; 
 2586:     }
 2587:     my $answer=&reply("currentversion:$fname",$home);
 2588:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2589: 	return -1;
 2590:     }
 2591:     return $answer;
 2592: }
 2593: 
 2594: #
 2595: # Return special version number of resource if set by override, empty otherwise
 2596: #
 2597: sub usedversion {
 2598:     my $fname=shift;
 2599:     unless ($fname) { $fname=$env{'request.uri'}; }
 2600:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2601:     if ($urlversion) { return $urlversion; }
 2602:     return '';
 2603: }
 2604: 
 2605: # ----------------------------- Subscribe to a resource, return URL if possible
 2606: 
 2607: sub subscribe {
 2608:     my $fname=shift;
 2609:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2610:     $fname=~s/[\n\r]//g;
 2611:     my $author=$fname;
 2612:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2613:     my ($udom,$uname)=split(/\//,$author);
 2614:     my $home=homeserver($uname,$udom);
 2615:     if ($home eq 'no_host') {
 2616:         return 'not_found';
 2617:     }
 2618:     my $answer=reply("sub:$fname",$home);
 2619:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2620: 	$answer.=' by '.$home;
 2621:     }
 2622:     return $answer;
 2623: }
 2624:     
 2625: # -------------------------------------------------------------- Replicate file
 2626: 
 2627: sub repcopy {
 2628:     my $filename=shift;
 2629:     $filename=~s/\/+/\//g;
 2630:     my $londocroot = $perlvar{'lonDocRoot'};
 2631:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2632:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2633:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2634: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2635: 	return &repcopy_userfile($filename);
 2636:     }
 2637:     $filename=~s/[\n\r]//g;
 2638:     my $transname="$filename.in.transfer";
 2639: # FIXME: this should flock
 2640:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2641:     my $remoteurl=subscribe($filename);
 2642:     if ($remoteurl =~ /^con_lost by/) {
 2643: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2644:            return 'unavailable';
 2645:     } elsif ($remoteurl eq 'not_found') {
 2646: 	   #&logthis("Subscribe returned not_found: $filename");
 2647: 	   return 'not_found';
 2648:     } elsif ($remoteurl =~ /^rejected by/) {
 2649: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2650:            return 'forbidden';
 2651:     } elsif ($remoteurl eq 'directory') {
 2652:            return 'ok';
 2653:     } else {
 2654:         my $author=$filename;
 2655:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2656:         my ($udom,$uname)=split(/\//,$author);
 2657:         my $home=homeserver($uname,$udom);
 2658:         unless ($home eq $perlvar{'lonHostID'}) {
 2659:            my @parts=split(/\//,$filename);
 2660:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2661:            if ($path ne "$londocroot/res") {
 2662:                &logthis("Malconfiguration for replication: $filename");
 2663: 	       return 'bad_request';
 2664:            }
 2665:            my $count;
 2666:            for ($count=5;$count<$#parts;$count++) {
 2667:                $path.="/$parts[$count]";
 2668:                if ((-e $path)!=1) {
 2669: 		   mkdir($path,0777);
 2670:                }
 2671:            }
 2672:            my $ua=new LWP::UserAgent;
 2673:            my $request=new HTTP::Request('GET',"$remoteurl");
 2674:            my $response=$ua->request($request,$transname);
 2675:            if ($response->is_error()) {
 2676: 	       unlink($transname);
 2677:                my $message=$response->status_line;
 2678:                &logthis("<font color=\"blue\">WARNING:"
 2679:                        ." LWP get: $message: $filename</font>");
 2680:                return 'unavailable';
 2681:            } else {
 2682: 	       if ($remoteurl!~/\.meta$/) {
 2683:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2684:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2685:                   if ($mresponse->is_error()) {
 2686: 		      unlink($filename.'.meta');
 2687:                       &logthis(
 2688:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2689:                   }
 2690: 	       }
 2691:                rename($transname,$filename);
 2692:                return 'ok';
 2693:            }
 2694:        }
 2695:     }
 2696: }
 2697: 
 2698: # ------------------------------------------------ Get server side include body
 2699: sub ssi_body {
 2700:     my ($filelink,%form)=@_;
 2701:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2702:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2703:     }
 2704:     my $output='';
 2705:     my $response;
 2706:     if ($filelink=~/^https?\:/) {
 2707:        ($output,$response)=&externalssi($filelink);
 2708:     } else {
 2709:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2710:        $filelink .= 'inhibitmenu=yes';
 2711:        ($output,$response)=&ssi($filelink,%form);
 2712:     }
 2713:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2714:     $output=~s/^.*?\<body[^\>]*\>//si;
 2715:     $output=~s/\<\/body\s*\>.*?$//si;
 2716:     if (wantarray) {
 2717:         return ($output, $response);
 2718:     } else {
 2719:         return $output;
 2720:     }
 2721: }
 2722: 
 2723: # --------------------------------------------------------- Server Side Include
 2724: 
 2725: sub absolute_url {
 2726:     my ($host_name) = @_;
 2727:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2728:     if ($host_name eq '') {
 2729: 	$host_name = $ENV{'SERVER_NAME'};
 2730:     }
 2731:     return $protocol.$host_name;
 2732: }
 2733: 
 2734: #
 2735: #   Server side include.
 2736: # Parameters:
 2737: #  fn     Possibly encrypted resource name/id.
 2738: #  form   Hash that describes how the rendering should be done
 2739: #         and other things.
 2740: # Returns:
 2741: #   Scalar context: The content of the response.
 2742: #   Array context:  2 element list of the content and the full response object.
 2743: #     
 2744: sub ssi {
 2745: 
 2746:     my ($fn,%form)=@_;
 2747:     my $ua=new LWP::UserAgent;
 2748:     my $request;
 2749: 
 2750:     $form{'no_update_last_known'}=1;
 2751:     &Apache::lonenc::check_encrypt(\$fn);
 2752:     if (%form) {
 2753:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2754:       $request->content(join('&',map { 
 2755:             my $name = escape($_);
 2756:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 2757:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 2758:             : &escape($form{$_}) );    
 2759:         } keys(%form)));
 2760:     } else {
 2761:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2762:     }
 2763: 
 2764:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2765:     my $response= $ua->request($request);
 2766:     my $content = $response->content;
 2767: 
 2768: 
 2769:     if (wantarray) {
 2770: 	return ($content, $response);
 2771:     } else {
 2772: 	return $content;
 2773:     }
 2774: }
 2775: 
 2776: sub externalssi {
 2777:     my ($url)=@_;
 2778:     my $ua=new LWP::UserAgent;
 2779:     my $request=new HTTP::Request('GET',$url);
 2780:     my $response=$ua->request($request);
 2781:     if (wantarray) {
 2782:         return ($response->content, $response);
 2783:     } else {
 2784:         return $response->content;
 2785:     }
 2786: }
 2787: 
 2788: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2789: 
 2790: sub allowuploaded {
 2791:     my ($srcurl,$url)=@_;
 2792:     $url=&clutter(&declutter($url));
 2793:     my $dir=$url;
 2794:     $dir=~s/\/[^\/]+$//;
 2795:     my %httpref=();
 2796:     my $httpurl=&hreflocation('',$url);
 2797:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2798:     &Apache::lonnet::appenv(\%httpref);
 2799: }
 2800: 
 2801: #
 2802: # Determine if the current user should be able to edit a particular resource,
 2803: # when viewing in course context.
 2804: # (a) When viewing resource used to determine if "Edit" item is included in 
 2805: #     Functions.
 2806: # (b) When displaying folder contents in course editor, used to determine if
 2807: #     "Edit" link will be displayed alongside resource.
 2808: #
 2809: #  input: six args -- filename (decluttered), course number, course domain,
 2810: #                   url, symb (if registered) and group (if this is a group
 2811: #                   item -- e.g., bulletin board, group page etc.).
 2812: #  output: array of five scalars -- 
 2813: #          $cfile -- url for file editing if editable on current server
 2814: #          $home -- homeserver of resource (i.e., for author if published,
 2815: #                                           or course if uploaded.).
 2816: #          $switchserver --  1 if server switch will be needed.
 2817: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2818: #          $forceview -- 1 if icon/link should be to go to view mode
 2819: #
 2820: 
 2821: sub can_edit_resource {
 2822:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2823:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2824: #
 2825: # For aboutme pages user can only edit his/her own.
 2826: #
 2827:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2828:         my ($sdom,$sname) = ($1,$2);
 2829:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2830:             $home = $env{'user.home'};
 2831:             $cfile = $resurl;
 2832:             if ($env{'form.forceedit'}) {
 2833:                 $forceview = 1;
 2834:             } else {
 2835:                 $forceedit = 1;
 2836:             }
 2837:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2838:         } else {
 2839:             return;
 2840:         }
 2841:     }
 2842: 
 2843:     if ($env{'request.course.id'}) {
 2844:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2845:         if ($group ne '') {
 2846: # if this is a group homepage or group bulletin board, check group privs
 2847:             my $allowed = 0;
 2848:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2849:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2850:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2851:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2852:                     $allowed = 1;
 2853:                 }
 2854:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2855:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2856:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2857:                     $allowed = 1;
 2858:                 }
 2859:             }
 2860:             if ($allowed) {
 2861:                 $home=&homeserver($cnum,$cdom);
 2862:                 if ($env{'form.forceedit'}) {
 2863:                     $forceview = 1;
 2864:                 } else {
 2865:                     $forceedit = 1;
 2866:                 }
 2867:                 $cfile = $resurl;
 2868:             } else {
 2869:                 return;
 2870:             }
 2871:         } else {
 2872:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2873:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2874:                     return;
 2875:                 }
 2876:             } elsif (!$crsedit) {
 2877: #
 2878: # No edit allowed where CC has switched to student role.
 2879: #
 2880:                 return;
 2881:             }
 2882:         }
 2883:     }
 2884: 
 2885:     if ($file ne '') {
 2886:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2887:             if (&is_course_upload($file,$cnum,$cdom)) {
 2888:                 $uploaded = 1;
 2889:                 $incourse = 1;
 2890:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2891:                     $cfile = &hreflocation('',$file);
 2892:                     if ($env{'form.forceedit'}) {
 2893:                         $forceview = 1;
 2894:                     } else {
 2895:                         $forceedit = 1;
 2896:                     }
 2897:                 }
 2898:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2899:                 $incourse = 1;
 2900:                 if ($env{'form.forceedit'}) {
 2901:                     $forceview = 1;
 2902:                 } else {
 2903:                     $forceedit = 1;
 2904:                 }
 2905:                 $cfile = $resurl;
 2906:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2907:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2908:                     $incourse = 1;
 2909:                     if ($env{'form.forceedit'}) {
 2910:                         $forceview = 1;
 2911:                     } else {
 2912:                         $forceedit = 1;
 2913:                     }
 2914:                     $cfile = $resurl;
 2915:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2916:                     $incourse = 1;
 2917:                     $cfile = $resurl.'/smpedit';
 2918:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2919:                     $incourse = 1;
 2920:                     if ($env{'form.forceedit'}) {
 2921:                         $forceview = 1;
 2922:                     } else {
 2923:                         $forceedit = 1;
 2924:                     }
 2925:                     $cfile = $resurl;
 2926:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2927:                     $incourse = 1;
 2928:                     if ($env{'form.forceedit'}) {
 2929:                         $forceview = 1;
 2930:                     } else {
 2931:                         $forceedit = 1;
 2932:                     }
 2933:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2934:                 }
 2935:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2936:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2937:                 if (&is_on_map($template)) { 
 2938:                     $incourse = 1;
 2939:                     $forceview = 1;
 2940:                     $cfile = $template;
 2941:                 }
 2942:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2943:                     $incourse = 1;
 2944:                     if ($env{'form.forceedit'}) {
 2945:                         $forceview = 1;
 2946:                     } else {
 2947:                         $forceedit = 1;
 2948:                     }
 2949:                     $cfile = $resurl;
 2950:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2951:                 $incourse = 1;
 2952:                 $forceview = 1;
 2953:                 if ($symb) {
 2954:                     my ($map,$id,$res)=&decode_symb($symb);
 2955:                     $env{'request.symb'} = $symb;
 2956:                     $cfile = &clutter($res);
 2957:                 } else {
 2958:                     $cfile = $env{'form.suppurl'};
 2959:                     $cfile =~ s{^http://}{};
 2960:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2961:                 }
 2962:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2963:                 if ($env{'form.forceedit'}) {
 2964:                     $forceview = 1;
 2965:                 } else {
 2966:                     $forceedit = 1;
 2967:                 }
 2968:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2969:             }
 2970:         }
 2971:         if ($uploaded || $incourse) {
 2972:             $home=&homeserver($cnum,$cdom);
 2973:         } elsif ($file !~ m{/$}) {
 2974:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2975:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2976:             # Check that the user has permission to edit this resource
 2977:             my $setpriv = 1;
 2978:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2979:             if (defined($cfudom)) {
 2980:                 $home=&homeserver($cfuname,$cfudom);
 2981:                 $cfile=$file;
 2982:             }
 2983:         }
 2984:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2985:             (($home ne '') && ($home ne 'no_host'))) {
 2986:             my @ids=&current_machine_ids();
 2987:             unless (grep(/^\Q$home\E$/,@ids)) {
 2988:                 $switchserver=1;
 2989:             }
 2990:         }
 2991:     }
 2992:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2993: }
 2994: 
 2995: sub is_course_upload {
 2996:     my ($file,$cnum,$cdom) = @_;
 2997:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2998:     $uploadpath =~ s{^\/}{};
 2999:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3000:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3001:         return 1;
 3002:     }
 3003:     return;
 3004: }
 3005: 
 3006: sub in_course {
 3007:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3008:     if ($hideprivileged) {
 3009:         my $skipuser;
 3010:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3011:         my @possdoms = ($cdom);  
 3012:         if ($coursehash{'checkforpriv'}) { 
 3013:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3014:         }
 3015:         if (&privileged($uname,$udom,\@possdoms)) {
 3016:             $skipuser = 1;
 3017:             if ($coursehash{'nothideprivileged'}) {
 3018:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3019:                     my $user;
 3020:                     if ($item =~ /:/) {
 3021:                         $user = $item;
 3022:                     } else {
 3023:                         $user = join(':',split(/[\@]/,$item));
 3024:                     }
 3025:                     if ($user eq $uname.':'.$udom) {
 3026:                         undef($skipuser);
 3027:                         last;
 3028:                     }
 3029:                 }
 3030:             }
 3031:             if ($skipuser) {
 3032:                 return 0;
 3033:             }
 3034:         }
 3035:     }
 3036:     $type ||= 'any';
 3037:     if (!defined($cdom) || !defined($cnum)) {
 3038:         my $cid  = $env{'request.course.id'};
 3039:         $cdom = $env{'course.'.$cid.'.domain'};
 3040:         $cnum = $env{'course.'.$cid.'.num'};
 3041:     }
 3042:     my $typesref;
 3043:     if (($type eq 'any') || ($type eq 'all')) {
 3044:         $typesref = ['active','previous','future'];
 3045:     } elsif ($type eq 'previous' || $type eq 'future') {
 3046:         $typesref = [$type];
 3047:     }
 3048:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3049:                               $typesref,undef,[$cdom]);
 3050:     my ($tmp) = keys(%roles);
 3051:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3052:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3053:     if (@course_roles > 0) {
 3054:         return 1;
 3055:     }
 3056:     return 0;
 3057: }
 3058: 
 3059: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3060: # input: action, courseID, current domain, intended
 3061: #        path to file, source of file, instruction to parse file for objects,
 3062: #        ref to hash for embedded objects,
 3063: #        ref to hash for codebase of java objects.
 3064: #        reference to scalar to accommodate mime type determined
 3065: #          from File::MMagic if $parser = parse.
 3066: #
 3067: # output: url to file (if action was uploaddoc), 
 3068: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3069: #
 3070: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3071: # course.
 3072: #
 3073: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3074: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3075: #          course's home server.
 3076: #
 3077: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3078: #          be copied from $source (current location) to 
 3079: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3080: #         and will then be copied to
 3081: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3082: #         course's home server.
 3083: #
 3084: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3085: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3086: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3087: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3088: #         in course's home server.
 3089: #
 3090: 
 3091: sub process_coursefile {
 3092:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3093:         $mimetype)=@_;
 3094:     my $fetchresult;
 3095:     my $home=&homeserver($docuname,$docudom);
 3096:     if ($action eq 'propagate') {
 3097:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3098: 			     $home);
 3099:     } else {
 3100:         my $fpath = '';
 3101:         my $fname = $file;
 3102:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3103:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3104:         my $filepath = &build_filepath($fpath);
 3105:         if ($action eq 'copy') {
 3106:             if ($source eq '') {
 3107:                 $fetchresult = 'no source file';
 3108:                 return $fetchresult;
 3109:             } else {
 3110:                 my $destination = $filepath.'/'.$fname;
 3111:                 rename($source,$destination);
 3112:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3113:                                  $home);
 3114:             }
 3115:         } elsif ($action eq 'uploaddoc') {
 3116:             open(my $fh,'>'.$filepath.'/'.$fname);
 3117:             print $fh $env{'form.'.$source};
 3118:             close($fh);
 3119:             if ($parser eq 'parse') {
 3120:                 my $mm = new File::MMagic;
 3121:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3122:                 if ($type eq 'text/html') {
 3123:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3124:                     unless ($parse_result eq 'ok') {
 3125:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3126:                     }
 3127:                 }
 3128:                 if (ref($mimetype)) {
 3129:                     $$mimetype = $type;
 3130:                 } 
 3131:             }
 3132:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3133:                                  $home);
 3134:             if ($fetchresult eq 'ok') {
 3135:                 return '/uploaded/'.$fpath.'/'.$fname;
 3136:             } else {
 3137:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3138:                         ' to host '.$home.': '.$fetchresult);
 3139:                 return '/adm/notfound.html';
 3140:             }
 3141:         }
 3142:     }
 3143:     unless ( $fetchresult eq 'ok') {
 3144:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3145:              ' to host '.$home.': '.$fetchresult);
 3146:     }
 3147:     return $fetchresult;
 3148: }
 3149: 
 3150: sub build_filepath {
 3151:     my ($fpath) = @_;
 3152:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3153:     unless ($fpath eq '') {
 3154:         my @parts=split('/',$fpath);
 3155:         foreach my $part (@parts) {
 3156:             $filepath.= '/'.$part;
 3157:             if ((-e $filepath)!=1) {
 3158:                 mkdir($filepath,0777);
 3159:             }
 3160:         }
 3161:     }
 3162:     return $filepath;
 3163: }
 3164: 
 3165: sub store_edited_file {
 3166:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3167:     my $file = $primary_url;
 3168:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3169:     my $fpath = '';
 3170:     my $fname = $file;
 3171:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3172:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3173:     my $filepath = &build_filepath($fpath);
 3174:     open(my $fh,'>'.$filepath.'/'.$fname);
 3175:     print $fh $content;
 3176:     close($fh);
 3177:     my $home=&homeserver($docuname,$docudom);
 3178:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3179: 			  $home);
 3180:     if ($$fetchresult eq 'ok') {
 3181:         return '/uploaded/'.$fpath.'/'.$fname;
 3182:     } else {
 3183:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3184: 		 ' to host '.$home.': '.$$fetchresult);
 3185:         return '/adm/notfound.html';
 3186:     }
 3187: }
 3188: 
 3189: sub clean_filename {
 3190:     my ($fname,$args)=@_;
 3191: # Replace Windows backslashes by forward slashes
 3192:     $fname=~s/\\/\//g;
 3193:     if (!$args->{'keep_path'}) {
 3194:         # Get rid of everything but the actual filename
 3195: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3196:     }
 3197: # Replace spaces by underscores
 3198:     $fname=~s/\s+/\_/g;
 3199: # Replace all other weird characters by nothing
 3200:     $fname=~s{[^/\w\.\-]}{}g;
 3201: # Replace all .\d. sequences with _\d. so they no longer look like version
 3202: # numbers
 3203:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3204:     return $fname;
 3205: }
 3206: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3207: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3208: # image with the same aspect ratio as the original, but with dimensions which do 
 3209: # not exceed $resizewidth and $resizeheight.
 3210:  
 3211: sub resizeImage {
 3212:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3213:     my $ima = Image::Magick->new;
 3214:     my $resized;
 3215:     if (-e $img_path) {
 3216:         $ima->Read($img_path);
 3217:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3218:             my $width = $ima->Get('width');
 3219:             my $height = $ima->Get('height');
 3220:             if ($width > $resizewidth) {
 3221: 	        my $factor = $width/$resizewidth;
 3222:                 my $newheight = $height/$factor;
 3223:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3224:                 $resized = 1;
 3225:             }
 3226:         }
 3227:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3228:             my $width = $ima->Get('width');
 3229:             my $height = $ima->Get('height');
 3230:             if ($height > $resizeheight) {
 3231:                 my $factor = $height/$resizeheight;
 3232:                 my $newwidth = $width/$factor;
 3233:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3234:                 $resized = 1;
 3235:             }
 3236:         }
 3237:         if ($resized) {
 3238:             $ima->Write($img_path);
 3239:         }
 3240:     }
 3241:     return;
 3242: }
 3243: 
 3244: # --------------- Take an uploaded file and put it into the userfiles directory
 3245: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3246: #                    the desired filename is in $env{"form.$formname.filename"}
 3247: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3248: #                                    canceloverwrite, or ''. 
 3249: #                   if 'coursedoc': upload to the current course
 3250: #                   if 'existingfile': write file to tmp/overwrites directory 
 3251: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3252: #                   $context is passed as argument to &finishuserfileupload
 3253: #        $subdir - directory in userfile to store the file into
 3254: #        $parser - instruction to parse file for objects ($parser = parse)    
 3255: #        $allfiles - reference to hash for embedded objects
 3256: #        $codebase - reference to hash for codebase of java objects
 3257: #        $desuname - username for permanent storage of uploaded file
 3258: #        $dsetudom - domain for permanaent storage of uploaded file
 3259: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3260: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3261: #        $resizewidth - width (pixels) to which to resize uploaded image
 3262: #        $resizeheight - height (pixels) to which to resize uploaded image
 3263: #        $mimetype - reference to scalar to accommodate mime type determined
 3264: #                    from File::MMagic.
 3265: # 
 3266: # output: url of file in userspace, or error: <message> 
 3267: #             or /adm/notfound.html if failure to upload occurse
 3268: 
 3269: sub userfileupload {
 3270:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3271:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3272:     if (!defined($subdir)) { $subdir='unknown'; }
 3273:     my $fname=$env{'form.'.$formname.'.filename'};
 3274:     $fname=&clean_filename($fname);
 3275:     # See if there is anything left
 3276:     unless ($fname) { return 'error: no uploaded file'; }
 3277:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3278:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3279:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3280:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3281:         my $now = time;
 3282:         my $filepath;
 3283:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3284:              $filepath = 'tmp/helprequests/'.$now;
 3285:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3286:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3287:                          '_'.$env{'user.domain'}.'/pending';
 3288:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3289:             my ($docuname,$docudom);
 3290:             if ($destudom) {
 3291:                 $docudom = $destudom;
 3292:             } else {
 3293:                 $docudom = $env{'user.domain'};
 3294:             }
 3295:             if ($destuname) {
 3296:                 $docuname = $destuname;
 3297:             } else {
 3298:                 $docuname = $env{'user.name'};
 3299:             }
 3300:             if (exists($env{'form.group'})) {
 3301:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3302:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3303:             }
 3304:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3305:             if ($context eq 'canceloverwrite') {
 3306:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3307:                 if (-e  $tempfile) {
 3308:                     my @info = stat($tempfile);
 3309:                     if ($info[9] eq $env{'form.timestamp'}) {
 3310:                         unlink($tempfile);
 3311:                     }
 3312:                 }
 3313:                 return;
 3314:             }
 3315:         }
 3316:         # Create the directory if not present
 3317:         my @parts=split(/\//,$filepath);
 3318:         my $fullpath = $perlvar{'lonDaemons'};
 3319:         for (my $i=0;$i<@parts;$i++) {
 3320:             $fullpath .= '/'.$parts[$i];
 3321:             if ((-e $fullpath)!=1) {
 3322:                 mkdir($fullpath,0777);
 3323:             }
 3324:         }
 3325:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3326:         print $fh $env{'form.'.$formname};
 3327:         close($fh);
 3328:         if ($context eq 'existingfile') {
 3329:             my @info = stat($fullpath.'/'.$fname);
 3330:             return ($fullpath.'/'.$fname,$info[9]);
 3331:         } else {
 3332:             return $fullpath.'/'.$fname;
 3333:         }
 3334:     }
 3335:     if ($subdir eq 'scantron') {
 3336:         $fname = 'scantron_orig_'.$fname;
 3337:     } else {
 3338:         $fname="$subdir/$fname";
 3339:     }
 3340:     if ($context eq 'coursedoc') {
 3341: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3342: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3343:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3344:             return &finishuserfileupload($docuname,$docudom,
 3345: 					 $formname,$fname,$parser,$allfiles,
 3346: 					 $codebase,$thumbwidth,$thumbheight,
 3347:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3348:         } else {
 3349:             if ($env{'form.folder'}) {
 3350:                 $fname=$env{'form.folder'}.'/'.$fname;
 3351:             }
 3352:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3353: 				       $fname,$formname,$parser,
 3354: 				       $allfiles,$codebase,$mimetype);
 3355:         }
 3356:     } elsif (defined($destuname)) {
 3357:         my $docuname=$destuname;
 3358:         my $docudom=$destudom;
 3359: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3360: 				     $parser,$allfiles,$codebase,
 3361:                                      $thumbwidth,$thumbheight,
 3362:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3363:     } else {
 3364:         my $docuname=$env{'user.name'};
 3365:         my $docudom=$env{'user.domain'};
 3366:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3367:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3368:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3369:         }
 3370: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3371: 				     $parser,$allfiles,$codebase,
 3372:                                      $thumbwidth,$thumbheight,
 3373:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3374:     }
 3375: }
 3376: 
 3377: sub finishuserfileupload {
 3378:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3379:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3380:     my $path=$docudom.'/'.$docuname.'/';
 3381:     my $filepath=$perlvar{'lonDocRoot'};
 3382:   
 3383:     my ($fnamepath,$file,$fetchthumb);
 3384:     $file=$fname;
 3385:     if ($fname=~m|/|) {
 3386:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3387: 	$path.=$fnamepath.'/';
 3388:     }
 3389:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3390:     my $count;
 3391:     for ($count=4;$count<=$#parts;$count++) {
 3392:         $filepath.="/$parts[$count]";
 3393:         if ((-e $filepath)!=1) {
 3394: 	    mkdir($filepath,0777);
 3395:         }
 3396:     }
 3397: 
 3398: # Save the file
 3399:     {
 3400: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3401: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3402: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3403: 	    return '/adm/notfound.html';
 3404: 	}
 3405:         if ($context eq 'overwrite') {
 3406:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3407:             my $target = $filepath.'/'.$file;
 3408:             if (-e $source) {
 3409:                 my @info = stat($source);
 3410:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3411:                     unless (&File::Copy::move($source,$target)) {
 3412:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3413:                         return "Moving from $source failed";
 3414:                     }
 3415:                 } else {
 3416:                     return "Temporary file: $source had unexpected date/time for last modification";
 3417:                 }
 3418:             } else {
 3419:                 return "Temporary file: $source missing";
 3420:             }
 3421:         } elsif (!print FH ($env{'form.'.$formname})) {
 3422: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3423: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3424: 	    return '/adm/notfound.html';
 3425: 	}
 3426: 	close(FH);
 3427:         if ($resizewidth && $resizeheight) {
 3428:             my $mm = new File::MMagic;
 3429:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3430:             if ($mime_type =~ m{^image/}) {
 3431: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3432:             }  
 3433: 	}
 3434:     }
 3435:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3436:         if (ref($mimetype)) {
 3437:             if ($$mimetype eq '') {
 3438:                 my $mm = new File::MMagic;
 3439:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3440:                 $$mimetype = $type;
 3441:             }
 3442:         }
 3443:     }
 3444:     if ($parser eq 'parse') {
 3445:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3446:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3447:                                                        $allfiles,$codebase);
 3448:             unless ($parse_result eq 'ok') {
 3449:                 &logthis('Failed to parse '.$filepath.$file.
 3450: 	   	         ' for embedded media: '.$parse_result); 
 3451:             }
 3452:         }
 3453:     }
 3454:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3455:         my $input = $filepath.'/'.$file;
 3456:         my $output = $filepath.'/'.'tn-'.$file;
 3457:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3458:         system("convert -sample $thumbsize $input $output");
 3459:         if (-e $filepath.'/'.'tn-'.$file) {
 3460:             $fetchthumb  = 1; 
 3461:         }
 3462:     }
 3463:  
 3464: # Notify homeserver to grep it
 3465: #
 3466:     my $docuhome=&homeserver($docuname,$docudom);	
 3467:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3468:     if ($fetchresult eq 'ok') {
 3469:         if ($fetchthumb) {
 3470:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3471:             if ($thumbresult ne 'ok') {
 3472:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3473:                          $docuhome.': '.$thumbresult);
 3474:             }
 3475:         }
 3476: #
 3477: # Return the URL to it
 3478:         return '/uploaded/'.$path.$file;
 3479:     } else {
 3480:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3481: 		 ': '.$fetchresult);
 3482:         return '/adm/notfound.html';
 3483:     }
 3484: }
 3485: 
 3486: sub extract_embedded_items {
 3487:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3488:     my @state = ();
 3489:     my (%lastids,%related,%shockwave,%flashvars);
 3490:     my %javafiles = (
 3491:                       codebase => '',
 3492:                       code => '',
 3493:                       archive => ''
 3494:                     );
 3495:     my %mediafiles = (
 3496:                       src => '',
 3497:                       movie => '',
 3498:                      );
 3499:     my $p;
 3500:     if ($content) {
 3501:         $p = HTML::LCParser->new($content);
 3502:     } else {
 3503:         $p = HTML::LCParser->new($fullpath);
 3504:     }
 3505:     while (my $t=$p->get_token()) {
 3506: 	if ($t->[0] eq 'S') {
 3507: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3508: 	    push(@state, $tagname);
 3509:             if (lc($tagname) eq 'allow') {
 3510:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3511:             }
 3512: 	    if (lc($tagname) eq 'img') {
 3513: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3514: 	    }
 3515: 	    if (lc($tagname) eq 'a') {
 3516:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3517:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3518:                 }
 3519: 	    }
 3520:             if (lc($tagname) eq 'script') {
 3521:                 my $src;
 3522:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3523:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3524:                 } else {
 3525:                     if ($attr->{'src'} ne '') {
 3526:                         $src = $attr->{'src'};
 3527:                         &add_filetype($allfiles,$src,'src');
 3528:                     }
 3529:                 }
 3530:                 my $text = $p->get_trimmed_text();
 3531:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3532:                     my @swfargs = split(/,/,$1);
 3533:                     foreach my $item (@swfargs) {
 3534:                         $item =~ s/["']//g;
 3535:                         $item =~ s/^\s+//;
 3536:                         $item =~ s/\s+$//;
 3537:                     }
 3538:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3539:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3540:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3541:                         } else {
 3542:                             $related{$swfargs[0]} = [$swfargs[2]];
 3543:                         }
 3544:                     }
 3545:                 }
 3546:             }
 3547:             if (lc($tagname) eq 'link') {
 3548:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3549:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3550:                 }
 3551:             }
 3552: 	    if (lc($tagname) eq 'object' ||
 3553: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3554: 		foreach my $item (keys(%javafiles)) {
 3555: 		    $javafiles{$item} = '';
 3556: 		}
 3557:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3558:                     $lastids{lc($tagname)} = $attr->{'id'};
 3559:                 }
 3560: 	    }
 3561: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3562: 		my $name = lc($attr->{'name'});
 3563: 		foreach my $item (keys(%javafiles)) {
 3564: 		    if ($name eq $item) {
 3565: 			$javafiles{$item} = $attr->{'value'};
 3566: 			last;
 3567: 		    }
 3568: 		}
 3569:                 my $pathfrom;
 3570: 		foreach my $item (keys(%mediafiles)) {
 3571: 		    if ($name eq $item) {
 3572:                         $pathfrom = $attr->{'value'};
 3573:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3574: 			&add_filetype($allfiles,$pathfrom,$name);
 3575: 			last;
 3576: 		    }
 3577: 		}
 3578:                 if ($name eq 'flashvars') {
 3579:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3580:                 }
 3581:                 if ($pathfrom ne '') {
 3582:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3583:                                          $pathfrom);
 3584:                 }
 3585: 	    }
 3586: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3587: 		foreach my $item (keys(%javafiles)) {
 3588: 		    if ($attr->{$item}) {
 3589: 			$javafiles{$item} = $attr->{$item};
 3590: 			last;
 3591: 		    }
 3592: 		}
 3593: 		foreach my $item (keys(%mediafiles)) {
 3594: 		    if ($attr->{$item}) {
 3595: 			&add_filetype($allfiles,$attr->{$item},$item);
 3596: 			last;
 3597: 		    }
 3598: 		}
 3599:                 if (lc($tagname) eq 'embed') {
 3600:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3601:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3602:                                              $attr->{'src'});
 3603:                     }
 3604:                 }
 3605: 	    }
 3606:             if (lc($tagname) eq 'iframe') {
 3607:                 my $src = $attr->{'src'} ;
 3608:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3609:                     &add_filetype($allfiles,$src,'src');
 3610:                 } elsif ($src =~ m{^/}) {
 3611:                     if ($env{'request.course.id'}) {
 3612:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3613:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3614:                         my $url = &hreflocation('',$fullpath);
 3615:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3616:                             my $relpath = $1;
 3617:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3618:                                 &add_filetype($allfiles,$1,'src');
 3619:                             }
 3620:                         }
 3621:                     }
 3622:                 }
 3623:             }
 3624:             if ($t->[4] =~ m{/>$}) {
 3625:                 pop(@state);
 3626:             }
 3627: 	} elsif ($t->[0] eq 'E') {
 3628: 	    my ($tagname) = ($t->[1]);
 3629: 	    if ($javafiles{'codebase'} ne '') {
 3630: 		$javafiles{'codebase'} .= '/';
 3631: 	    }  
 3632: 	    if (lc($tagname) eq 'applet' ||
 3633: 		lc($tagname) eq 'object' ||
 3634: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3635: 		) {
 3636: 		foreach my $item (keys(%javafiles)) {
 3637: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3638: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3639: 			&add_filetype($allfiles,$file,$item);
 3640: 		    }
 3641: 		}
 3642: 	    } 
 3643: 	    pop @state;
 3644: 	}
 3645:     }
 3646:     foreach my $id (sort(keys(%flashvars))) {
 3647:         if ($shockwave{$id} ne '') {
 3648:             my @pairs = split(/\&/,$flashvars{$id});
 3649:             foreach my $pair (@pairs) {
 3650:                 my ($key,$value) = split(/\=/,$pair);
 3651:                 if ($key eq 'thumb') {
 3652:                     &add_filetype($allfiles,$value,$key);
 3653:                 } elsif ($key eq 'content') {
 3654:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3655:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3656:                     if ($ext ne '') {
 3657:                         &add_filetype($allfiles,$path.$value,$ext);
 3658:                     }
 3659:                 }
 3660:             }
 3661:         }
 3662:     }
 3663:     return 'ok';
 3664: }
 3665: 
 3666: sub add_filetype {
 3667:     my ($allfiles,$file,$type)=@_;
 3668:     if (exists($allfiles->{$file})) {
 3669: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3670: 	    push(@{$allfiles->{$file}}, &escape($type));
 3671: 	}
 3672:     } else {
 3673: 	@{$allfiles->{$file}} = (&escape($type));
 3674:     }
 3675: }
 3676: 
 3677: sub embedded_dependency {
 3678:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3679:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3680:         if (($identifier ne '') &&
 3681:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3682:             ($pathfrom ne '')) {
 3683:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3684:             foreach my $dep (@{$related->{$identifier}}) {
 3685:                 &add_filetype($allfiles,$path.$dep,'object');
 3686:             }
 3687:         }
 3688:     }
 3689:     return;
 3690: }
 3691: 
 3692: sub removeuploadedurl {
 3693:     my ($url)=@_;	
 3694:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3695:     return &removeuserfile($uname,$udom,$fname);
 3696: }
 3697: 
 3698: sub removeuserfile {
 3699:     my ($docuname,$docudom,$fname)=@_;
 3700:     my $home=&homeserver($docuname,$docudom);    
 3701:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3702:     if ($result eq 'ok') {	
 3703:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3704:             my $metafile = $fname.'.meta';
 3705:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3706: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3707:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3708:             my $sqlresult = 
 3709:                 &update_portfolio_table($docuname,$docudom,$file,
 3710:                                         'portfolio_metadata',$group,
 3711:                                         'delete');
 3712:         }
 3713:     }
 3714:     return $result;
 3715: }
 3716: 
 3717: sub mkdiruserfile {
 3718:     my ($docuname,$docudom,$dir)=@_;
 3719:     my $home=&homeserver($docuname,$docudom);
 3720:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3721: }
 3722: 
 3723: sub renameuserfile {
 3724:     my ($docuname,$docudom,$old,$new)=@_;
 3725:     my $home=&homeserver($docuname,$docudom);
 3726:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3727:                         &escape("$old").':'.&escape("$new"),$home);
 3728:     if ($result eq 'ok') {
 3729:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3730:             my $oldmeta = $old.'.meta';
 3731:             my $newmeta = $new.'.meta';
 3732:             my $metaresult = 
 3733:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3734: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3735:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3736:             my $sqlresult = 
 3737:                 &update_portfolio_table($docuname,$docudom,$file,
 3738:                                         'portfolio_metadata',$group,
 3739:                                         'delete');
 3740:         }
 3741:     }
 3742:     return $result;
 3743: }
 3744: 
 3745: # ------------------------------------------------------------------------- Log
 3746: 
 3747: sub log {
 3748:     my ($dom,$nam,$hom,$what)=@_;
 3749:     return critical("log:$dom:$nam:$what",$hom);
 3750: }
 3751: 
 3752: # ------------------------------------------------------------------ Course Log
 3753: #
 3754: # This routine flushes several buffers of non-mission-critical nature
 3755: #
 3756: 
 3757: sub flushcourselogs {
 3758:     &logthis('Flushing log buffers');
 3759: #
 3760: # course logs
 3761: # This is a log of all transactions in a course, which can be used
 3762: # for data mining purposes
 3763: #
 3764: # It also collects the courseid database, which lists last transaction
 3765: # times and course titles for all courseids
 3766: #
 3767:     my %courseidbuffer=();
 3768:     foreach my $crsid (keys(%courselogs)) {
 3769:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3770: 		          &escape($courselogs{$crsid}),
 3771: 		          $coursehombuf{$crsid}) eq 'ok') {
 3772: 	    delete $courselogs{$crsid};
 3773:         } else {
 3774:             &logthis('Failed to flush log buffer for '.$crsid);
 3775:             if (length($courselogs{$crsid})>40000) {
 3776:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3777:                         " exceeded maximum size, deleting.</font>");
 3778:                delete $courselogs{$crsid};
 3779:             }
 3780:         }
 3781:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3782:             'description' => $coursedescrbuf{$crsid},
 3783:             'inst_code'    => $courseinstcodebuf{$crsid},
 3784:             'type'        => $coursetypebuf{$crsid},
 3785:             'owner'       => $courseownerbuf{$crsid},
 3786:         };
 3787:     }
 3788: #
 3789: # Write course id database (reverse lookup) to homeserver of courses 
 3790: # Is used in pickcourse
 3791: #
 3792:     foreach my $crs_home (keys(%courseidbuffer)) {
 3793:         my $response = &courseidput(&host_domain($crs_home),
 3794:                                     $courseidbuffer{$crs_home},
 3795:                                     $crs_home,'timeonly');
 3796:     }
 3797: #
 3798: # File accesses
 3799: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3800: #
 3801:     foreach my $entry (keys(%accesshash)) {
 3802:         if ($entry =~ /___count$/) {
 3803:             my ($dom,$name);
 3804:             ($dom,$name,undef)=
 3805: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3806:             if (! defined($dom) || $dom eq '' || 
 3807:                 ! defined($name) || $name eq '') {
 3808:                 my $cid = $env{'request.course.id'};
 3809:                 $dom  = $env{'request.'.$cid.'.domain'};
 3810:                 $name = $env{'request.'.$cid.'.num'};
 3811:             }
 3812:             my $value = $accesshash{$entry};
 3813:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3814:             my %temphash=($url => $value);
 3815:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3816:             if ($result eq 'ok') {
 3817:                 delete $accesshash{$entry};
 3818:             }
 3819:         } else {
 3820:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3821:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3822:             my %temphash=($entry => $accesshash{$entry});
 3823:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3824:                 delete $accesshash{$entry};
 3825:             }
 3826:         }
 3827:     }
 3828: #
 3829: # Roles
 3830: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3831: #
 3832:     foreach my $entry (keys(%userrolehash)) {
 3833:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3834: 	    split(/\:/,$entry);
 3835:         if (&Apache::lonnet::put('nohist_userroles',
 3836:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3837:                 $rudom,$runame) eq 'ok') {
 3838: 	    delete $userrolehash{$entry};
 3839:         }
 3840:     }
 3841: #
 3842: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3843: #
 3844:     my %domrolebuffer = ();
 3845:     foreach my $entry (keys(%domainrolehash)) {
 3846:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3847:         if ($domrolebuffer{$rudom}) {
 3848:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3849:                       '='.&escape($domainrolehash{$entry});
 3850:         } else {
 3851:             $domrolebuffer{$rudom}.=&escape($entry).
 3852:                       '='.&escape($domainrolehash{$entry});
 3853:         }
 3854:         delete $domainrolehash{$entry};
 3855:     }
 3856:     foreach my $dom (keys(%domrolebuffer)) {
 3857: 	my %servers = &get_servers($dom,'library');
 3858: 	foreach my $tryserver (keys(%servers)) {
 3859: 	    unless (&reply('domroleput:'.$dom.':'.
 3860: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3861: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3862: 	    }
 3863:         }
 3864:     }
 3865:     $dumpcount++;
 3866: }
 3867: 
 3868: sub courselog {
 3869:     my $what=shift;
 3870:     $what=time.':'.$what;
 3871:     unless ($env{'request.course.id'}) { return ''; }
 3872:     $coursedombuf{$env{'request.course.id'}}=
 3873:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3874:     $coursenumbuf{$env{'request.course.id'}}=
 3875:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3876:     $coursehombuf{$env{'request.course.id'}}=
 3877:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3878:     $coursedescrbuf{$env{'request.course.id'}}=
 3879:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3880:     $courseinstcodebuf{$env{'request.course.id'}}=
 3881:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3882:     $courseownerbuf{$env{'request.course.id'}}=
 3883:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3884:     $coursetypebuf{$env{'request.course.id'}}=
 3885:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3886:     if (defined $courselogs{$env{'request.course.id'}}) {
 3887: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3888:     } else {
 3889: 	$courselogs{$env{'request.course.id'}}.=$what;
 3890:     }
 3891:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3892: 	&flushcourselogs();
 3893:     }
 3894: }
 3895: 
 3896: sub courseacclog {
 3897:     my $fnsymb=shift;
 3898:     unless ($env{'request.course.id'}) { return ''; }
 3899:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3900:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3901:         $what.=':POST';
 3902:         # FIXME: Probably ought to escape things....
 3903: 	foreach my $key (keys(%env)) {
 3904:             if ($key=~/^form\.(.*)/) {
 3905:                 my $formitem = $1;
 3906:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3907:                     $what.=':'.$formitem.'='.$env{$key};
 3908:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3909:                     $what.=':'.$formitem.'='.$env{$key};
 3910:                 }
 3911:             }
 3912:         }
 3913:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3914:         # FIXME: We should not be depending on a form parameter that someone
 3915:         # editing lonsearchcat.pm might change in the future.
 3916:         if ($env{'form.phase'} eq 'course_search') {
 3917:             $what.= ':POST';
 3918:             # FIXME: Probably ought to escape things....
 3919:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3920:                                  'crsdiscuss') {
 3921:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3922:             }
 3923:         }
 3924:     }
 3925:     &courselog($what);
 3926: }
 3927: 
 3928: sub countacc {
 3929:     my $url=&declutter(shift);
 3930:     return if (! defined($url) || $url eq '');
 3931:     unless ($env{'request.course.id'}) { return ''; }
 3932: #
 3933: # Mark that this url was used in this course
 3934: #
 3935:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3936: #
 3937: # Increase the access count for this resource in this child process
 3938: #
 3939:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3940:     $accesshash{$key}++;
 3941: }
 3942: 
 3943: sub linklog {
 3944:     my ($from,$to)=@_;
 3945:     $from=&declutter($from);
 3946:     $to=&declutter($to);
 3947:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3948:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3949: }
 3950: 
 3951: sub statslog {
 3952:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3953:     if ($users<2) { return; }
 3954:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3955:             'course'       => $env{'request.course.id'},
 3956:             'sections'     => '"all"',
 3957:             'num_students' => $users,
 3958:             'part'         => $part,
 3959:             'symb'         => $symb,
 3960:             'mean_tries'   => $av_attempts,
 3961:             'deg_of_diff'  => $degdiff});
 3962:     foreach my $key (keys(%dynstore)) {
 3963:         $accesshash{$key}=$dynstore{$key};
 3964:     }
 3965: }
 3966:   
 3967: sub userrolelog {
 3968:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3969:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3970:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3971:        $userrolehash
 3972:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3973:                     =$tend.':'.$tstart;
 3974:     }
 3975:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3976:        $userrolehash
 3977:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3978:                     =$tend.':'.$tstart;
 3979:     }
 3980:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3981:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3982:        $domainrolehash
 3983:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3984:                     = $tend.':'.$tstart;
 3985:     }
 3986: }
 3987: 
 3988: sub courserolelog {
 3989:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3990:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3991:         my $cdom = $1;
 3992:         my $cnum = $2;
 3993:         my $sec = $3;
 3994:         my $namespace = 'rolelog';
 3995:         my %storehash = (
 3996:                            role    => $trole,
 3997:                            start   => $tstart,
 3998:                            end     => $tend,
 3999:                            selfenroll => $selfenroll,
 4000:                            context    => $context,
 4001:                         );
 4002:         if ($trole eq 'gr') {
 4003:             $namespace = 'groupslog';
 4004:             $storehash{'group'} = $sec;
 4005:         } else {
 4006:             $storehash{'section'} = $sec;
 4007:         }
 4008:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4009:                    $domain,$cnum,$cdom);
 4010:         if (($trole ne 'st') || ($sec ne '')) {
 4011:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4012:         }
 4013:     }
 4014:     return;
 4015: }
 4016: 
 4017: sub domainrolelog {
 4018:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4019:     if ($area =~ m{^/($match_domain)/$}) {
 4020:         my $cdom = $1;
 4021:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4022:         my $namespace = 'rolelog';
 4023:         my %storehash = (
 4024:                            role    => $trole,
 4025:                            start   => $tstart,
 4026:                            end     => $tend,
 4027:                            context => $context,
 4028:                         );
 4029:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4030:                    $domain,$domconfiguser,$cdom);
 4031:     }
 4032:     return;
 4033: 
 4034: }
 4035: 
 4036: sub coauthorrolelog {
 4037:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4038:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4039:         my $audom = $1;
 4040:         my $auname = $2;
 4041:         my $namespace = 'rolelog';
 4042:         my %storehash = (
 4043:                            role    => $trole,
 4044:                            start   => $tstart,
 4045:                            end     => $tend,
 4046:                            context => $context,
 4047:                         );
 4048:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4049:                    $domain,$auname,$audom);
 4050:     }
 4051:     return;
 4052: }
 4053: 
 4054: sub get_course_adv_roles {
 4055:     my ($cid,$codes) = @_;
 4056:     $cid=$env{'request.course.id'} unless (defined($cid));
 4057:     my %coursehash=&coursedescription($cid);
 4058:     my $crstype = &Apache::loncommon::course_type($cid);
 4059:     my %nothide=();
 4060:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4061:         if ($user !~ /:/) {
 4062: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4063:         } else {
 4064:             $nothide{$user}=1;
 4065:         }
 4066:     }
 4067:     my @possdoms = ($coursehash{'domain'});
 4068:     if ($coursehash{'checkforpriv'}) {
 4069:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4070:     }
 4071:     my %returnhash=();
 4072:     my %dumphash=
 4073:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4074:     my $now=time;
 4075:     my %privileged;
 4076:     foreach my $entry (keys(%dumphash)) {
 4077: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4078:         if (($tstart) && ($tstart<0)) { next; }
 4079:         if (($tend) && ($tend<$now)) { next; }
 4080:         if (($tstart) && ($now<$tstart)) { next; }
 4081:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4082: 	if ($username eq '' || $domain eq '') { next; }
 4083:         if ((&privileged($username,$domain,\@possdoms)) &&
 4084:             (!$nothide{$username.':'.$domain})) { next; }
 4085: 	if ($role eq 'cr') { next; }
 4086:         if ($codes) {
 4087:             if ($section) { $role .= ':'.$section; }
 4088:             if ($returnhash{$role}) {
 4089:                 $returnhash{$role}.=','.$username.':'.$domain;
 4090:             } else {
 4091:                 $returnhash{$role}=$username.':'.$domain;
 4092:             }
 4093:         } else {
 4094:             my $key=&plaintext($role,$crstype);
 4095:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4096:             if ($returnhash{$key}) {
 4097: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4098:             } else {
 4099:                 $returnhash{$key}=$username.':'.$domain;
 4100:             }
 4101:         }
 4102:     }
 4103:     return %returnhash;
 4104: }
 4105: 
 4106: sub get_my_roles {
 4107:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4108:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4109:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4110:     my (%dumphash,%nothide);
 4111:     if ($context eq 'userroles') {
 4112:         %dumphash = &dump('roles',$udom,$uname);
 4113:     } else {
 4114:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4115:         if ($hidepriv) {
 4116:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4117:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4118:                 if ($user !~ /:/) {
 4119:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4120:                 } else {
 4121:                     $nothide{$user} = 1;
 4122:                 }
 4123:             }
 4124:         }
 4125:     }
 4126:     my %returnhash=();
 4127:     my $now=time;
 4128:     my %privileged;
 4129:     foreach my $entry (keys(%dumphash)) {
 4130:         my ($role,$tend,$tstart);
 4131:         if ($context eq 'userroles') {
 4132:             next if ($entry =~ /^rolesdef/);
 4133: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4134:         } else {
 4135:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4136:         }
 4137:         if (($tstart) && ($tstart<0)) { next; }
 4138:         my $status = 'active';
 4139:         if (($tend) && ($tend<=$now)) {
 4140:             $status = 'previous';
 4141:         } 
 4142:         if (($tstart) && ($now<$tstart)) {
 4143:             $status = 'future';
 4144:         }
 4145:         if (ref($types) eq 'ARRAY') {
 4146:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4147:                 next;
 4148:             } 
 4149:         } else {
 4150:             if ($status ne 'active') {
 4151:                 next;
 4152:             }
 4153:         }
 4154:         my ($rolecode,$username,$domain,$section,$area);
 4155:         if ($context eq 'userroles') {
 4156:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4157:             (undef,$domain,$username,$section) = split(/\//,$area);
 4158:         } else {
 4159:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4160:         }
 4161:         if (ref($roledoms) eq 'ARRAY') {
 4162:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4163:                 next;
 4164:             }
 4165:         }
 4166:         if (ref($roles) eq 'ARRAY') {
 4167:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4168:                 if ($role =~ /^cr\//) {
 4169:                     if (!grep(/^cr$/,@{$roles})) {
 4170:                         next;
 4171:                     }
 4172:                 } elsif ($role =~ /^gr\//) {
 4173:                     if (!grep(/^gr$/,@{$roles})) {
 4174:                         next;
 4175:                     }
 4176:                 } else {
 4177:                     next;
 4178:                 }
 4179:             }
 4180:         }
 4181:         if ($hidepriv) {
 4182:             my @privroles = ('dc','su');
 4183:             if ($context eq 'userroles') {
 4184:                 next if (grep(/^\Q$role\E$/,@privroles));
 4185:             } else {
 4186:                 my $possdoms = [$domain];
 4187:                 if (ref($roledoms) eq 'ARRAY') {
 4188:                    push(@{$possdoms},@{$roledoms}); 
 4189:                 }
 4190:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4191:                     if (!$nothide{$username.':'.$domain}) {
 4192:                         next;
 4193:                     }
 4194:                 }
 4195:             }
 4196:         }
 4197:         if ($withsec) {
 4198:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4199:                 $tstart.':'.$tend;
 4200:         } else {
 4201:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4202:         }
 4203:     }
 4204:     return %returnhash;
 4205: }
 4206: 
 4207: # ----------------------------------------------------- Frontpage Announcements
 4208: #
 4209: #
 4210: 
 4211: sub postannounce {
 4212:     my ($server,$text)=@_;
 4213:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4214:     unless ($text=~/\w/) { $text=''; }
 4215:     return &reply('setannounce:'.&escape($text),$server);
 4216: }
 4217: 
 4218: sub getannounce {
 4219: 
 4220:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4221: 	my $announcement='';
 4222: 	while (my $line = <$fh>) { $announcement .= $line; }
 4223: 	close($fh);
 4224: 	if ($announcement=~/\w/) { 
 4225: 	    return 
 4226:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4227:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4228: 	} else {
 4229: 	    return '';
 4230: 	}
 4231:     } else {
 4232: 	return '';
 4233:     }
 4234: }
 4235: 
 4236: # ---------------------------------------------------------- Course ID routines
 4237: # Deal with domain's nohist_courseid.db files
 4238: #
 4239: 
 4240: sub courseidput {
 4241:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4242:     return unless (ref($storehash) eq 'HASH');
 4243:     my $outcome;
 4244:     if ($caller eq 'timeonly') {
 4245:         my $cids = '';
 4246:         foreach my $item (keys(%$storehash)) {
 4247:             $cids.=&escape($item).'&';
 4248:         }
 4249:         $cids=~s/\&$//;
 4250:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4251:                           $coursehome);       
 4252:     } else {
 4253:         my $items = '';
 4254:         foreach my $item (keys(%$storehash)) {
 4255:             $items.= &escape($item).'='.
 4256:                      &freeze_escape($$storehash{$item}).'&';
 4257:         }
 4258:         $items=~s/\&$//;
 4259:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4260:                           $coursehome);
 4261:     }
 4262:     if ($outcome eq 'unknown_cmd') {
 4263:         my $what;
 4264:         foreach my $cid (keys(%$storehash)) {
 4265:             $what .= &escape($cid).'=';
 4266:             foreach my $item ('description','inst_code','owner','type') {
 4267:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4268:             }
 4269:             $what =~ s/\:$/&/;
 4270:         }
 4271:         $what =~ s/\&$//;  
 4272:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4273:     } else {
 4274:         return $outcome;
 4275:     }
 4276: }
 4277: 
 4278: sub courseiddump {
 4279:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4280:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4281:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4282:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4283:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4284:     my $as_hash = 1;
 4285:     my %returnhash;
 4286:     if (!$domfilter) { $domfilter=''; }
 4287:     my %libserv = &all_library();
 4288:     foreach my $tryserver (keys(%libserv)) {
 4289:         if ( (  $hostidflag == 1 
 4290: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4291: 	     || (!defined($hostidflag)) ) {
 4292: 
 4293: 	    if (($domfilter eq '') ||
 4294: 		(&host_domain($tryserver) eq $domfilter)) {
 4295:                 my $rep;
 4296:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4297:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4298:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4299:                                 &escape($descfilter), &escape($instcodefilter), 
 4300:                                 &escape($ownerfilter), &escape($coursefilter),
 4301:                                 &escape($typefilter), &escape($regexp_ok), 
 4302:                                 $as_hash, &escape($selfenrollonly), 
 4303:                                 &escape($catfilter), $showhidden, $caller, 
 4304:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4305:                                 &escape($createdbefore), &escape($createdafter), 
 4306:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 4307:                                 $reqcrsdom,&escape($reqinstcode))));
 4308:                 } else {
 4309:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4310:                              $sincefilter.':'.&escape($descfilter).':'.
 4311:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4312:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4313:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4314:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4315:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4316:                              &escape($cc_clone).':'.$cloneonly.':'.
 4317:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4318:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 4319:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 4320:                 }
 4321:                      
 4322:                 my @pairs=split(/\&/,$rep);
 4323:                 foreach my $item (@pairs) {
 4324:                     my ($key,$value)=split(/\=/,$item,2);
 4325:                     $key = &unescape($key);
 4326:                     next if ($key =~ /^error: 2 /);
 4327:                     my $result = &thaw_unescape($value);
 4328:                     if (ref($result) eq 'HASH') {
 4329:                         $returnhash{$key}=$result;
 4330:                     } else {
 4331:                         my @responses = split(/:/,$value);
 4332:                         my @items = ('description','inst_code','owner','type');
 4333:                         for (my $i=0; $i<@responses; $i++) {
 4334:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4335:                         }
 4336:                     }
 4337:                 }
 4338:             }
 4339:         }
 4340:     }
 4341:     return %returnhash;
 4342: }
 4343: 
 4344: sub courselastaccess {
 4345:     my ($cdom,$cnum,$hostidref) = @_;
 4346:     my %returnhash;
 4347:     if ($cdom && $cnum) {
 4348:         my $chome = &homeserver($cnum,$cdom);
 4349:         if ($chome ne 'no_host') {
 4350:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4351:             &extract_lastaccess(\%returnhash,$rep);
 4352:         }
 4353:     } else {
 4354:         if (!$cdom) { $cdom=''; }
 4355:         my %libserv = &all_library();
 4356:         foreach my $tryserver (keys(%libserv)) {
 4357:             if (ref($hostidref) eq 'ARRAY') {
 4358:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4359:             } 
 4360:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4361:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4362:                 &extract_lastaccess(\%returnhash,$rep);
 4363:             }
 4364:         }
 4365:     }
 4366:     return %returnhash;
 4367: }
 4368: 
 4369: sub extract_lastaccess {
 4370:     my ($returnhash,$rep) = @_;
 4371:     if (ref($returnhash) eq 'HASH') {
 4372:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4373:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4374:                  $rep eq '') {
 4375:             my @pairs=split(/\&/,$rep);
 4376:             foreach my $item (@pairs) {
 4377:                 my ($key,$value)=split(/\=/,$item,2);
 4378:                 $key = &unescape($key);
 4379:                 next if ($key =~ /^error: 2 /);
 4380:                 $returnhash->{$key} = &thaw_unescape($value);
 4381:             }
 4382:         }
 4383:     }
 4384:     return;
 4385: }
 4386: 
 4387: # ---------------------------------------------------------- DC e-mail
 4388: 
 4389: sub dcmailput {
 4390:     my ($domain,$msgid,$message,$server)=@_;
 4391:     my $status = &Apache::lonnet::critical(
 4392:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4393:        &escape($message),$server);
 4394:     return $status;
 4395: }
 4396: 
 4397: sub dcmaildump {
 4398:     my ($dom,$startdate,$enddate,$senders) = @_;
 4399:     my %returnhash=();
 4400: 
 4401:     if (defined(&domain($dom,'primary'))) {
 4402:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4403:                                                          &escape($enddate).':';
 4404: 	my @esc_senders=map { &escape($_)} @$senders;
 4405: 	$cmd.=&escape(join('&',@esc_senders));
 4406: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4407:             my ($key,$value) = split(/\=/,$line,2);
 4408:             if (($key) && ($value)) {
 4409:                 $returnhash{&unescape($key)} = &unescape($value);
 4410:             }
 4411:         }
 4412:     }
 4413:     return %returnhash;
 4414: }
 4415: # ---------------------------------------------------------- Domain roles
 4416: 
 4417: sub get_domain_roles {
 4418:     my ($dom,$roles,$startdate,$enddate)=@_;
 4419:     if ((!defined($startdate)) || ($startdate eq '')) {
 4420:         $startdate = '.';
 4421:     }
 4422:     if ((!defined($enddate)) || ($enddate eq '')) {
 4423:         $enddate = '.';
 4424:     }
 4425:     my $rolelist;
 4426:     if (ref($roles) eq 'ARRAY') {
 4427:         $rolelist = join('&',@{$roles});
 4428:     }
 4429:     my %personnel = ();
 4430: 
 4431:     my %servers = &get_servers($dom,'library');
 4432:     foreach my $tryserver (keys(%servers)) {
 4433: 	%{$personnel{$tryserver}}=();
 4434: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4435: 					    &escape($startdate).':'.
 4436: 					    &escape($enddate).':'.
 4437: 					    &escape($rolelist), $tryserver))) {
 4438: 	    my ($key,$value) = split(/\=/,$line,2);
 4439: 	    if (($key) && ($value)) {
 4440: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4441: 	    }
 4442: 	}
 4443:     }
 4444:     return %personnel;
 4445: }
 4446: 
 4447: # ----------------------------------------------------------- Interval timing 
 4448: 
 4449: {
 4450: # Caches needed for speedup of navmaps
 4451: # We don't want to cache this for very long at all (5 seconds at most)
 4452: # 
 4453: # The user for whom we cache
 4454: my $cachedkey='';
 4455: # The cached times for this user
 4456: my %cachedtimes=();
 4457: # When this was last done
 4458: my $cachedtime='';
 4459: 
 4460: sub load_all_first_access {
 4461:     my ($uname,$udom)=@_;
 4462:     if (($cachedkey eq $uname.':'.$udom) &&
 4463:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4464:         return;
 4465:     }
 4466:     $cachedtime=time;
 4467:     $cachedkey=$uname.':'.$udom;
 4468:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4469: }
 4470: 
 4471: sub get_first_access {
 4472:     my ($type,$argsymb,$argmap)=@_;
 4473:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4474:     if ($argsymb) { $symb=$argsymb; }
 4475:     my ($map,$id,$res)=&decode_symb($symb);
 4476:     if ($argmap) { $map = $argmap; }
 4477:     if ($type eq 'course') {
 4478: 	$res='course';
 4479:     } elsif ($type eq 'map') {
 4480: 	$res=&symbread($map);
 4481:     } else {
 4482: 	$res=$symb;
 4483:     }
 4484:     &load_all_first_access($uname,$udom);
 4485:     return $cachedtimes{"$courseid\0$res"};
 4486: }
 4487: 
 4488: sub set_first_access {
 4489:     my ($type,$interval)=@_;
 4490:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4491:     my ($map,$id,$res)=&decode_symb($symb);
 4492:     if ($type eq 'course') {
 4493: 	$res='course';
 4494:     } elsif ($type eq 'map') {
 4495: 	$res=&symbread($map);
 4496:     } else {
 4497: 	$res=$symb;
 4498:     }
 4499:     $cachedkey='';
 4500:     my $firstaccess=&get_first_access($type,$symb,$map);
 4501:     if (!$firstaccess) {
 4502:         my $start = time;
 4503: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4504:                           $udom,$uname);
 4505:         if ($putres eq 'ok') {
 4506:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4507:                  $udom,$uname); 
 4508:             &appenv(
 4509:                      {
 4510:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4511:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4512:                      }
 4513:                   );
 4514:         }
 4515:         return $putres;
 4516:     }
 4517:     return 'already_set';
 4518: }
 4519: }
 4520: 
 4521: # --------------------------------------------- Set Expire Date for Spreadsheet
 4522: 
 4523: sub expirespread {
 4524:     my ($uname,$udom,$stype,$usymb)=@_;
 4525:     my $cid=$env{'request.course.id'}; 
 4526:     if ($cid) {
 4527:        my $now=time;
 4528:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4529:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4530:                             $env{'course.'.$cid.'.num'}.
 4531: 	        	    ':nohist_expirationdates:'.
 4532:                             &escape($key).'='.$now,
 4533:                             $env{'course.'.$cid.'.home'})
 4534:     }
 4535:     return 'ok';
 4536: }
 4537: 
 4538: # ----------------------------------------------------- Devalidate Spreadsheets
 4539: 
 4540: sub devalidate {
 4541:     my ($symb,$uname,$udom)=@_;
 4542:     my $cid=$env{'request.course.id'}; 
 4543:     if ($cid) {
 4544:         # delete the stored spreadsheets for
 4545:         # - the student level sheet of this user in course's homespace
 4546:         # - the assessment level sheet for this resource 
 4547:         #   for this user in user's homespace
 4548: 	# - current conditional state info
 4549: 	my $key=$uname.':'.$udom.':';
 4550:         my $status=
 4551: 	    &del('nohist_calculatedsheets',
 4552: 		 [$key.'studentcalc:'],
 4553: 		 $env{'course.'.$cid.'.domain'},
 4554: 		 $env{'course.'.$cid.'.num'})
 4555: 		.' '.
 4556: 	    &del('nohist_calculatedsheets_'.$cid,
 4557: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4558:         unless ($status eq 'ok ok') {
 4559:            &logthis('Could not devalidate spreadsheet '.
 4560:                     $uname.' at '.$udom.' for '.
 4561: 		    $symb.': '.$status);
 4562:         }
 4563: 	&delenv('user.state.'.$cid);
 4564:     }
 4565: }
 4566: 
 4567: sub get_scalar {
 4568:     my ($string,$end) = @_;
 4569:     my $value;
 4570:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4571: 	$value = $1;
 4572:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4573: 	$value = $1;
 4574:     }
 4575:     return &unescape($value);
 4576: }
 4577: 
 4578: sub array2str {
 4579:   my (@array) = @_;
 4580:   my $result=&arrayref2str(\@array);
 4581:   $result=~s/^__ARRAY_REF__//;
 4582:   $result=~s/__END_ARRAY_REF__$//;
 4583:   return $result;
 4584: }
 4585: 
 4586: sub arrayref2str {
 4587:   my ($arrayref) = @_;
 4588:   my $result='__ARRAY_REF__';
 4589:   foreach my $elem (@$arrayref) {
 4590:     if(ref($elem) eq 'ARRAY') {
 4591:       $result.=&arrayref2str($elem).'&';
 4592:     } elsif(ref($elem) eq 'HASH') {
 4593:       $result.=&hashref2str($elem).'&';
 4594:     } elsif(ref($elem)) {
 4595:       #print("Got a ref of ".(ref($elem))." skipping.");
 4596:     } else {
 4597:       $result.=&escape($elem).'&';
 4598:     }
 4599:   }
 4600:   $result=~s/\&$//;
 4601:   $result .= '__END_ARRAY_REF__';
 4602:   return $result;
 4603: }
 4604: 
 4605: sub hash2str {
 4606:   my (%hash) = @_;
 4607:   my $result=&hashref2str(\%hash);
 4608:   $result=~s/^__HASH_REF__//;
 4609:   $result=~s/__END_HASH_REF__$//;
 4610:   return $result;
 4611: }
 4612: 
 4613: sub hashref2str {
 4614:   my ($hashref)=@_;
 4615:   my $result='__HASH_REF__';
 4616:   foreach my $key (sort(keys(%$hashref))) {
 4617:     if (ref($key) eq 'ARRAY') {
 4618:       $result.=&arrayref2str($key).'=';
 4619:     } elsif (ref($key) eq 'HASH') {
 4620:       $result.=&hashref2str($key).'=';
 4621:     } elsif (ref($key)) {
 4622:       $result.='=';
 4623:       #print("Got a ref of ".(ref($key))." skipping.");
 4624:     } else {
 4625: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4626:     }
 4627: 
 4628:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4629:       $result.=&arrayref2str($hashref->{$key}).'&';
 4630:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4631:       $result.=&hashref2str($hashref->{$key}).'&';
 4632:     } elsif(ref($hashref->{$key})) {
 4633:        $result.='&';
 4634:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4635:     } else {
 4636:       $result.=&escape($hashref->{$key}).'&';
 4637:     }
 4638:   }
 4639:   $result=~s/\&$//;
 4640:   $result .= '__END_HASH_REF__';
 4641:   return $result;
 4642: }
 4643: 
 4644: sub str2hash {
 4645:     my ($string)=@_;
 4646:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4647:     return %$hash;
 4648: }
 4649: 
 4650: sub str2hashref {
 4651:   my ($string) = @_;
 4652: 
 4653:   my %hash;
 4654: 
 4655:   if($string !~ /^__HASH_REF__/) {
 4656:       if (! ($string eq '' || !defined($string))) {
 4657: 	  $hash{'error'}='Not hash reference';
 4658:       }
 4659:       return (\%hash, $string);
 4660:   }
 4661: 
 4662:   $string =~ s/^__HASH_REF__//;
 4663: 
 4664:   while($string !~ /^__END_HASH_REF__/) {
 4665:       #key
 4666:       my $key='';
 4667:       if($string =~ /^__HASH_REF__/) {
 4668:           ($key, $string)=&str2hashref($string);
 4669:           if(defined($key->{'error'})) {
 4670:               $hash{'error'}='Bad data';
 4671:               return (\%hash, $string);
 4672:           }
 4673:       } elsif($string =~ /^__ARRAY_REF__/) {
 4674:           ($key, $string)=&str2arrayref($string);
 4675:           if($key->[0] eq 'Array reference error') {
 4676:               $hash{'error'}='Bad data';
 4677:               return (\%hash, $string);
 4678:           }
 4679:       } else {
 4680:           $string =~ s/^(.*?)=//;
 4681: 	  $key=&unescape($1);
 4682:       }
 4683:       $string =~ s/^=//;
 4684: 
 4685:       #value
 4686:       my $value='';
 4687:       if($string =~ /^__HASH_REF__/) {
 4688:           ($value, $string)=&str2hashref($string);
 4689:           if(defined($value->{'error'})) {
 4690:               $hash{'error'}='Bad data';
 4691:               return (\%hash, $string);
 4692:           }
 4693:       } elsif($string =~ /^__ARRAY_REF__/) {
 4694:           ($value, $string)=&str2arrayref($string);
 4695:           if($value->[0] eq 'Array reference error') {
 4696:               $hash{'error'}='Bad data';
 4697:               return (\%hash, $string);
 4698:           }
 4699:       } else {
 4700: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4701:       }
 4702:       $string =~ s/^&//;
 4703: 
 4704:       $hash{$key}=$value;
 4705:   }
 4706: 
 4707:   $string =~ s/^__END_HASH_REF__//;
 4708: 
 4709:   return (\%hash, $string);
 4710: }
 4711: 
 4712: sub str2array {
 4713:     my ($string)=@_;
 4714:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4715:     return @$array;
 4716: }
 4717: 
 4718: sub str2arrayref {
 4719:   my ($string) = @_;
 4720:   my @array;
 4721: 
 4722:   if($string !~ /^__ARRAY_REF__/) {
 4723:       if (! ($string eq '' || !defined($string))) {
 4724: 	  $array[0]='Array reference error';
 4725:       }
 4726:       return (\@array, $string);
 4727:   }
 4728: 
 4729:   $string =~ s/^__ARRAY_REF__//;
 4730: 
 4731:   while($string !~ /^__END_ARRAY_REF__/) {
 4732:       my $value='';
 4733:       if($string =~ /^__HASH_REF__/) {
 4734:           ($value, $string)=&str2hashref($string);
 4735:           if(defined($value->{'error'})) {
 4736:               $array[0] ='Array reference error';
 4737:               return (\@array, $string);
 4738:           }
 4739:       } elsif($string =~ /^__ARRAY_REF__/) {
 4740:           ($value, $string)=&str2arrayref($string);
 4741:           if($value->[0] eq 'Array reference error') {
 4742:               $array[0] ='Array reference error';
 4743:               return (\@array, $string);
 4744:           }
 4745:       } else {
 4746: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4747:       }
 4748:       $string =~ s/^&//;
 4749: 
 4750:       push(@array, $value);
 4751:   }
 4752: 
 4753:   $string =~ s/^__END_ARRAY_REF__//;
 4754: 
 4755:   return (\@array, $string);
 4756: }
 4757: 
 4758: # -------------------------------------------------------------------Temp Store
 4759: 
 4760: sub tmpreset {
 4761:   my ($symb,$namespace,$domain,$stuname) = @_;
 4762:   if (!$symb) {
 4763:     $symb=&symbread();
 4764:     if (!$symb) { $symb= $env{'request.url'}; }
 4765:   }
 4766:   $symb=escape($symb);
 4767: 
 4768:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4769:   $namespace=~s/\//\_/g;
 4770:   $namespace=~s/\W//g;
 4771: 
 4772:   if (!$domain) { $domain=$env{'user.domain'}; }
 4773:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4774:   if ($domain eq 'public' && $stuname eq 'public') {
 4775:       $stuname=$ENV{'REMOTE_ADDR'};
 4776:   }
 4777:   my $path=LONCAPA::tempdir();
 4778:   my %hash;
 4779:   if (tie(%hash,'GDBM_File',
 4780: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4781: 	  &GDBM_WRCREAT(),0640)) {
 4782:     foreach my $key (keys(%hash)) {
 4783:       if ($key=~ /:$symb/) {
 4784: 	delete($hash{$key});
 4785:       }
 4786:     }
 4787:   }
 4788: }
 4789: 
 4790: sub tmpstore {
 4791:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4792: 
 4793:   if (!$symb) {
 4794:     $symb=&symbread();
 4795:     if (!$symb) { $symb= $env{'request.url'}; }
 4796:   }
 4797:   $symb=escape($symb);
 4798: 
 4799:   if (!$namespace) {
 4800:     # I don't think we would ever want to store this for a course.
 4801:     # it seems this will only be used if we don't have a course.
 4802:     #$namespace=$env{'request.course.id'};
 4803:     #if (!$namespace) {
 4804:       $namespace=$env{'request.state'};
 4805:     #}
 4806:   }
 4807:   $namespace=~s/\//\_/g;
 4808:   $namespace=~s/\W//g;
 4809:   if (!$domain) { $domain=$env{'user.domain'}; }
 4810:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4811:   if ($domain eq 'public' && $stuname eq 'public') {
 4812:       $stuname=$ENV{'REMOTE_ADDR'};
 4813:   }
 4814:   my $now=time;
 4815:   my %hash;
 4816:   my $path=LONCAPA::tempdir();
 4817:   if (tie(%hash,'GDBM_File',
 4818: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4819: 	  &GDBM_WRCREAT(),0640)) {
 4820:     $hash{"version:$symb"}++;
 4821:     my $version=$hash{"version:$symb"};
 4822:     my $allkeys=''; 
 4823:     foreach my $key (keys(%$storehash)) {
 4824:       $allkeys.=$key.':';
 4825:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4826:     }
 4827:     $hash{"$version:$symb:timestamp"}=$now;
 4828:     $allkeys.='timestamp';
 4829:     $hash{"$version:keys:$symb"}=$allkeys;
 4830:     if (untie(%hash)) {
 4831:       return 'ok';
 4832:     } else {
 4833:       return "error:$!";
 4834:     }
 4835:   } else {
 4836:     return "error:$!";
 4837:   }
 4838: }
 4839: 
 4840: # -----------------------------------------------------------------Temp Restore
 4841: 
 4842: sub tmprestore {
 4843:   my ($symb,$namespace,$domain,$stuname) = @_;
 4844: 
 4845:   if (!$symb) {
 4846:     $symb=&symbread();
 4847:     if (!$symb) { $symb= $env{'request.url'}; }
 4848:   }
 4849:   $symb=escape($symb);
 4850: 
 4851:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4852: 
 4853:   if (!$domain) { $domain=$env{'user.domain'}; }
 4854:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4855:   if ($domain eq 'public' && $stuname eq 'public') {
 4856:       $stuname=$ENV{'REMOTE_ADDR'};
 4857:   }
 4858:   my %returnhash;
 4859:   $namespace=~s/\//\_/g;
 4860:   $namespace=~s/\W//g;
 4861:   my %hash;
 4862:   my $path=LONCAPA::tempdir();
 4863:   if (tie(%hash,'GDBM_File',
 4864: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4865: 	  &GDBM_READER(),0640)) {
 4866:     my $version=$hash{"version:$symb"};
 4867:     $returnhash{'version'}=$version;
 4868:     my $scope;
 4869:     for ($scope=1;$scope<=$version;$scope++) {
 4870:       my $vkeys=$hash{"$scope:keys:$symb"};
 4871:       my @keys=split(/:/,$vkeys);
 4872:       my $key;
 4873:       $returnhash{"$scope:keys"}=$vkeys;
 4874:       foreach $key (@keys) {
 4875: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4876: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4877:       }
 4878:     }
 4879:     if (!(untie(%hash))) {
 4880:       return "error:$!";
 4881:     }
 4882:   } else {
 4883:     return "error:$!";
 4884:   }
 4885:   return %returnhash;
 4886: }
 4887: 
 4888: # ----------------------------------------------------------------------- Store
 4889: 
 4890: sub store {
 4891:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4892:     my $home='';
 4893: 
 4894:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4895: 
 4896:     $symb=&symbclean($symb);
 4897:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4898: 
 4899:     if (!$domain) { $domain=$env{'user.domain'}; }
 4900:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4901: 
 4902:     &devalidate($symb,$stuname,$domain);
 4903: 
 4904:     $symb=escape($symb);
 4905:     if (!$namespace) { 
 4906:        unless ($namespace=$env{'request.course.id'}) { 
 4907:           return ''; 
 4908:        } 
 4909:     }
 4910:     if (!$home) { $home=$env{'user.home'}; }
 4911: 
 4912:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4913:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4914: 
 4915:     my $namevalue='';
 4916:     foreach my $key (keys(%$storehash)) {
 4917:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4918:     }
 4919:     $namevalue=~s/\&$//;
 4920:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4921:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4922: }
 4923: 
 4924: # -------------------------------------------------------------- Critical Store
 4925: 
 4926: sub cstore {
 4927:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4928:     my $home='';
 4929: 
 4930:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4931: 
 4932:     $symb=&symbclean($symb);
 4933:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4934: 
 4935:     if (!$domain) { $domain=$env{'user.domain'}; }
 4936:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4937: 
 4938:     &devalidate($symb,$stuname,$domain);
 4939: 
 4940:     $symb=escape($symb);
 4941:     if (!$namespace) { 
 4942:        unless ($namespace=$env{'request.course.id'}) { 
 4943:           return ''; 
 4944:        } 
 4945:     }
 4946:     if (!$home) { $home=$env{'user.home'}; }
 4947: 
 4948:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4949:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4950: 
 4951:     my $namevalue='';
 4952:     foreach my $key (keys(%$storehash)) {
 4953:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4954:     }
 4955:     $namevalue=~s/\&$//;
 4956:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4957:     return critical
 4958:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4959: }
 4960: 
 4961: # --------------------------------------------------------------------- Restore
 4962: 
 4963: sub restore {
 4964:     my ($symb,$namespace,$domain,$stuname) = @_;
 4965:     my $home='';
 4966: 
 4967:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4968: 
 4969:     if (!$symb) {
 4970:         return if ($namespace eq 'courserequests');
 4971:         unless ($symb=escape(&symbread())) { return ''; }
 4972:     } else {
 4973:         unless ($namespace eq 'courserequests') {
 4974:             $symb=&escape(&symbclean($symb));
 4975:         }
 4976:     }
 4977:     if (!$namespace) { 
 4978:        unless ($namespace=$env{'request.course.id'}) { 
 4979:           return ''; 
 4980:        } 
 4981:     }
 4982:     if (!$domain) { $domain=$env{'user.domain'}; }
 4983:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4984:     if (!$home) { $home=$env{'user.home'}; }
 4985:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4986: 
 4987:     my %returnhash=();
 4988:     foreach my $line (split(/\&/,$answer)) {
 4989: 	my ($name,$value)=split(/\=/,$line);
 4990:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4991:     }
 4992:     my $version;
 4993:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4994:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4995:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4996:        }
 4997:     }
 4998:     return %returnhash;
 4999: }
 5000: 
 5001: # ---------------------------------------------------------- Course Description
 5002: #
 5003: #  
 5004: 
 5005: sub coursedescription {
 5006:     my ($courseid,$args)=@_;
 5007:     $courseid=~s/^\///;
 5008:     $courseid=~s/\_/\//g;
 5009:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5010:     my $chome=&homeserver($cnum,$cdomain);
 5011:     my $normalid=$cdomain.'_'.$cnum;
 5012:     # need to always cache even if we get errors otherwise we keep 
 5013:     # trying and trying and trying to get the course description.
 5014:     my %envhash=();
 5015:     my %returnhash=();
 5016:     
 5017:     my $expiretime=600;
 5018:     if ($env{'request.course.id'} eq $normalid) {
 5019: 	$expiretime=120;
 5020:     }
 5021: 
 5022:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5023:     if (!$args->{'freshen_cache'}
 5024: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5025: 	foreach my $key (keys(%env)) {
 5026: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5027: 	    my ($setting) = $1;
 5028: 	    $returnhash{$setting} = $env{$key};
 5029: 	}
 5030: 	return %returnhash;
 5031:     }
 5032: 
 5033:     # get the data again
 5034: 
 5035:     if (!$args->{'one_time'}) {
 5036: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5037:     }
 5038: 
 5039:     if ($chome ne 'no_host') {
 5040:        %returnhash=&dump('environment',$cdomain,$cnum);
 5041:        if (!exists($returnhash{'con_lost'})) {
 5042: 	   my $username = $env{'user.name'}; # Defult username
 5043: 	   if(defined $args->{'user'}) {
 5044: 	       $username = $args->{'user'};
 5045: 	   }
 5046:            $returnhash{'home'}= $chome;
 5047: 	   $returnhash{'domain'} = $cdomain;
 5048: 	   $returnhash{'num'} = $cnum;
 5049:            if (!defined($returnhash{'type'})) {
 5050:                $returnhash{'type'} = 'Course';
 5051:            }
 5052:            while (my ($name,$value) = each %returnhash) {
 5053:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5054:            }
 5055:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5056:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5057: 	       $username.'_'.$cdomain.'_'.$cnum;
 5058:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5059:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5060:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5061:        }
 5062:     }
 5063:     if (!$args->{'one_time'}) {
 5064: 	&appenv(\%envhash);
 5065:     }
 5066:     return %returnhash;
 5067: }
 5068: 
 5069: sub update_released_required {
 5070:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5071:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5072:         $cid = $env{'request.course.id'};
 5073:         $cdom = $env{'course.'.$cid.'.domain'};
 5074:         $cnum = $env{'course.'.$cid.'.num'};
 5075:         $chome = $env{'course.'.$cid.'.home'};
 5076:     }
 5077:     if ($needsrelease) {
 5078:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5079:         my $needsupdate;
 5080:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5081:             $needsupdate = 1;
 5082:         } else {
 5083:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5084:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5085:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5086:                 $needsupdate = 1;
 5087:             }
 5088:         }
 5089:         if ($needsupdate) {
 5090:             my %needshash = (
 5091:                              'internal.releaserequired' => $needsrelease,
 5092:                             );
 5093:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5094:             if ($putresult eq 'ok') {
 5095:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5096:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5097:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5098:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5099:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5100:                 }
 5101:             }
 5102:         }
 5103:     }
 5104:     return;
 5105: }
 5106: 
 5107: # -------------------------------------------------See if a user is privileged
 5108: 
 5109: sub privileged {
 5110:     my ($username,$domain,$possdomains,$possroles)=@_;
 5111:     my $now = time;
 5112:     my $roles;
 5113:     if (ref($possroles) eq 'ARRAY') {
 5114:         $roles = $possroles; 
 5115:     } else {
 5116:         $roles = ['dc','su'];
 5117:     }
 5118:     if (ref($possdomains) eq 'ARRAY') {
 5119:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5120:         foreach my $dom (@{$possdomains}) {
 5121:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5122:                 (ref($privileged{$dom}) eq 'HASH')) {
 5123:                 foreach my $role (@{$roles}) {
 5124:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5125:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5126:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5127:                             return 1 unless (($end && $end < $now) ||
 5128:                                              ($start && $start > $now));
 5129:                         }
 5130:                     }
 5131:                 }
 5132:             }
 5133:         }
 5134:     } else {
 5135:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5136:         my $now = time;
 5137: 
 5138:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5139:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5140:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5141:                 return 1 unless ($tend && $tend < $now) 
 5142:                         or ($tstart && $tstart > $now);
 5143:             }
 5144:         }
 5145:     }
 5146:     return 0;
 5147: }
 5148: 
 5149: sub privileged_by_domain {
 5150:     my ($domains,$roles) = @_;
 5151:     my %privileged = ();
 5152:     my $cachetime = 60*60*24;
 5153:     my $now = time;
 5154:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5155:         return %privileged;
 5156:     }
 5157:     foreach my $dom (@{$domains}) {
 5158:         next if (ref($privileged{$dom}) eq 'HASH');
 5159:         my $needroles;
 5160:         foreach my $role (@{$roles}) {
 5161:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5162:             if (defined($cached)) {
 5163:                 if (ref($result) eq 'HASH') {
 5164:                     $privileged{$dom}{$role} = $result;
 5165:                 }
 5166:             } else {
 5167:                 $needroles = 1;
 5168:             }
 5169:         }
 5170:         if ($needroles) {
 5171:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5172:             $privileged{$dom} = {};
 5173:             foreach my $server (keys(%dompersonnel)) {
 5174:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5175:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5176:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5177:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5178:                         next if ($end && $end < $now);
 5179:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5180:                             $dompersonnel{$server}{$item};
 5181:                     }
 5182:                 }
 5183:             }
 5184:             if (ref($privileged{$dom}) eq 'HASH') {
 5185:                 foreach my $role (@{$roles}) {
 5186:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5187:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5188:                     } else {
 5189:                         my %hash = ();
 5190:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5191:                     }
 5192:                 }
 5193:             }
 5194:         }
 5195:     }
 5196:     return %privileged;
 5197: }
 5198: 
 5199: # -------------------------------------------------------- Get user privileges
 5200: 
 5201: sub rolesinit {
 5202:     my ($domain, $username) = @_;
 5203:     my %userroles = ('user.login.time' => time);
 5204:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5205: 
 5206:     # firstaccess and timerinterval are related to timed maps/resources. 
 5207:     # also, blocking can be triggered by an activating timer
 5208:     # it's saved in the user's %env.
 5209:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5210:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5211:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5212:         %timerintchk, %timerintenv);
 5213: 
 5214:     foreach my $key (keys(%firstaccess)) {
 5215:         my ($cid, $rest) = split(/\0/, $key);
 5216:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5217:     }
 5218: 
 5219:     foreach my $key (keys(%timerinterval)) {
 5220:         my ($cid,$rest) = split(/\0/,$key);
 5221:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5222:     }
 5223: 
 5224:     my %allroles=();
 5225:     my %allgroups=();
 5226: 
 5227:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5228:         my $role = $rolesdump{$area};
 5229:         $area =~ s/\_\w\w$//;
 5230: 
 5231:         my ($trole, $tend, $tstart, $group_privs);
 5232: 
 5233:         if ($role =~ /^cr/) {
 5234:         # Custom role, defined by a user 
 5235:         # e.g., user.role.cr/msu/smith/mynewrole
 5236:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5237:                 $trole = $1;
 5238:                 ($tend, $tstart) = split('_', $2);
 5239:             } else {
 5240:                 $trole = $role;
 5241:             }
 5242:         } elsif ($role =~ m|^gr/|) {
 5243:         # Role of member in a group, defined within a course/community
 5244:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5245:             ($trole, $tend, $tstart) = split(/_/, $role);
 5246:             next if $tstart eq '-1';
 5247:             ($trole, $group_privs) = split(/\//, $trole);
 5248:             $group_privs = &unescape($group_privs);
 5249:         } else {
 5250:         # Just a normal role, defined in roles.tab
 5251:             ($trole, $tend, $tstart) = split(/_/,$role);
 5252:         }
 5253: 
 5254:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5255:                  $username);
 5256:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5257: 
 5258:         # role expired or not available yet?
 5259:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5260:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5261: 
 5262:         next if $area eq '' or $trole eq '';
 5263: 
 5264:         my $spec = "$trole.$area";
 5265:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5266: 
 5267:         if ($trole =~ /^cr\//) {
 5268:         # Custom role, defined by a user
 5269:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5270:         } elsif ($trole eq 'gr') {
 5271:         # Role of a member in a group, defined within a course/community
 5272:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5273:             next;
 5274:         } else {
 5275:         # Normal role, defined in roles.tab
 5276:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5277:         }
 5278: 
 5279:         my $cid = $tdomain.'_'.$trest;
 5280:         unless ($firstaccchk{$cid}) {
 5281:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5282:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5283:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5284:                         $coursetimerstarts{$cid}{$item}; 
 5285:                 }
 5286:             }
 5287:             $firstaccchk{$cid} = 1;
 5288:         }
 5289:         unless ($timerintchk{$cid}) {
 5290:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5291:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5292:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5293:                        $coursetimerintervals{$cid}{$item};
 5294:                 }
 5295:             }
 5296:             $timerintchk{$cid} = 1;
 5297:         }
 5298:     }
 5299: 
 5300:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5301:         \%allroles, \%allgroups);
 5302:     $env{'user.adv'} = $userroles{'user.adv'};
 5303: 
 5304:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5305: }
 5306: 
 5307: sub set_arearole {
 5308:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5309:     unless ($nolog) {
 5310: # log the associated role with the area
 5311:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5312:     }
 5313:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5314: }
 5315: 
 5316: sub custom_roleprivs {
 5317:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5318:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5319:     my $homsvr = &homeserver($rauthor,$rdomain);
 5320:     if (&hostname($homsvr) ne '') {
 5321:         my ($rdummy,$roledef)=
 5322:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5323:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5324:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5325:             if (defined($syspriv)) {
 5326:                 if ($trest =~ /^$match_community$/) {
 5327:                     $syspriv =~ s/bre\&S//; 
 5328:                 }
 5329:                 $$allroles{'cm./'}.=':'.$syspriv;
 5330:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5331:             }
 5332:             if ($tdomain ne '') {
 5333:                 if (defined($dompriv)) {
 5334:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5335:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5336:                 }
 5337:                 if (($trest ne '') && (defined($coursepriv))) {
 5338:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5339:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5340:                 }
 5341:             }
 5342:         }
 5343:     }
 5344: }
 5345: 
 5346: sub group_roleprivs {
 5347:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5348:     my $access = 1;
 5349:     my $now = time;
 5350:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5351:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5352:     if ($access) {
 5353:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5354:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5355:     }
 5356: }
 5357: 
 5358: sub standard_roleprivs {
 5359:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5360:     if (defined($pr{$trole.':s'})) {
 5361:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5362:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5363:     }
 5364:     if ($tdomain ne '') {
 5365:         if (defined($pr{$trole.':d'})) {
 5366:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5367:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5368:         }
 5369:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5370:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5371:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5372:         }
 5373:     }
 5374: }
 5375: 
 5376: sub set_userprivs {
 5377:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5378:     my $author=0;
 5379:     my $adv=0;
 5380:     my %grouproles = ();
 5381:     if (keys(%{$allgroups}) > 0) {
 5382:         my @groupkeys; 
 5383:         foreach my $role (keys(%{$allroles})) {
 5384:             push(@groupkeys,$role);
 5385:         }
 5386:         if (ref($groups_roles) eq 'HASH') {
 5387:             foreach my $key (keys(%{$groups_roles})) {
 5388:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5389:                     push(@groupkeys,$key);
 5390:                 }
 5391:             }
 5392:         }
 5393:         if (@groupkeys > 0) {
 5394:             foreach my $role (@groupkeys) {
 5395:                 my ($trole,$area,$sec,$extendedarea);
 5396:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5397:                     $trole = $1;
 5398:                     $area = $2;
 5399:                     $sec = $3;
 5400:                     $extendedarea = $area.$sec;
 5401:                     if (exists($$allgroups{$area})) {
 5402:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5403:                             my $spec = $trole.'.'.$extendedarea;
 5404:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5405:                                                 $$allgroups{$area}{$group};
 5406:                         }
 5407:                     }
 5408:                 }
 5409:             }
 5410:         }
 5411:     }
 5412:     foreach my $group (keys(%grouproles)) {
 5413:         $$allroles{$group} = $grouproles{$group};
 5414:     }
 5415:     foreach my $role (keys(%{$allroles})) {
 5416:         my %thesepriv;
 5417:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5418:         foreach my $item (split(/:/,$$allroles{$role})) {
 5419:             if ($item ne '') {
 5420:                 my ($privilege,$restrictions)=split(/&/,$item);
 5421:                 if ($restrictions eq '') {
 5422:                     $thesepriv{$privilege}='F';
 5423:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5424:                     $thesepriv{$privilege}.=$restrictions;
 5425:                 }
 5426:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5427:             }
 5428:         }
 5429:         my $thesestr='';
 5430:         foreach my $priv (sort(keys(%thesepriv))) {
 5431: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5432: 	}
 5433:         $userroles->{'user.priv.'.$role} = $thesestr;
 5434:     }
 5435:     return ($author,$adv);
 5436: }
 5437: 
 5438: sub role_status {
 5439:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5440:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5441:         my ($one,$two) = split(m{\./},$rolekey,2);
 5442:         (undef,undef,$$role) = split(/\./,$one,3);
 5443:         unless (!defined($$role) || $$role eq '') {
 5444:             $$where = '/'.$two;
 5445:             $$trolecode=$$role.'.'.$$where;
 5446:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5447:             $$tstatus='is';
 5448:             if ($$tstart && $$tstart>$update) {
 5449:                 $$tstatus='future';
 5450:                 if ($$tstart<$now) {
 5451:                     if ($$tstart && $$tstart>$refresh) {
 5452:                         if (($$where ne '') && ($$role ne '')) {
 5453:                             my (%allroles,%allgroups,$group_privs,
 5454:                                 %groups_roles,@rolecodes);
 5455:                             my %userroles = (
 5456:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5457:                             );
 5458:                             @rolecodes = ('cm'); 
 5459:                             my $spec=$$role.'.'.$$where;
 5460:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5461:                             if ($$role =~ /^cr\//) {
 5462:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5463:                                 push(@rolecodes,'cr');
 5464:                             } elsif ($$role eq 'gr') {
 5465:                                 push(@rolecodes,$$role);
 5466:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5467:                                                     $env{'user.name'});
 5468:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5469:                                 (undef,my $group_privs) = split(/\//,$trole);
 5470:                                 $group_privs = &unescape($group_privs);
 5471:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5472:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5473:                                 &get_groups_roles($tdomain,$trest,
 5474:                                                   \%course_roles,\@rolecodes,
 5475:                                                   \%groups_roles);
 5476:                             } else {
 5477:                                 push(@rolecodes,$$role);
 5478:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5479:                             }
 5480:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5481:                             &appenv(\%userroles,\@rolecodes);
 5482:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5483:                         }
 5484:                     }
 5485:                     $$tstatus = 'is';
 5486:                 }
 5487:             }
 5488:             if ($$tend) {
 5489:                 if ($$tend<$update) {
 5490:                     $$tstatus='expired';
 5491:                 } elsif ($$tend<$now) {
 5492:                     $$tstatus='will_not';
 5493:                 }
 5494:             }
 5495:         }
 5496:     }
 5497: }
 5498: 
 5499: sub get_groups_roles {
 5500:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5501:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5502:                   (ref($rolecodes) eq 'ARRAY') && 
 5503:                   (ref($groups_roles) eq 'HASH')); 
 5504:     if (keys(%{$cdom_courseroles}) > 0) {
 5505:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5506:         if ($cdom ne '' && $cnum ne '') {
 5507:             foreach my $key (keys(%{$cdom_courseroles})) {
 5508:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5509:                     my $crsrole = $1;
 5510:                     my $crssec = $2;
 5511:                     if ($crsrole =~ /^cr/) {
 5512:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5513:                             push(@{$rolecodes},'cr');
 5514:                         }
 5515:                     } else {
 5516:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5517:                             push(@{$rolecodes},$crsrole);
 5518:                         }
 5519:                     }
 5520:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5521:                     if ($crssec ne '') {
 5522:                         $rolekey .= "/$crssec";
 5523:                     }
 5524:                     $rolekey .= './';
 5525:                     $groups_roles->{$rolekey} = $rolecodes;
 5526:                 }
 5527:             }
 5528:         }
 5529:     }
 5530:     return;
 5531: }
 5532: 
 5533: sub delete_env_groupprivs {
 5534:     my ($where,$courseroles,$possroles) = @_;
 5535:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5536:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5537:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5538:         %{$courseroles->{$udom}} =
 5539:             &get_my_roles('','','userroles',['active'],
 5540:                           $possroles,[$udom],1);
 5541:     }
 5542:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5543:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5544:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5545:             my $area = '/'.$cdom.'/'.$cnum;
 5546:             my $privkey = "user.priv.$crsrole.$area";
 5547:             if ($crssec ne '') {
 5548:                 $privkey .= '/'.$crssec;
 5549:             }
 5550:             $privkey .= ".$area/$group";
 5551:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5552:         }
 5553:     }
 5554:     return;
 5555: }
 5556: 
 5557: sub check_adhoc_privs {
 5558:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5559:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5560:     my $setprivs;
 5561:     if ($env{$cckey}) {
 5562:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5563:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5564:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5565:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5566:             $setprivs = 1;
 5567:         }
 5568:     } else {
 5569:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5570:         $setprivs = 1;
 5571:     }
 5572:     return $setprivs;
 5573: }
 5574: 
 5575: sub set_adhoc_privileges {
 5576: # role can be cc or ca
 5577:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5578:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5579:     my $spec = $role.'.'.$area;
 5580:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5581:                                   $env{'user.name'},1);
 5582:     my %ccrole = ();
 5583:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5584:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5585:     &appenv(\%userroles,[$role,'cm']);
 5586:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5587:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5588:         &appenv( {'request.role'        => $spec,
 5589:                   'request.role.domain' => $dcdom,
 5590:                   'request.course.sec'  => ''
 5591:                  }
 5592:                );
 5593:         my $tadv=0;
 5594:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5595:         &appenv({'request.role.adv'    => $tadv});
 5596:     }
 5597: }
 5598: 
 5599: # --------------------------------------------------------------- get interface
 5600: 
 5601: sub get {
 5602:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5603:    my $items='';
 5604:    foreach my $item (@$storearr) {
 5605:        $items.=&escape($item).'&';
 5606:    }
 5607:    $items=~s/\&$//;
 5608:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5609:    if (!$uname) { $uname=$env{'user.name'}; }
 5610:    my $uhome=&homeserver($uname,$udomain);
 5611: 
 5612:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5613:    my @pairs=split(/\&/,$rep);
 5614:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5615:      return @pairs;
 5616:    }
 5617:    my %returnhash=();
 5618:    my $i=0;
 5619:    foreach my $item (@$storearr) {
 5620:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5621:       $i++;
 5622:    }
 5623:    return %returnhash;
 5624: }
 5625: 
 5626: # --------------------------------------------------------------- del interface
 5627: 
 5628: sub del {
 5629:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5630:    my $items='';
 5631:    foreach my $item (@$storearr) {
 5632:        $items.=&escape($item).'&';
 5633:    }
 5634: 
 5635:    $items=~s/\&$//;
 5636:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5637:    if (!$uname) { $uname=$env{'user.name'}; }
 5638:    my $uhome=&homeserver($uname,$udomain);
 5639:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5640: }
 5641: 
 5642: # -------------------------------------------------------------- dump interface
 5643: 
 5644: sub unserialize {
 5645:     my ($rep, $escapedkeys) = @_;
 5646: 
 5647:     return {} if $rep =~ /^error/;
 5648: 
 5649:     my %returnhash=();
 5650: 	foreach my $item (split(/\&/,$rep)) {
 5651: 	    my ($key, $value) = split(/=/, $item, 2);
 5652: 	    $key = unescape($key) unless $escapedkeys;
 5653: 	    next if $key =~ /^error: 2 /;
 5654: 	    $returnhash{$key} = &thaw_unescape($value);
 5655: 	}
 5656:     #return %returnhash;
 5657:     return \%returnhash;
 5658: }        
 5659: 
 5660: # see Lond::dump_with_regexp
 5661: # if $escapedkeys hash keys won't get unescaped.
 5662: sub dump {
 5663:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5664:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5665:     if (!$uname) { $uname=$env{'user.name'}; }
 5666:     my $uhome=&homeserver($uname,$udomain);
 5667: 
 5668:     if ($regexp) {
 5669:         $regexp=&escape($regexp);
 5670:     } else {
 5671:         $regexp='.';
 5672:     }
 5673:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5674:         # user is hosted on this machine
 5675:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5676:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5677:         return %{unserialize($reply, $escapedkeys)};
 5678:     }
 5679:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5680:     my @pairs=split(/\&/,$rep);
 5681:     my %returnhash=();
 5682:     if (!($rep =~ /^error/ )) {
 5683: 	foreach my $item (@pairs) {
 5684: 	    my ($key,$value)=split(/=/,$item,2);
 5685:         $key = unescape($key) unless $escapedkeys;
 5686:         #$key = &unescape($key);
 5687: 	    next if ($key =~ /^error: 2 /);
 5688: 	    $returnhash{$key}=&thaw_unescape($value);
 5689: 	}
 5690:     }
 5691:     return %returnhash;
 5692: }
 5693: 
 5694: 
 5695: # --------------------------------------------------------- dumpstore interface
 5696: 
 5697: sub dumpstore {
 5698:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5699:    # same as dump but keys must be escaped. They may contain colon separated
 5700:    # lists of values that may themself contain colons (e.g. symbs).
 5701:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5702: }
 5703: 
 5704: # -------------------------------------------------------------- keys interface
 5705: 
 5706: sub getkeys {
 5707:    my ($namespace,$udomain,$uname)=@_;
 5708:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5709:    if (!$uname) { $uname=$env{'user.name'}; }
 5710:    my $uhome=&homeserver($uname,$udomain);
 5711:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5712:    my @keyarray=();
 5713:    foreach my $key (split(/\&/,$rep)) {
 5714:       next if ($key =~ /^error: 2 /);
 5715:       push(@keyarray,&unescape($key));
 5716:    }
 5717:    return @keyarray;
 5718: }
 5719: 
 5720: # --------------------------------------------------------------- currentdump
 5721: sub currentdump {
 5722:    my ($courseid,$sdom,$sname)=@_;
 5723:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5724:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5725:    $sname    = $env{'user.name'}         if (! defined($sname));
 5726:    my $uhome = &homeserver($sname,$sdom);
 5727:    my $rep;
 5728: 
 5729:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5730:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5731:                    $courseid)));
 5732:    } else {
 5733:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5734:    }
 5735: 
 5736:    return if ($rep =~ /^(error:|no_such_host)/);
 5737:    #
 5738:    my %returnhash=();
 5739:    #
 5740:    if ($rep eq "unknown_cmd") { 
 5741:        # an old lond will not know currentdump
 5742:        # Do a dump and make it look like a currentdump
 5743:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5744:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5745:        my %hash = @tmp;
 5746:        @tmp=();
 5747:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5748:    } else {
 5749:        my @pairs=split(/\&/,$rep);
 5750:        foreach my $pair (@pairs) {
 5751:            my ($key,$value)=split(/=/,$pair,2);
 5752:            my ($symb,$param) = split(/:/,$key);
 5753:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5754:                                                         &thaw_unescape($value);
 5755:        }
 5756:    }
 5757:    return %returnhash;
 5758: }
 5759: 
 5760: sub convert_dump_to_currentdump{
 5761:     my %hash = %{shift()};
 5762:     my %returnhash;
 5763:     # Code ripped from lond, essentially.  The only difference
 5764:     # here is the unescaping done by lonnet::dump().  Conceivably
 5765:     # we might run in to problems with parameter names =~ /^v\./
 5766:     while (my ($key,$value) = each(%hash)) {
 5767:         my ($v,$symb,$param) = split(/:/,$key);
 5768: 	$symb  = &unescape($symb);
 5769: 	$param = &unescape($param);
 5770:         next if ($v eq 'version' || $symb eq 'keys');
 5771:         next if (exists($returnhash{$symb}) &&
 5772:                  exists($returnhash{$symb}->{$param}) &&
 5773:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5774:         $returnhash{$symb}->{$param}=$value;
 5775:         $returnhash{$symb}->{'v.'.$param}=$v;
 5776:     }
 5777:     #
 5778:     # Remove all of the keys in the hashes which keep track of
 5779:     # the version of the parameter.
 5780:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5781:         # use a foreach because we are going to delete from the hash.
 5782:         foreach my $key (keys(%$param_hash)) {
 5783:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5784:         }
 5785:     }
 5786:     return \%returnhash;
 5787: }
 5788: 
 5789: # ------------------------------------------------------ critical inc interface
 5790: 
 5791: sub cinc {
 5792:     return &inc(@_,'critical');
 5793: }
 5794: 
 5795: # --------------------------------------------------------------- inc interface
 5796: 
 5797: sub inc {
 5798:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5799:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5800:     if (!$uname) { $uname=$env{'user.name'}; }
 5801:     my $uhome=&homeserver($uname,$udomain);
 5802:     my $items='';
 5803:     if (! ref($store)) {
 5804:         # got a single value, so use that instead
 5805:         $items = &escape($store).'=&';
 5806:     } elsif (ref($store) eq 'SCALAR') {
 5807:         $items = &escape($$store).'=&';        
 5808:     } elsif (ref($store) eq 'ARRAY') {
 5809:         $items = join('=&',map {&escape($_);} @{$store});
 5810:     } elsif (ref($store) eq 'HASH') {
 5811:         while (my($key,$value) = each(%{$store})) {
 5812:             $items.= &escape($key).'='.&escape($value).'&';
 5813:         }
 5814:     }
 5815:     $items=~s/\&$//;
 5816:     if ($critical) {
 5817: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5818:     } else {
 5819: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5820:     }
 5821: }
 5822: 
 5823: # --------------------------------------------------------------- put interface
 5824: 
 5825: sub put {
 5826:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5827:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5828:    if (!$uname) { $uname=$env{'user.name'}; }
 5829:    my $uhome=&homeserver($uname,$udomain);
 5830:    my $items='';
 5831:    foreach my $item (keys(%$storehash)) {
 5832:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5833:    }
 5834:    $items=~s/\&$//;
 5835:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5836: }
 5837: 
 5838: # ------------------------------------------------------------ newput interface
 5839: 
 5840: sub newput {
 5841:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5842:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5843:    if (!$uname) { $uname=$env{'user.name'}; }
 5844:    my $uhome=&homeserver($uname,$udomain);
 5845:    my $items='';
 5846:    foreach my $key (keys(%$storehash)) {
 5847:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5848:    }
 5849:    $items=~s/\&$//;
 5850:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5851: }
 5852: 
 5853: # ---------------------------------------------------------  putstore interface
 5854: 
 5855: sub putstore {
 5856:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 5857:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5858:    if (!$uname) { $uname=$env{'user.name'}; }
 5859:    my $uhome=&homeserver($uname,$udomain);
 5860:    my $items='';
 5861:    foreach my $key (keys(%$storehash)) {
 5862:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5863:    }
 5864:    $items=~s/\&$//;
 5865:    my $esc_symb=&escape($symb);
 5866:    my $esc_v=&escape($version);
 5867:    my $reply =
 5868:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5869: 	      $uhome);
 5870:    if (($tolog) && ($reply eq 'ok')) {
 5871:        my $namevalue='';
 5872:        foreach my $key (keys(%{$storehash})) {
 5873:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5874:        }
 5875:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5876:                      '&host='.&escape($perlvar{'lonHostID'}).
 5877:                      '&version='.$esc_v.
 5878:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5879:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5880:    }
 5881:    if ($reply eq 'unknown_cmd') {
 5882:        # gfall back to way things use to be done
 5883:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5884: 			    $uname);
 5885:    }
 5886:    return $reply;
 5887: }
 5888: 
 5889: sub old_putstore {
 5890:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5891:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5892:     if (!$uname) { $uname=$env{'user.name'}; }
 5893:     my $uhome=&homeserver($uname,$udomain);
 5894:     my %newstorehash;
 5895:     foreach my $item (keys(%$storehash)) {
 5896: 	my $key = $version.':'.&escape($symb).':'.$item;
 5897: 	$newstorehash{$key} = $storehash->{$item};
 5898:     }
 5899:     my $items='';
 5900:     my %allitems = ();
 5901:     foreach my $item (keys(%newstorehash)) {
 5902: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5903: 	    my $key = $1.':keys:'.$2;
 5904: 	    $allitems{$key} .= $3.':';
 5905: 	}
 5906: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5907:     }
 5908:     foreach my $item (keys(%allitems)) {
 5909: 	$allitems{$item} =~ s/\:$//;
 5910: 	$items.= $item.'='.$allitems{$item}.'&';
 5911:     }
 5912:     $items=~s/\&$//;
 5913:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5914: }
 5915: 
 5916: # ------------------------------------------------------ critical put interface
 5917: 
 5918: sub cput {
 5919:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5921:    if (!$uname) { $uname=$env{'user.name'}; }
 5922:    my $uhome=&homeserver($uname,$udomain);
 5923:    my $items='';
 5924:    foreach my $item (keys(%$storehash)) {
 5925:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5926:    }
 5927:    $items=~s/\&$//;
 5928:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5929: }
 5930: 
 5931: # -------------------------------------------------------------- eget interface
 5932: 
 5933: sub eget {
 5934:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5935:    my $items='';
 5936:    foreach my $item (@$storearr) {
 5937:        $items.=&escape($item).'&';
 5938:    }
 5939:    $items=~s/\&$//;
 5940:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5941:    if (!$uname) { $uname=$env{'user.name'}; }
 5942:    my $uhome=&homeserver($uname,$udomain);
 5943:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5944:    my @pairs=split(/\&/,$rep);
 5945:    my %returnhash=();
 5946:    my $i=0;
 5947:    foreach my $item (@$storearr) {
 5948:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5949:       $i++;
 5950:    }
 5951:    return %returnhash;
 5952: }
 5953: 
 5954: # ------------------------------------------------------------ tmpput interface
 5955: sub tmpput {
 5956:     my ($storehash,$server,$context)=@_;
 5957:     my $items='';
 5958:     foreach my $item (keys(%$storehash)) {
 5959: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5960:     }
 5961:     $items=~s/\&$//;
 5962:     if (defined($context)) {
 5963:         $items .= ':'.&escape($context);
 5964:     }
 5965:     return &reply("tmpput:$items",$server);
 5966: }
 5967: 
 5968: # ------------------------------------------------------------ tmpget interface
 5969: sub tmpget {
 5970:     my ($token,$server)=@_;
 5971:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5972:     my $rep=&reply("tmpget:$token",$server);
 5973:     my %returnhash;
 5974:     foreach my $item (split(/\&/,$rep)) {
 5975: 	my ($key,$value)=split(/=/,$item);
 5976:         next if ($key =~ /^error: 2 /);
 5977: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5978:     }
 5979:     return %returnhash;
 5980: }
 5981: 
 5982: # ------------------------------------------------------------ tmpdel interface
 5983: sub tmpdel {
 5984:     my ($token,$server)=@_;
 5985:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5986:     return &reply("tmpdel:$token",$server);
 5987: }
 5988: 
 5989: # ------------------------------------------------------------ get_timebased_id 
 5990: 
 5991: sub get_timebased_id {
 5992:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5993:         $maxtries) = @_;
 5994:     my ($newid,$error,$dellock);
 5995:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5996:         return ('','ok','invalid call to get suffix');
 5997:     }
 5998: 
 5999: # set defaults for any optional args for which values were not supplied
 6000:     if ($who eq '') {
 6001:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6002:     }
 6003:     if (!$locktries) {
 6004:         $locktries = 3;
 6005:     }
 6006:     if (!$maxtries) {
 6007:         $maxtries = 10;
 6008:     }
 6009:     
 6010:     if (($cdom eq '') || ($cnum eq '')) {
 6011:         if ($env{'request.course.id'}) {
 6012:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6013:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6014:         }
 6015:         if (($cdom eq '') || ($cnum eq '')) {
 6016:             return ('','ok','call to get suffix not in course context');
 6017:         }
 6018:     }
 6019: 
 6020: # construct locking item
 6021:     my $lockhash = {
 6022:                       $prefix."\0".'locked_'.$keyid => $who,
 6023:                    };
 6024:     my $tries = 0;
 6025: 
 6026: # attempt to get lock on nohist_$namespace file
 6027:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6028:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6029:         $tries ++;
 6030:         sleep 1;
 6031:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6032:     }
 6033: 
 6034: # attempt to get unique identifier, based on current timestamp
 6035:     if ($gotlock eq 'ok') {
 6036:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6037:         my $id = time;
 6038:         $newid = $id;
 6039:         if ($idtype eq 'addcode') {
 6040:             $newid .= &sixnum_code();
 6041:         }
 6042:         my $idtries = 0;
 6043:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6044:             if ($idtype eq 'concat') {
 6045:                 $newid = $id.$idtries;
 6046:             } elsif ($idtype eq 'addcode') {
 6047:                 $newid = $newid.&sixnum_code();
 6048:             } else {
 6049:                 $newid ++;
 6050:             }
 6051:             $idtries ++;
 6052:         }
 6053:         if (!exists($inuse{$prefix."\0".$newid})) {
 6054:             my %new_item =  (
 6055:                               $prefix."\0".$newid => $who,
 6056:                             );
 6057:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6058:                                                  $cdom,$cnum);
 6059:             if ($putresult ne 'ok') {
 6060:                 undef($newid);
 6061:                 $error = 'error saving new item: '.$putresult;
 6062:             }
 6063:         } else {
 6064:              undef($newid);
 6065:              $error = ('error: no unique suffix available for the new item ');
 6066:         }
 6067: #  remove lock
 6068:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6069:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6070:     } else {
 6071:         $error = "error: could not obtain lockfile\n";
 6072:         $dellock = 'ok';
 6073:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6074:             $dellock = 'nolock';
 6075:         }
 6076:     }
 6077:     return ($newid,$dellock,$error);
 6078: }
 6079: 
 6080: sub sixnum_code {
 6081:     my $code;
 6082:     for (0..6) {
 6083:         $code .= int( rand(9) );
 6084:     }
 6085:     return $code;
 6086: }
 6087: 
 6088: # -------------------------------------------------- portfolio access checking
 6089: 
 6090: sub portfolio_access {
 6091:     my ($requrl,$clientip) = @_;
 6092:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6093:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6094:     if ($result) {
 6095:         my %setters;
 6096:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6097:             my ($startblock,$endblock) =
 6098:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6099:             if ($startblock && $endblock) {
 6100:                 return 'B';
 6101:             }
 6102:         } else {
 6103:             my ($startblock,$endblock) =
 6104:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6105:             if ($startblock && $endblock) {
 6106:                 return 'B';
 6107:             }
 6108:         }
 6109:     }
 6110:     if ($result eq 'ok') {
 6111:        return 'F';
 6112:     } elsif ($result =~ /^[^:]+:guest_/) {
 6113:        return 'A';
 6114:     }
 6115:     return '';
 6116: }
 6117: 
 6118: sub get_portfolio_access {
 6119:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6120: 
 6121:     if (!ref($access_hash)) {
 6122: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6123: 	my %access_controls = &get_access_controls($current_perms,$group,
 6124: 						   $file_name);
 6125: 	$access_hash = $access_controls{$file_name};
 6126:     }
 6127: 
 6128:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6129:     my $now = time;
 6130:     if (ref($access_hash) eq 'HASH') {
 6131:         foreach my $key (keys(%{$access_hash})) {
 6132:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6133:             if ($start > $now) {
 6134:                 next;
 6135:             }
 6136:             if ($end && $end<$now) {
 6137:                 next;
 6138:             }
 6139:             if ($scope eq 'public') {
 6140:                 $public = $key;
 6141:                 last;
 6142:             } elsif ($scope eq 'guest') {
 6143:                 $guest = $key;
 6144:             } elsif ($scope eq 'domains') {
 6145:                 push(@domains,$key);
 6146:             } elsif ($scope eq 'users') {
 6147:                 push(@users,$key);
 6148:             } elsif ($scope eq 'course') {
 6149:                 push(@courses,$key);
 6150:             } elsif ($scope eq 'group') {
 6151:                 push(@groups,$key);
 6152:             } elsif ($scope eq 'ip') {
 6153:                 push(@ips,$key);
 6154:             }
 6155:         }
 6156:         if ($public) {
 6157:             return 'ok';
 6158:         } elsif (@ips > 0) {
 6159:             my $allowed;
 6160:             foreach my $ipkey (@ips) {
 6161:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6162:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6163:                         $allowed = 1;
 6164:                         last; 
 6165:                     }
 6166:                 }
 6167:             }
 6168:             if ($allowed) {
 6169:                 return 'ok';
 6170:             }
 6171:         }
 6172:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6173:             if ($guest) {
 6174:                 return $guest;
 6175:             }
 6176:         } else {
 6177:             if (@domains > 0) {
 6178:                 foreach my $domkey (@domains) {
 6179:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6180:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6181:                             return 'ok';
 6182:                         }
 6183:                     }
 6184:                 }
 6185:             }
 6186:             if (@users > 0) {
 6187:                 foreach my $userkey (@users) {
 6188:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6189:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6190:                             if (ref($item) eq 'HASH') {
 6191:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6192:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6193:                                     return 'ok';
 6194:                                 }
 6195:                             }
 6196:                         }
 6197:                     } 
 6198:                 }
 6199:             }
 6200:             my %roleshash;
 6201:             my @courses_and_groups = @courses;
 6202:             push(@courses_and_groups,@groups); 
 6203:             if (@courses_and_groups > 0) {
 6204:                 my (%allgroups,%allroles); 
 6205:                 my ($start,$end,$role,$sec,$group);
 6206:                 foreach my $envkey (%env) {
 6207:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6208:                         my $cid = $2.'_'.$3; 
 6209:                         if ($1 eq 'gr') {
 6210:                             $group = $4;
 6211:                             $allgroups{$cid}{$group} = $env{$envkey};
 6212:                         } else {
 6213:                             if ($4 eq '') {
 6214:                                 $sec = 'none';
 6215:                             } else {
 6216:                                 $sec = $4;
 6217:                             }
 6218:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6219:                         }
 6220:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6221:                         my $cid = $2.'_'.$3;
 6222:                         if ($4 eq '') {
 6223:                             $sec = 'none';
 6224:                         } else {
 6225:                             $sec = $4;
 6226:                         }
 6227:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6228:                     }
 6229:                 }
 6230:                 if (keys(%allroles) == 0) {
 6231:                     return;
 6232:                 }
 6233:                 foreach my $key (@courses_and_groups) {
 6234:                     my %content = %{$$access_hash{$key}};
 6235:                     my $cnum = $content{'number'};
 6236:                     my $cdom = $content{'domain'};
 6237:                     my $cid = $cdom.'_'.$cnum;
 6238:                     if (!exists($allroles{$cid})) {
 6239:                         next;
 6240:                     }    
 6241:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6242:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6243:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6244:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6245:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6246:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6247:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6248:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6249:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6250:                                         if (grep/^all$/,@sections) {
 6251:                                             return 'ok';
 6252:                                         } else {
 6253:                                             if (grep/^$sec$/,@sections) {
 6254:                                                 return 'ok';
 6255:                                             }
 6256:                                         }
 6257:                                     }
 6258:                                 }
 6259:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6260:                                     if (grep/^none$/,@groups) {
 6261:                                         return 'ok';
 6262:                                     }
 6263:                                 } else {
 6264:                                     if (grep/^all$/,@groups) {
 6265:                                         return 'ok';
 6266:                                     } 
 6267:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6268:                                         if (grep/^$group$/,@groups) {
 6269:                                             return 'ok';
 6270:                                         }
 6271:                                     }
 6272:                                 } 
 6273:                             }
 6274:                         }
 6275:                     }
 6276:                 }
 6277:             }
 6278:             if ($guest) {
 6279:                 return $guest;
 6280:             }
 6281:         }
 6282:     }
 6283:     return;
 6284: }
 6285: 
 6286: sub course_group_datechecker {
 6287:     my ($dates,$now,$status) = @_;
 6288:     my ($start,$end) = split(/\./,$dates);
 6289:     if (!$start && !$end) {
 6290:         return 'ok';
 6291:     }
 6292:     if (grep/^active$/,@{$status}) {
 6293:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6294:             return 'ok';
 6295:         }
 6296:     }
 6297:     if (grep/^previous$/,@{$status}) {
 6298:         if ($end > $now ) {
 6299:             return 'ok';
 6300:         }
 6301:     }
 6302:     if (grep/^future$/,@{$status}) {
 6303:         if ($start > $now) {
 6304:             return 'ok';
 6305:         }
 6306:     }
 6307:     return; 
 6308: }
 6309: 
 6310: sub parse_portfolio_url {
 6311:     my ($url) = @_;
 6312: 
 6313:     my ($type,$udom,$unum,$group,$file_name);
 6314:     
 6315:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6316: 	$type = 1;
 6317:         $udom = $1;
 6318:         $unum = $2;
 6319:         $file_name = $3;
 6320:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6321: 	$type = 2;
 6322:         $udom = $1;
 6323:         $unum = $2;
 6324:         $group = $3;
 6325:         $file_name = $3.'/'.$4;
 6326:     }
 6327:     if (wantarray) {
 6328: 	return ($type,$udom,$unum,$file_name,$group);
 6329:     }
 6330:     return $type;
 6331: }
 6332: 
 6333: sub is_portfolio_url {
 6334:     my ($url) = @_;
 6335:     return scalar(&parse_portfolio_url($url));
 6336: }
 6337: 
 6338: sub is_portfolio_file {
 6339:     my ($file) = @_;
 6340:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6341:         return 1;
 6342:     }
 6343:     return;
 6344: }
 6345: 
 6346: sub usertools_access {
 6347:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6348:     my ($access,%tools);
 6349:     if ($context eq '') {
 6350:         $context = 'tools';
 6351:     }
 6352:     if ($context eq 'requestcourses') {
 6353:         %tools = (
 6354:                       official   => 1,
 6355:                       unofficial => 1,
 6356:                       community  => 1,
 6357:                       textbook   => 1,
 6358:                  );
 6359:     } elsif ($context eq 'requestauthor') {
 6360:         %tools = (
 6361:                       requestauthor => 1,
 6362:                  );
 6363:     } else {
 6364:         %tools = (
 6365:                       aboutme   => 1,
 6366:                       blog      => 1,
 6367:                       webdav    => 1,
 6368:                       portfolio => 1,
 6369:                  );
 6370:     }
 6371:     return if (!defined($tools{$tool}));
 6372: 
 6373:     if (($udom eq '') || ($uname eq '')) {
 6374:         $udom = $env{'user.domain'};
 6375:         $uname = $env{'user.name'};
 6376:     }
 6377: 
 6378:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6379:         if ($action ne 'reload') {
 6380:             if ($context eq 'requestcourses') {
 6381:                 return $env{'environment.canrequest.'.$tool};
 6382:             } elsif ($context eq 'requestauthor') {
 6383:                 return $env{'environment.canrequest.author'};
 6384:             } else {
 6385:                 return $env{'environment.availabletools.'.$tool};
 6386:             }
 6387:         }
 6388:     }
 6389: 
 6390:     my ($toolstatus,$inststatus,$envkey);
 6391:     if ($context eq 'requestauthor') {
 6392:         $envkey = $context; 
 6393:     } else {
 6394:         $envkey = $context.'.'.$tool;
 6395:     }
 6396: 
 6397:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6398:          ($action ne 'reload')) {
 6399:         $toolstatus = $env{'environment.'.$envkey};
 6400:         $inststatus = $env{'environment.inststatus'};
 6401:     } else {
 6402:         if (ref($userenvref) eq 'HASH') {
 6403:             $toolstatus = $userenvref->{$envkey};
 6404:             $inststatus = $userenvref->{'inststatus'};
 6405:         } else {
 6406:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6407:             $toolstatus = $userenv{$envkey};
 6408:             $inststatus = $userenv{'inststatus'};
 6409:         }
 6410:     }
 6411: 
 6412:     if ($toolstatus ne '') {
 6413:         if ($toolstatus) {
 6414:             $access = 1;
 6415:         } else {
 6416:             $access = 0;
 6417:         }
 6418:         return $access;
 6419:     }
 6420: 
 6421:     my ($is_adv,%domdef);
 6422:     if (ref($is_advref) eq 'HASH') {
 6423:         $is_adv = $is_advref->{'is_adv'};
 6424:     } else {
 6425:         $is_adv = &is_advanced_user($udom,$uname);
 6426:     }
 6427:     if (ref($domdefref) eq 'HASH') {
 6428:         %domdef = %{$domdefref};
 6429:     } else {
 6430:         %domdef = &get_domain_defaults($udom);
 6431:     }
 6432:     if (ref($domdef{$tool}) eq 'HASH') {
 6433:         if ($is_adv) {
 6434:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6435:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6436:                     $access = 1;
 6437:                 } else {
 6438:                     $access = 0;
 6439:                 }
 6440:                 return $access;
 6441:             }
 6442:         }
 6443:         if ($inststatus ne '') {
 6444:             my ($hasaccess,$hasnoaccess);
 6445:             foreach my $affiliation (split(/:/,$inststatus)) {
 6446:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6447:                     if ($domdef{$tool}{$affiliation}) {
 6448:                         $hasaccess = 1;
 6449:                     } else {
 6450:                         $hasnoaccess = 1;
 6451:                     }
 6452:                 }
 6453:             }
 6454:             if ($hasaccess || $hasnoaccess) {
 6455:                 if ($hasaccess) {
 6456:                     $access = 1;
 6457:                 } elsif ($hasnoaccess) {
 6458:                     $access = 0; 
 6459:                 }
 6460:                 return $access;
 6461:             }
 6462:         } else {
 6463:             if ($domdef{$tool}{'default'} ne '') {
 6464:                 if ($domdef{$tool}{'default'}) {
 6465:                     $access = 1;
 6466:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6467:                     $access = 0;
 6468:                 }
 6469:                 return $access;
 6470:             }
 6471:         }
 6472:     } else {
 6473:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6474:             $access = 1;
 6475:         } else {
 6476:             $access = 0;
 6477:         }
 6478:         return $access;
 6479:     }
 6480: }
 6481: 
 6482: sub is_course_owner {
 6483:     my ($cdom,$cnum,$udom,$uname) = @_;
 6484:     if (($udom eq '') || ($uname eq '')) {
 6485:         $udom = $env{'user.domain'};
 6486:         $uname = $env{'user.name'};
 6487:     }
 6488:     unless (($udom eq '') || ($uname eq '')) {
 6489:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6490:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6491:                 return 1;
 6492:             } else {
 6493:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6494:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6495:                     return 1;
 6496:                 }
 6497:             }
 6498:         }
 6499:     }
 6500:     return;
 6501: }
 6502: 
 6503: sub is_advanced_user {
 6504:     my ($udom,$uname) = @_;
 6505:     if ($udom ne '' && $uname ne '') {
 6506:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6507:             if (wantarray) {
 6508:                 return ($env{'user.adv'},$env{'user.author'});
 6509:             } else {
 6510:                 return $env{'user.adv'};
 6511:             }
 6512:         }
 6513:     }
 6514:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6515:     my %allroles;
 6516:     my ($is_adv,$is_author);
 6517:     foreach my $role (keys(%roleshash)) {
 6518:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6519:         my $area = '/'.$tdomain.'/'.$trest;
 6520:         if ($sec ne '') {
 6521:             $area .= '/'.$sec;
 6522:         }
 6523:         if (($area ne '') && ($trole ne '')) {
 6524:             my $spec=$trole.'.'.$area;
 6525:             if ($trole =~ /^cr\//) {
 6526:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6527:             } elsif ($trole ne 'gr') {
 6528:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6529:             }
 6530:             if ($trole eq 'au') {
 6531:                 $is_author = 1;
 6532:             }
 6533:         }
 6534:     }
 6535:     foreach my $role (keys(%allroles)) {
 6536:         last if ($is_adv);
 6537:         foreach my $item (split(/:/,$allroles{$role})) {
 6538:             if ($item ne '') {
 6539:                 my ($privilege,$restrictions)=split(/&/,$item);
 6540:                 if ($privilege eq 'adv') {
 6541:                     $is_adv = 1;
 6542:                     last;
 6543:                 }
 6544:             }
 6545:         }
 6546:     }
 6547:     if (wantarray) {
 6548:         return ($is_adv,$is_author);
 6549:     }
 6550:     return $is_adv;
 6551: }
 6552: 
 6553: sub check_can_request {
 6554:     my ($dom,$can_request,$request_domains) = @_;
 6555:     my $canreq = 0;
 6556:     my ($types,$typename) = &Apache::loncommon::course_types();
 6557:     my @options = ('approval','validate','autolimit');
 6558:     my $optregex = join('|',@options);
 6559:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6560:         foreach my $type (@{$types}) {
 6561:             if (&usertools_access($env{'user.name'},
 6562:                                   $env{'user.domain'},
 6563:                                   $type,undef,'requestcourses')) {
 6564:                 $canreq ++;
 6565:                 if (ref($request_domains) eq 'HASH') {
 6566:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6567:                 }
 6568:                 if ($dom eq $env{'user.domain'}) {
 6569:                     $can_request->{$type} = 1;
 6570:                 }
 6571:             }
 6572:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6573:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6574:                 if (@curr > 0) {
 6575:                     foreach my $item (@curr) {
 6576:                         if (ref($request_domains) eq 'HASH') {
 6577:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6578:                             if ($otherdom ne '') {
 6579:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6580:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6581:                                         push(@{$request_domains->{$type}},$otherdom);
 6582:                                     }
 6583:                                 } else {
 6584:                                     push(@{$request_domains->{$type}},$otherdom);
 6585:                                 }
 6586:                             }
 6587:                         }
 6588:                     }
 6589:                     unless($dom eq $env{'user.domain'}) {
 6590:                         $canreq ++;
 6591:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6592:                             $can_request->{$type} = 1;
 6593:                         }
 6594:                     }
 6595:                 }
 6596:             }
 6597:         }
 6598:     }
 6599:     return $canreq;
 6600: }
 6601: 
 6602: # ---------------------------------------------- Custom access rule evaluation
 6603: 
 6604: sub customaccess {
 6605:     my ($priv,$uri)=@_;
 6606:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6607:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6608:     $udom = &LONCAPA::clean_domain($udom);
 6609:     $ucrs = &LONCAPA::clean_username($ucrs);
 6610:     my $access=0;
 6611:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6612: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6613: 	if ($type eq 'user') {
 6614: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6615: 		my ($tdom,$tuname)=split(m{/},$scope);
 6616: 		if ($tdom) {
 6617: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6618: 		}
 6619: 		if ($tuname) {
 6620: 		    if ($tuname ne $env{'user.name'}) { next; }
 6621: 		}
 6622: 		$access=($effect eq 'allow');
 6623: 		last;
 6624: 	    }
 6625: 	} else {
 6626: 	    if ($role) {
 6627: 		if ($role ne $urole) { next; }
 6628: 	    }
 6629: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6630: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6631: 		if ($tdom) {
 6632: 		    if ($tdom ne $udom) { next; }
 6633: 		}
 6634: 		if ($tcrs) {
 6635: 		    if ($tcrs ne $ucrs) { next; }
 6636: 		}
 6637: 		if ($tsec) {
 6638: 		    if ($tsec ne $usec) { next; }
 6639: 		}
 6640: 		$access=($effect eq 'allow');
 6641: 		last;
 6642: 	    }
 6643: 	    if ($realm eq '' && $role eq '') {
 6644: 		$access=($effect eq 'allow');
 6645: 	    }
 6646: 	}
 6647:     }
 6648:     return $access;
 6649: }
 6650: 
 6651: # ------------------------------------------------- Check for a user privilege
 6652: 
 6653: sub allowed {
 6654:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 6655:     my $ver_orguri=$uri;
 6656:     $uri=&deversion($uri);
 6657:     my $orguri=$uri;
 6658:     $uri=&declutter($uri);
 6659: 
 6660:     if ($priv eq 'evb') {
 6661: # Evade communication block restrictions for specified role in a course
 6662:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6663:             return $1;
 6664:         } else {
 6665:             return;
 6666:         }
 6667:     }
 6668: 
 6669:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6670: # Free bre access to adm and meta resources
 6671:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6672: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6673: 	&& ($priv eq 'bre')) {
 6674: 	return 'F';
 6675:     }
 6676: 
 6677: # Free bre access to user's own portfolio contents
 6678:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6679:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6680: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6681:         my %setters;
 6682:         my ($startblock,$endblock) = 
 6683:             &Apache::loncommon::blockcheck(\%setters,'port');
 6684:         if ($startblock && $endblock) {
 6685:             return 'B';
 6686:         } else {
 6687:             return 'F';
 6688:         }
 6689:     }
 6690: 
 6691: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6692:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6693:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6694:         if (exists($env{'request.course.id'})) {
 6695:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6696:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6697:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6698:                 my $courseprivid=$env{'request.course.id'};
 6699:                 $courseprivid=~s/\_/\//;
 6700:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6701:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6702:                     return $1; 
 6703:                 } else {
 6704:                     if ($env{'request.course.sec'}) {
 6705:                         $courseprivid.='/'.$env{'request.course.sec'};
 6706:                     }
 6707:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6708:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6709:                         return $2;
 6710:                     }
 6711:                 }
 6712:             }
 6713:         }
 6714:     }
 6715: 
 6716: # Free bre to public access
 6717: 
 6718:     if ($priv eq 'bre') {
 6719:         my $copyright=&metadata($uri,'copyright');
 6720: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6721:            return 'F'; 
 6722:         }
 6723:         if ($copyright eq 'priv') {
 6724:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6725: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6726: 		return '';
 6727:             }
 6728:         }
 6729:         if ($copyright eq 'domain') {
 6730:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6731: 	    unless (($env{'user.domain'} eq $1) ||
 6732:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6733: 		return '';
 6734:             }
 6735:         }
 6736:         if ($env{'request.role'}=~ /li\.\//) {
 6737:             # Library role, so allow browsing of resources in this domain.
 6738:             return 'F';
 6739:         }
 6740:         if ($copyright eq 'custom') {
 6741: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6742:         }
 6743:     }
 6744:     # Domain coordinator is trying to create a course
 6745:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6746:         # uri is the requested domain in this case.
 6747:         # comparison to 'request.role.domain' shows if the user has selected
 6748:         # a role of dc for the domain in question.
 6749:         return 'F' if ($uri eq $env{'request.role.domain'});
 6750:     }
 6751: 
 6752:     my $thisallowed='';
 6753:     my $statecond=0;
 6754:     my $courseprivid='';
 6755: 
 6756:     my $ownaccess;
 6757:     # Community Coordinator or Assistant Co-author browsing resource space.
 6758:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6759:         if ($uri eq '') {
 6760:             $ownaccess = 1;
 6761:         } else {
 6762:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6763:                 my $udom = $env{'user.domain'};
 6764:                 my $uname = $env{'user.name'};
 6765:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6766:                     $ownaccess = 1;
 6767:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6768:                     unless ($uri =~ m{\.\./}) {
 6769:                         $ownaccess = 1;
 6770:                     }
 6771:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6772:                     my $now = time;
 6773:                     if ($uri =~ m{^([^/]+)/?$}) {
 6774:                         my $adom = $1;
 6775:                         foreach my $key (keys(%env)) {
 6776:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6777:                                 my ($start,$end) = split('.',$env{$key});
 6778:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6779:                                     $ownaccess = 1;
 6780:                                     last;
 6781:                                 }
 6782:                             }
 6783:                         }
 6784:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6785:                         my $adom = $1;
 6786:                         my $aname = $2;
 6787:                         foreach my $role ('ca','aa') { 
 6788:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6789:                                 my ($start,$end) =
 6790:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6791:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6792:                                     $ownaccess = 1;
 6793:                                     last;
 6794:                                 }
 6795:                             }
 6796:                         }
 6797:                     }
 6798:                 }
 6799:             }
 6800:         }
 6801:     }
 6802: 
 6803: # Course
 6804: 
 6805:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6806:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6807:             $thisallowed.=$1;
 6808:         }
 6809:     }
 6810: 
 6811: # Domain
 6812: 
 6813:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6814:        =~/\Q$priv\E\&([^\:]*)/) {
 6815:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6816:             $thisallowed.=$1;
 6817:         }
 6818:     }
 6819: 
 6820: # User who is not author or co-author might still be able to edit
 6821: # resource of an author in the domain (e.g., if Domain Coordinator).
 6822:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6823:         (&allowed('mdc',$env{'request.course.id'}))) {
 6824:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6825:             $thisallowed.=$1;
 6826:         }
 6827:     }
 6828: 
 6829: # Course: uri itself is a course
 6830:     my $courseuri=$uri;
 6831:     $courseuri=~s/\_(\d)/\/$1/;
 6832:     $courseuri=~s/^([^\/])/\/$1/;
 6833: 
 6834:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6835:        =~/\Q$priv\E\&([^\:]*)/) {
 6836:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6837:             $thisallowed.=$1;
 6838:         }
 6839:     }
 6840: 
 6841: # URI is an uploaded document for this course, default permissions don't matter
 6842: # not allowing 'edit' access (editupload) to uploaded course docs
 6843:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6844: 	$thisallowed='';
 6845:         my ($match)=&is_on_map($uri);
 6846:         if ($match) {
 6847:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6848:                   =~/\Q$priv\E\&([^\:]*)/) {
 6849:                 my $value = $1;
 6850:                 if ($noblockcheck) {
 6851:                     $thisallowed.=$value;
 6852:                 } else {
 6853:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6854:                     if (@blockers > 0) {
 6855:                         $thisallowed = 'B';
 6856:                     } else {
 6857:                         $thisallowed.=$value;
 6858:                     }
 6859:                 }
 6860:             }
 6861:         } else {
 6862:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6863:             if ($refuri) {
 6864:                 if ($refuri =~ m|^/adm/|) {
 6865:                     $thisallowed='F';
 6866:                 } else {
 6867:                     $refuri=&declutter($refuri);
 6868:                     my ($match) = &is_on_map($refuri);
 6869:                     if ($match) {
 6870:                         if ($noblockcheck) {
 6871:                             $thisallowed='F';
 6872:                         } else {
 6873:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6874:                             if (@blockers > 0) {
 6875:                                 $thisallowed = 'B';
 6876:                             } else {
 6877:                                 $thisallowed='F';
 6878:                             }
 6879:                         }
 6880:                     }
 6881:                 }
 6882:             }
 6883:         }
 6884:     }
 6885: 
 6886:     if ($priv eq 'bre'
 6887: 	&& $thisallowed ne 'F' 
 6888: 	&& $thisallowed ne '2'
 6889: 	&& &is_portfolio_url($uri)) {
 6890: 	$thisallowed = &portfolio_access($uri,$clientip);
 6891:     }
 6892: 
 6893: # Full access at system, domain or course-wide level? Exit.
 6894:     if ($thisallowed=~/F/) {
 6895: 	return 'F';
 6896:     }
 6897: 
 6898: # If this is generating or modifying users, exit with special codes
 6899: 
 6900:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6901: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6902: 	    my ($audom,$auname)=split('/',$uri);
 6903: # no author name given, so this just checks on the general right to make a co-author in this domain
 6904: 	    unless ($auname) { return $thisallowed; }
 6905: # an author name is given, so we are about to actually make a co-author for a certain account
 6906: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6907: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6908: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6909: 	}
 6910: 	return $thisallowed;
 6911:     }
 6912: #
 6913: # Gathered so far: system, domain and course wide privileges
 6914: #
 6915: # Course: See if uri or referer is an individual resource that is part of 
 6916: # the course
 6917: 
 6918:     if ($env{'request.course.id'}) {
 6919: 
 6920:        $courseprivid=$env{'request.course.id'};
 6921:        if ($env{'request.course.sec'}) {
 6922:           $courseprivid.='/'.$env{'request.course.sec'};
 6923:        }
 6924:        $courseprivid=~s/\_/\//;
 6925:        my $checkreferer=1;
 6926:        my ($match,$cond)=&is_on_map($uri);
 6927:        if ($match) {
 6928:            $statecond=$cond;
 6929:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6930:                =~/\Q$priv\E\&([^\:]*)/) {
 6931:                my $value = $1;
 6932:                if ($priv eq 'bre') {
 6933:                    if ($noblockcheck) {
 6934:                        $thisallowed.=$value;
 6935:                    } else {
 6936:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6937:                        if (@blockers > 0) {
 6938:                            $thisallowed = 'B';
 6939:                        } else {
 6940:                            $thisallowed.=$value;
 6941:                        }
 6942:                    }
 6943:                } else {
 6944:                    $thisallowed.=$value;
 6945:                }
 6946:                $checkreferer=0;
 6947:            }
 6948:        }
 6949:        
 6950:        if ($checkreferer) {
 6951: 	  my $refuri=$env{'httpref.'.$orguri};
 6952:             unless ($refuri) {
 6953:                 foreach my $key (keys(%env)) {
 6954: 		    if ($key=~/^httpref\..*\*/) {
 6955: 			my $pattern=$key;
 6956:                         $pattern=~s/^httpref\.\/res\///;
 6957:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6958:                         $pattern=~s/\//\\\//g;
 6959:                         if ($orguri=~/$pattern/) {
 6960: 			    $refuri=$env{$key};
 6961:                         }
 6962:                     }
 6963:                 }
 6964:             }
 6965: 
 6966:          if ($refuri) { 
 6967: 	  $refuri=&declutter($refuri);
 6968:           my ($match,$cond)=&is_on_map($refuri);
 6969:             if ($match) {
 6970:               my $refstatecond=$cond;
 6971:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6972:                   =~/\Q$priv\E\&([^\:]*)/) {
 6973:                   my $value = $1;
 6974:                   if ($priv eq 'bre') {
 6975:                       if ($noblockcheck) {
 6976:                           $thisallowed.=$value;
 6977:                       } else {
 6978:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6979:                           if (@blockers > 0) {
 6980:                               $thisallowed = 'B';
 6981:                           } else {
 6982:                               $thisallowed.=$value;
 6983:                           }
 6984:                       }
 6985:                   } else {
 6986:                       $thisallowed.=$value;
 6987:                   }
 6988:                   $uri=$refuri;
 6989:                   $statecond=$refstatecond;
 6990:               }
 6991:           }
 6992:         }
 6993:        }
 6994:    }
 6995: 
 6996: #
 6997: # Gathered now: all privileges that could apply, and condition number
 6998: # 
 6999: #
 7000: # Full or no access?
 7001: #
 7002: 
 7003:     if ($thisallowed=~/F/) {
 7004: 	return 'F';
 7005:     }
 7006: 
 7007:     unless ($thisallowed) {
 7008:         return '';
 7009:     }
 7010: 
 7011: # Restrictions exist, deal with them
 7012: #
 7013: #   C:according to course preferences
 7014: #   R:according to resource settings
 7015: #   L:unless locked
 7016: #   X:according to user session state
 7017: #
 7018: 
 7019: # Possibly locked functionality, check all courses
 7020: # Locks might take effect only after 10 minutes cache expiration for other
 7021: # courses, and 2 minutes for current course
 7022: 
 7023:     my $envkey;
 7024:     if ($thisallowed=~/L/) {
 7025:         foreach $envkey (keys(%env)) {
 7026:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7027:                my $courseid=$2;
 7028:                my $roleid=$1.'.'.$2;
 7029:                $courseid=~s/^\///;
 7030:                my $expiretime=600;
 7031:                if ($env{'request.role'} eq $roleid) {
 7032: 		  $expiretime=120;
 7033:                }
 7034: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7035:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7036:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7037: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7038:                }
 7039:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7040:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7041: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7042:                        &log($env{'user.domain'},$env{'user.name'},
 7043:                             $env{'user.home'},
 7044:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7045:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7046:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7047: 		       return '';
 7048:                    }
 7049:                }
 7050:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7051:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7052: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7053:                        &log($env{'user.domain'},$env{'user.name'},
 7054:                             $env{'user.home'},
 7055:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7056:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7057:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7058: 		       return '';
 7059:                    }
 7060:                }
 7061: 	   }
 7062:        }
 7063:     }
 7064:    
 7065: #
 7066: # Rest of the restrictions depend on selected course
 7067: #
 7068: 
 7069:     unless ($env{'request.course.id'}) {
 7070: 	if ($thisallowed eq 'A') {
 7071: 	    return 'A';
 7072:         } elsif ($thisallowed eq 'B') {
 7073:             return 'B';
 7074: 	} else {
 7075: 	    return '1';
 7076: 	}
 7077:     }
 7078: 
 7079: #
 7080: # Now user is definitely in a course
 7081: #
 7082: 
 7083: 
 7084: # Course preferences
 7085: 
 7086:    if ($thisallowed=~/C/) {
 7087:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7088:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7089:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7090: 	   =~/\Q$rolecode\E/) {
 7091: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7092: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7093: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7094: 			$env{'request.course.id'});
 7095: 	   }
 7096:            return '';
 7097:        }
 7098: 
 7099:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7100: 	   =~/\Q$unamedom\E/) {
 7101: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7102: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7103: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7104: 			$env{'request.course.id'});
 7105: 	   }
 7106:            return '';
 7107:        }
 7108:    }
 7109: 
 7110: # Resource preferences
 7111: 
 7112:    if ($thisallowed=~/R/) {
 7113:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7114:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7115: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7116: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7117: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7118: 	   }
 7119: 	   return '';
 7120:        }
 7121:    }
 7122: 
 7123: # Restricted by state or randomout?
 7124: 
 7125:    if ($thisallowed=~/X/) {
 7126:       if ($env{'acc.randomout'}) {
 7127: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7128:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7129:             return ''; 
 7130:          }
 7131:       }
 7132:       if (&condval($statecond)) {
 7133: 	 return '2';
 7134:       } else {
 7135:          return '';
 7136:       }
 7137:    }
 7138: 
 7139:     if ($thisallowed eq 'A') {
 7140: 	return 'A';
 7141:     } elsif ($thisallowed eq 'B') {
 7142:         return 'B';
 7143:     }
 7144:    return 'F';
 7145: }
 7146: 
 7147: # ------------------------------------------- Check construction space access
 7148: 
 7149: sub constructaccess {
 7150:     my ($url,$setpriv)=@_;
 7151: 
 7152: # We do not allow editing of previous versions of files
 7153:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7154: 
 7155: # Get username and domain from URL
 7156:     my ($ownername,$ownerdomain,$ownerhome);
 7157: 
 7158:     ($ownerdomain,$ownername) =
 7159:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7160: 
 7161: # The URL does not really point to any authorspace, forget it
 7162:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7163: 
 7164: # Now we need to see if the user has access to the authorspace of
 7165: # $ownername at $ownerdomain
 7166: 
 7167:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7168: # Real author for this?
 7169:        $ownerhome = $env{'user.home'};
 7170:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7171:           return ($ownername,$ownerdomain,$ownerhome);
 7172:        }
 7173:     } else {
 7174: # Co-author for this?
 7175:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7176:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7177:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7178:             return ($ownername,$ownerdomain,$ownerhome);
 7179:         }
 7180:     }
 7181: 
 7182: # We don't have any access right now. If we are not possibly going to do anything about this,
 7183: # we might as well leave
 7184:    unless ($setpriv) { return ''; }
 7185: 
 7186: # Backdoor access?
 7187:     my $allowed=&allowed('eco',$ownerdomain);
 7188: # Nope
 7189:     unless ($allowed) { return ''; }
 7190: # Looks like we may have access, but could be locked by the owner of the construction space
 7191:     if ($allowed eq 'U') {
 7192:         my %blocked=&get('environment',['domcoord.author'],
 7193:                          $ownerdomain,$ownername);
 7194: # Is blocked by owner
 7195:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7196:     }
 7197:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7198: # Grant temporary access
 7199:         my $then=$env{'user.login.time'};
 7200:         my $update=$env{'user.update.time'};
 7201:         if (!$update) { $update = $then; }
 7202:         my $refresh=$env{'user.refresh.time'};
 7203:         if (!$refresh) { $refresh = $update; }
 7204:         my $now = time;
 7205:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7206:                            $now,'ca','constructaccess');
 7207:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7208:         return($ownername,$ownerdomain,$ownerhome);
 7209:     }
 7210: # No business here
 7211:     return '';
 7212: }
 7213: 
 7214: # ----------------------------------------------------------- Content Blocking
 7215: 
 7216: {
 7217: # Caches for faster Course Contents display where content blocking
 7218: # is in operation (i.e., interval param set) for timed quiz.
 7219: #
 7220: # User for whom data are being temporarily cached.
 7221: my $cacheduser='';
 7222: # Cached blockers for this user (a hash of blocking items). 
 7223: my %cachedblockers=();
 7224: # When the data were last cached.
 7225: my $cachedlast='';
 7226: 
 7227: sub load_all_blockers {
 7228:     my ($uname,$udom,$blocks)=@_;
 7229:     if (($uname ne '') && ($udom ne '')) { 
 7230:         if (($cacheduser eq $uname.':'.$udom) &&
 7231:             (abs($cachedlast-time)<5)) {
 7232:             return;
 7233:         }
 7234:     }
 7235:     $cachedlast=time;
 7236:     $cacheduser=$uname.':'.$udom;
 7237:     %cachedblockers = &get_commblock_resources($blocks);
 7238: }
 7239: 
 7240: sub get_comm_blocks {
 7241:     my ($cdom,$cnum) = @_;
 7242:     if ($cdom eq '' || $cnum eq '') {
 7243:         return unless ($env{'request.course.id'});
 7244:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7245:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7246:     }
 7247:     my %commblocks;
 7248:     my $hashid=$cdom.'_'.$cnum;
 7249:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7250:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7251:         %commblocks = %{$blocksref};
 7252:     } else {
 7253:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7254:         my $cachetime = 600;
 7255:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7256:     }
 7257:     return %commblocks;
 7258: }
 7259: 
 7260: sub get_commblock_resources {
 7261:     my ($blocks) = @_;
 7262:     my %blockers = ();
 7263:     return %blockers unless ($env{'request.course.id'});
 7264:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7265:     my %commblocks;
 7266:     if (ref($blocks) eq 'HASH') {
 7267:         %commblocks = %{$blocks};
 7268:     } else {
 7269:         %commblocks = &get_comm_blocks();
 7270:     }
 7271:     return %blockers unless (keys(%commblocks) > 0); 
 7272:     my $navmap = Apache::lonnavmaps::navmap->new();
 7273:     return %blockers unless (ref($navmap));
 7274:     my $now = time;
 7275:     foreach my $block (keys(%commblocks)) {
 7276:         if ($block =~ /^(\d+)____(\d+)$/) {
 7277:             my ($start,$end) = ($1,$2);
 7278:             if ($start <= $now && $end >= $now) {
 7279:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7280:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7281:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7282:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7283:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 7284:                             }
 7285:                         }
 7286:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7287:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7288:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7289:                             }
 7290:                         }
 7291:                     }
 7292:                 }
 7293:             }
 7294:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7295:             my $item = $1;
 7296:             my @to_test;
 7297:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7298:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7299:                     my @interval;
 7300:                     my $type = 'map';
 7301:                     if ($item eq 'course') {
 7302:                         $type = 'course';
 7303:                         @interval=&EXT("resource.0.interval");
 7304:                     } else {
 7305:                         if ($item =~ /___\d+___/) {
 7306:                             $type = 'resource';
 7307:                             @interval=&EXT("resource.0.interval",$item);
 7308:                             if (ref($navmap)) {                        
 7309:                                 my $res = $navmap->getBySymb($item); 
 7310:                                 push(@to_test,$res);
 7311:                             }
 7312:                         } else {
 7313:                             my $mapsymb = &symbread($item,1);
 7314:                             if ($mapsymb) {
 7315:                                 if (ref($navmap)) {
 7316:                                     my $mapres = $navmap->getBySymb($mapsymb);
 7317:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 7318:                                     foreach my $res (@to_test) {
 7319:                                         my $symb = $res->symb();
 7320:                                         next if ($symb eq $mapsymb);
 7321:                                         if ($symb ne '') {
 7322:                                             @interval=&EXT("resource.0.interval",$symb);
 7323:                                             if ($interval[1] eq 'map') {
 7324:                                                 last;
 7325:                                             }
 7326:                                         }
 7327:                                     }
 7328:                                 }
 7329:                             }
 7330:                         }
 7331:                     }
 7332:                     if ($interval[0] =~ /^\d+$/) {
 7333:                         my $first_access;
 7334:                         if ($type eq 'resource') {
 7335:                             $first_access=&get_first_access($interval[1],$item);
 7336:                         } elsif ($type eq 'map') {
 7337:                             $first_access=&get_first_access($interval[1],undef,$item);
 7338:                         } else {
 7339:                             $first_access=&get_first_access($interval[1]);
 7340:                         }
 7341:                         if ($first_access) {
 7342:                             my $timesup = $first_access+$interval[0];
 7343:                             if ($timesup > $now) {
 7344:                                 my $activeblock;
 7345:                                 foreach my $res (@to_test) {
 7346:                                     if ($res->answerable()) {
 7347:                                         $activeblock = 1;
 7348:                                         last;
 7349:                                     }
 7350:                                 }
 7351:                                 if ($activeblock) {
 7352:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7353:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7354:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 7355:                                          }
 7356:                                     }
 7357:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7358:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7359:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7360:                                         }
 7361:                                     }
 7362:                                 }
 7363:                             }
 7364:                         }
 7365:                     }
 7366:                 }
 7367:             }
 7368:         }
 7369:     }
 7370:     return %blockers;
 7371: }
 7372: 
 7373: sub has_comm_blocking {
 7374:     my ($priv,$symb,$uri,$blocks) = @_;
 7375:     my @blockers;
 7376:     return unless ($env{'request.course.id'});
 7377:     return unless ($priv eq 'bre');
 7378:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7379:     return if ($env{'request.state'} eq 'construct');
 7380:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 7381:     return unless (keys(%cachedblockers) > 0);
 7382:     my (%possibles,@symbs);
 7383:     if (!$symb) {
 7384:         $symb = &symbread($uri,1,1,1,\%possibles);
 7385:     }
 7386:     if ($symb) {
 7387:         @symbs = ($symb);
 7388:     } elsif (keys(%possibles)) { 
 7389:         @symbs = keys(%possibles);
 7390:     }
 7391:     my $noblock;
 7392:     foreach my $symb (@symbs) {
 7393:         last if ($noblock);
 7394:         my ($map,$resid,$resurl)=&decode_symb($symb);
 7395:         foreach my $block (keys(%cachedblockers)) {
 7396:             if ($block =~ /^firstaccess____(.+)$/) {
 7397:                 my $item = $1;
 7398:                 if (($item eq $map) || ($item eq $symb)) {
 7399:                     $noblock = 1;
 7400:                     last;
 7401:                 }
 7402:             }
 7403:             if (ref($cachedblockers{$block}) eq 'HASH') {
 7404:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 7405:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 7406:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 7407:                             push(@blockers,$block);
 7408:                         }
 7409:                     }
 7410:                 }
 7411:             }
 7412:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 7413:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 7414:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 7415:                         push(@blockers,$block);
 7416:                     }
 7417:                 }
 7418:             }
 7419:         }
 7420:     }
 7421:     return if ($noblock);
 7422:     return @blockers;
 7423: }
 7424: }
 7425: 
 7426: # -------------------------------- Deversion and split uri into path an filename   
 7427: 
 7428: #
 7429: #   Removes the version from a URI and
 7430: #   splits it in to its filename and path to the filename.
 7431: #   Seems like File::Basename could have done this more clearly.
 7432: #   Parameters:
 7433: #      $uri   - input URI
 7434: #   Returns:
 7435: #     Two element list consisting of 
 7436: #     $pathname  - the URI up to and excluding the trailing /
 7437: #     $filename  - The part of the URI following the last /
 7438: #  NOTE:
 7439: #    Another realization of this is simply:
 7440: #    use File::Basename;
 7441: #    ...
 7442: #    $uri = shift;
 7443: #    $filename = basename($uri);
 7444: #    $path     = dirname($uri);
 7445: #    return ($filename, $path);
 7446: #
 7447: #     The implementation below is probably faster however.
 7448: #
 7449: sub split_uri_for_cond {
 7450:     my $uri=&deversion(&declutter(shift));
 7451:     my @uriparts=split(/\//,$uri);
 7452:     my $filename=pop(@uriparts);
 7453:     my $pathname=join('/',@uriparts);
 7454:     return ($pathname,$filename);
 7455: }
 7456: # --------------------------------------------------- Is a resource on the map?
 7457: 
 7458: sub is_on_map {
 7459:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7460:     #Trying to find the conditional for the file
 7461:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7462: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7463:     if ($match) {
 7464: 	return (1,$1);
 7465:     } else {
 7466: 	return (0,0);
 7467:     }
 7468: }
 7469: 
 7470: # --------------------------------------------------------- Get symb from alias
 7471: 
 7472: sub get_symb_from_alias {
 7473:     my $symb=shift;
 7474:     my ($map,$resid,$url)=&decode_symb($symb);
 7475: # Already is a symb
 7476:     if ($url) { return $symb; }
 7477: # Must be an alias
 7478:     my $aliassymb='';
 7479:     my %bighash;
 7480:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7481:                             &GDBM_READER(),0640)) {
 7482:         my $rid=$bighash{'mapalias_'.$symb};
 7483: 	if ($rid) {
 7484: 	    my ($mapid,$resid)=split(/\./,$rid);
 7485: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7486: 				    $resid,$bighash{'src_'.$rid});
 7487: 	}
 7488:         untie %bighash;
 7489:     }
 7490:     return $aliassymb;
 7491: }
 7492: 
 7493: # ----------------------------------------------------------------- Define Role
 7494: 
 7495: sub definerole {
 7496:   if (allowed('mcr','/')) {
 7497:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7498:     foreach my $role (split(':',$sysrole)) {
 7499: 	my ($crole,$cqual)=split(/\&/,$role);
 7500:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7501:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7502: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7503:                return "refused:s:$crole&$cqual"; 
 7504:             }
 7505:         }
 7506:     }
 7507:     foreach my $role (split(':',$domrole)) {
 7508: 	my ($crole,$cqual)=split(/\&/,$role);
 7509:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7510:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7511: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7512:                return "refused:d:$crole&$cqual"; 
 7513:             }
 7514:         }
 7515:     }
 7516:     foreach my $role (split(':',$courole)) {
 7517: 	my ($crole,$cqual)=split(/\&/,$role);
 7518:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7519:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7520: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7521:                return "refused:c:$crole&$cqual"; 
 7522:             }
 7523:         }
 7524:     }
 7525:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7526:                 "$env{'user.domain'}:$env{'user.name'}:".
 7527: 	        "rolesdef_$rolename=".
 7528:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7529:     return reply($command,$env{'user.home'});
 7530:   } else {
 7531:     return 'refused';
 7532:   }
 7533: }
 7534: 
 7535: # ---------------- Make a metadata query against the network of library servers
 7536: 
 7537: sub metadata_query {
 7538:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7539:     my %rhash;
 7540:     my %libserv = &all_library();
 7541:     my @server_list = (defined($server_array) ? @$server_array
 7542:                                               : keys(%libserv) );
 7543:     for my $server (@server_list) {
 7544:         my $domains = ''; 
 7545:         if (ref($domains_hash) eq 'HASH') {
 7546:             $domains = $domains_hash->{$server}; 
 7547:         }
 7548: 	unless ($custom or $customshow) {
 7549: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7550: 	    $rhash{$server}=$reply;
 7551: 	}
 7552: 	else {
 7553: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7554: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7555: 			     $server);
 7556: 	    $rhash{$server}=$reply;
 7557: 	}
 7558:     }
 7559:     return \%rhash;
 7560: }
 7561: 
 7562: # ----------------------------------------- Send log queries and wait for reply
 7563: 
 7564: sub log_query {
 7565:     my ($uname,$udom,$query,%filters)=@_;
 7566:     my $uhome=&homeserver($uname,$udom);
 7567:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7568:     my $uhost=&hostname($uhome);
 7569:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7570:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7571:                        $uhome);
 7572:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7573:     return get_query_reply($queryid);
 7574: }
 7575: 
 7576: # -------------------------- Update MySQL table for portfolio file
 7577: 
 7578: sub update_portfolio_table {
 7579:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7580:     if ($group ne '') {
 7581:         $file_name =~s /^\Q$group\E//;
 7582:     }
 7583:     my $homeserver = &homeserver($uname,$udom);
 7584:     my $queryid=
 7585:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7586:                ':'.&escape($file_name).':'.$action,$homeserver);
 7587:     my $reply = &get_query_reply($queryid);
 7588:     return $reply;
 7589: }
 7590: 
 7591: # -------------------------- Update MySQL allusers table
 7592: 
 7593: sub update_allusers_table {
 7594:     my ($uname,$udom,$names) = @_;
 7595:     my $homeserver = &homeserver($uname,$udom);
 7596:     my $queryid=
 7597:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7598:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7599:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7600:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7601:                'generation='.&escape($names->{'generation'}).'%%'.
 7602:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7603:                'id='.&escape($names->{'id'}),$homeserver);
 7604:     return;
 7605: }
 7606: 
 7607: # ------- Request retrieval of institutional classlists for course(s)
 7608: 
 7609: sub fetch_enrollment_query {
 7610:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7611:     my $homeserver;
 7612:     my $maxtries = 1;
 7613:     if ($context eq 'automated') {
 7614:         $homeserver = $perlvar{'lonHostID'};
 7615:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7616:     } else {
 7617:         $homeserver = &homeserver($cnum,$dom);
 7618:     }
 7619:     my $host=&hostname($homeserver);
 7620:     my $cmd = '';
 7621:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7622:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7623:     }
 7624:     $cmd =~ s/%%$//;
 7625:     $cmd = &escape($cmd);
 7626:     my $query = 'fetchenrollment';
 7627:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7628:     unless ($queryid=~/^\Q$host\E\_/) { 
 7629:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7630:         return 'error: '.$queryid;
 7631:     }
 7632:     my $reply = &get_query_reply($queryid);
 7633:     my $tries = 1;
 7634:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7635:         $reply = &get_query_reply($queryid);
 7636:         $tries ++;
 7637:     }
 7638:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7639:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7640:     } else {
 7641:         my @responses = split(/:/,$reply);
 7642:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7643:             foreach my $line (@responses) {
 7644:                 my ($key,$value) = split(/=/,$line,2);
 7645:                 $$replyref{$key} = $value;
 7646:             }
 7647:         } else {
 7648:             my $pathname = LONCAPA::tempdir();
 7649:             foreach my $line (@responses) {
 7650:                 my ($key,$value) = split(/=/,$line);
 7651:                 $$replyref{$key} = $value;
 7652:                 if ($value > 0) {
 7653:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7654:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7655:                         my $destname = $pathname.'/'.$filename;
 7656:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7657:                         if ($xml_classlist =~ /^error/) {
 7658:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7659:                         } else {
 7660:                             if ( open(FILE,">$destname") ) {
 7661:                                 print FILE &unescape($xml_classlist);
 7662:                                 close(FILE);
 7663:                             } else {
 7664:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7665:                             }
 7666:                         }
 7667:                     }
 7668:                 }
 7669:             }
 7670:         }
 7671:         return 'ok';
 7672:     }
 7673:     return 'error';
 7674: }
 7675: 
 7676: sub get_query_reply {
 7677:     my $queryid=shift;
 7678:     my $replyfile=LONCAPA::tempdir().$queryid;
 7679:     my $reply='';
 7680:     for (1..100) {
 7681: 	sleep(0.2);
 7682:         if (-e $replyfile.'.end') {
 7683: 	    if (open(my $fh,$replyfile)) {
 7684: 		$reply = join('',<$fh>);
 7685: 		close($fh);
 7686: 	   } else { return 'error: reply_file_error'; }
 7687:            return &unescape($reply);
 7688: 	}
 7689:     }
 7690:     return 'timeout:'.$queryid;
 7691: }
 7692: 
 7693: sub courselog_query {
 7694: #
 7695: # possible filters:
 7696: # url: url or symb
 7697: # username
 7698: # domain
 7699: # action: view, submit, grade
 7700: # start: timestamp
 7701: # end: timestamp
 7702: #
 7703:     my (%filters)=@_;
 7704:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7705:     if ($filters{'url'}) {
 7706: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7707:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7708:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7709:     }
 7710:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7711:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7712:     return &log_query($cname,$cdom,'courselog',%filters);
 7713: }
 7714: 
 7715: sub userlog_query {
 7716: #
 7717: # possible filters:
 7718: # action: log check role
 7719: # start: timestamp
 7720: # end: timestamp
 7721: #
 7722:     my ($uname,$udom,%filters)=@_;
 7723:     return &log_query($uname,$udom,'userlog',%filters);
 7724: }
 7725: 
 7726: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7727: 
 7728: sub auto_run {
 7729:     my ($cnum,$cdom) = @_;
 7730:     my $response = 0;
 7731:     my $settings;
 7732:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7733:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7734:         $settings = $domconfig{'autoenroll'};
 7735:         if ($settings->{'run'} eq '1') {
 7736:             $response = 1;
 7737:         }
 7738:     } else {
 7739:         my $homeserver;
 7740:         if (&is_course($cdom,$cnum)) {
 7741:             $homeserver = &homeserver($cnum,$cdom);
 7742:         } else {
 7743:             $homeserver = &domain($cdom,'primary');
 7744:         }
 7745:         if ($homeserver ne 'no_host') {
 7746:             $response = &reply('autorun:'.$cdom,$homeserver);
 7747:         }
 7748:     }
 7749:     return $response;
 7750: }
 7751: 
 7752: sub auto_get_sections {
 7753:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7754:     my $homeserver;
 7755:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7756:         $homeserver = &homeserver($cnum,$cdom);
 7757:     }
 7758:     if (!defined($homeserver)) { 
 7759:         if ($cdom =~ /^$match_domain$/) {
 7760:             $homeserver = &domain($cdom,'primary');
 7761:         }
 7762:     }
 7763:     my @secs;
 7764:     if (defined($homeserver)) {
 7765:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7766:         unless ($response eq 'refused') {
 7767:             @secs = split(/:/,$response);
 7768:         }
 7769:     }
 7770:     return @secs;
 7771: }
 7772: 
 7773: sub auto_new_course {
 7774:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7775:     my $homeserver = &homeserver($cnum,$cdom);
 7776:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7777:     return $response;
 7778: }
 7779: 
 7780: sub auto_validate_courseID {
 7781:     my ($cnum,$cdom,$inst_course_id) = @_;
 7782:     my $homeserver = &homeserver($cnum,$cdom);
 7783:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7784:     return $response;
 7785: }
 7786: 
 7787: sub auto_validate_instcode {
 7788:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7789:     my ($homeserver,$response);
 7790:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7791:         $homeserver = &homeserver($cnum,$cdom);
 7792:     }
 7793:     if (!defined($homeserver)) {
 7794:         if ($cdom =~ /^$match_domain$/) {
 7795:             $homeserver = &domain($cdom,'primary');
 7796:         }
 7797:     }
 7798:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7799:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7800:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7801:     return ($outcome,$description,$defaultcredits);
 7802: }
 7803: 
 7804: sub auto_create_password {
 7805:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7806:     my ($homeserver,$response);
 7807:     my $create_passwd = 0;
 7808:     my $authchk = '';
 7809:     if ($udom =~ /^$match_domain$/) {
 7810:         $homeserver = &domain($udom,'primary');
 7811:     }
 7812:     if ($homeserver eq '') {
 7813:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7814:             $homeserver = &homeserver($cnum,$cdom);
 7815:         }
 7816:     }
 7817:     if ($homeserver eq '') {
 7818:         $authchk = 'nodomain';
 7819:     } else {
 7820:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7821:         if ($response eq 'refused') {
 7822:             $authchk = 'refused';
 7823:         } else {
 7824:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7825:         }
 7826:     }
 7827:     return ($authparam,$create_passwd,$authchk);
 7828: }
 7829: 
 7830: sub auto_photo_permission {
 7831:     my ($cnum,$cdom,$students) = @_;
 7832:     my $homeserver = &homeserver($cnum,$cdom);
 7833:     my ($outcome,$perm_reqd,$conditions) = 
 7834: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7835:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7836: 	return (undef,undef);
 7837:     }
 7838:     return ($outcome,$perm_reqd,$conditions);
 7839: }
 7840: 
 7841: sub auto_checkphotos {
 7842:     my ($uname,$udom,$pid) = @_;
 7843:     my $homeserver = &homeserver($uname,$udom);
 7844:     my ($result,$resulttype);
 7845:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7846: 				   &escape($uname).':'.&escape($pid),
 7847: 				   $homeserver));
 7848:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7849: 	return (undef,undef);
 7850:     }
 7851:     if ($outcome) {
 7852:         ($result,$resulttype) = split(/:/,$outcome);
 7853:     } 
 7854:     return ($result,$resulttype);
 7855: }
 7856: 
 7857: sub auto_photochoice {
 7858:     my ($cnum,$cdom) = @_;
 7859:     my $homeserver = &homeserver($cnum,$cdom);
 7860:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7861: 						       &escape($cdom),
 7862: 						       $homeserver)));
 7863:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7864: 	return (undef,undef);
 7865:     }
 7866:     return ($update,$comment);
 7867: }
 7868: 
 7869: sub auto_photoupdate {
 7870:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7871:     my $homeserver = &homeserver($cnum,$dom);
 7872:     my $host=&hostname($homeserver);
 7873:     my $cmd = '';
 7874:     my $maxtries = 1;
 7875:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7876:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7877:     }
 7878:     $cmd =~ s/%%$//;
 7879:     $cmd = &escape($cmd);
 7880:     my $query = 'institutionalphotos';
 7881:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7882:     unless ($queryid=~/^\Q$host\E\_/) {
 7883:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7884:         return 'error: '.$queryid;
 7885:     }
 7886:     my $reply = &get_query_reply($queryid);
 7887:     my $tries = 1;
 7888:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7889:         $reply = &get_query_reply($queryid);
 7890:         $tries ++;
 7891:     }
 7892:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7893:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7894:     } else {
 7895:         my @responses = split(/:/,$reply);
 7896:         my $outcome = shift(@responses); 
 7897:         foreach my $item (@responses) {
 7898:             my ($key,$value) = split(/=/,$item);
 7899:             $$photo{$key} = $value;
 7900:         }
 7901:         return $outcome;
 7902:     }
 7903:     return 'error';
 7904: }
 7905: 
 7906: sub auto_instcode_format {
 7907:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7908: 	$cat_order) = @_;
 7909:     my $courses = '';
 7910:     my @homeservers;
 7911:     if ($caller eq 'global') {
 7912: 	my %servers = &get_servers($codedom,'library');
 7913: 	foreach my $tryserver (keys(%servers)) {
 7914: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7915: 		push(@homeservers,$tryserver);
 7916: 	    }
 7917:         }
 7918:     } elsif ($caller eq 'requests') {
 7919:         if ($codedom =~ /^$match_domain$/) {
 7920:             my $chome = &domain($codedom,'primary');
 7921:             unless ($chome eq 'no_host') {
 7922:                 push(@homeservers,$chome);
 7923:             }
 7924:         }
 7925:     } else {
 7926:         push(@homeservers,&homeserver($caller,$codedom));
 7927:     }
 7928:     foreach my $code (keys(%{$instcodes})) {
 7929:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7930:     }
 7931:     chop($courses);
 7932:     my $ok_response = 0;
 7933:     my $response;
 7934:     while (@homeservers > 0 && $ok_response == 0) {
 7935:         my $server = shift(@homeservers); 
 7936:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7937:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7938:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7939: 		split(/:/,$response);
 7940:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7941:             push(@{$codetitles},&str2array($codetitles_str));
 7942:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7943:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7944:             $ok_response = 1;
 7945:         }
 7946:     }
 7947:     if ($ok_response) {
 7948:         return 'ok';
 7949:     } else {
 7950:         return $response;
 7951:     }
 7952: }
 7953: 
 7954: sub auto_instcode_defaults {
 7955:     my ($domain,$returnhash,$code_order) = @_;
 7956:     my @homeservers;
 7957: 
 7958:     my %servers = &get_servers($domain,'library');
 7959:     foreach my $tryserver (keys(%servers)) {
 7960: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7961: 	    push(@homeservers,$tryserver);
 7962: 	}
 7963:     }
 7964: 
 7965:     my $response;
 7966:     foreach my $server (@homeservers) {
 7967:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7968:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7969: 	
 7970: 	foreach my $pair (split(/\&/,$response)) {
 7971: 	    my ($name,$value)=split(/\=/,$pair);
 7972: 	    if ($name eq 'code_order') {
 7973: 		@{$code_order} = split(/\&/,&unescape($value));
 7974: 	    } else {
 7975: 		$returnhash->{&unescape($name)}=&unescape($value);
 7976: 	    }
 7977: 	}
 7978: 	return 'ok';
 7979:     }
 7980: 
 7981:     return $response;
 7982: }
 7983: 
 7984: sub auto_possible_instcodes {
 7985:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7986:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7987:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7988:         return;
 7989:     }
 7990:     my (@homeservers,$uhome);
 7991:     if (defined(&domain($domain,'primary'))) {
 7992:         $uhome=&domain($domain,'primary');
 7993:         push(@homeservers,&domain($domain,'primary'));
 7994:     } else {
 7995:         my %servers = &get_servers($domain,'library');
 7996:         foreach my $tryserver (keys(%servers)) {
 7997:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7998:                 push(@homeservers,$tryserver);
 7999:             }
 8000:         }
 8001:     }
 8002:     my $response;
 8003:     foreach my $server (@homeservers) {
 8004:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8005:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8006:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8007:             split(':',$response);
 8008:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8009:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8010:         foreach my $item (split('&',$cat_title)) {   
 8011:             my ($name,$value)=split('=',$item);
 8012:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8013:         }
 8014:         foreach my $item (split('&',$cat_order)) {
 8015:             my ($name,$value)=split('=',$item);
 8016:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8017:         }
 8018:         return 'ok';
 8019:     }
 8020:     return $response;
 8021: }
 8022: 
 8023: sub auto_courserequest_checks {
 8024:     my ($dom) = @_;
 8025:     my ($homeserver,%validations);
 8026:     if ($dom =~ /^$match_domain$/) {
 8027:         $homeserver = &domain($dom,'primary');
 8028:     }
 8029:     unless ($homeserver eq 'no_host') {
 8030:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8031:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8032:             my @items = split(/&/,$response);
 8033:             foreach my $item (@items) {
 8034:                 my ($key,$value) = split('=',$item);
 8035:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8036:             }
 8037:         }
 8038:     }
 8039:     return %validations; 
 8040: }
 8041: 
 8042: sub auto_courserequest_validation {
 8043:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8044:     my ($homeserver,$response);
 8045:     if ($dom =~ /^$match_domain$/) {
 8046:         $homeserver = &domain($dom,'primary');
 8047:     }
 8048:     unless ($homeserver eq 'no_host') {
 8049:         my $customdata;
 8050:         if (ref($custominfo) eq 'HASH') {
 8051:             $customdata = &freeze_escape($custominfo);
 8052:         }
 8053:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8054:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8055:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8056:                                     $customdata,$homeserver));
 8057:     }
 8058:     return $response;
 8059: }
 8060: 
 8061: sub auto_validate_class_sec {
 8062:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8063:     my $homeserver = &homeserver($cnum,$cdom);
 8064:     my $ownerlist;
 8065:     if (ref($owners) eq 'ARRAY') {
 8066:         $ownerlist = join(',',@{$owners});
 8067:     } else {
 8068:         $ownerlist = $owners;
 8069:     }
 8070:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8071:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8072:     return $response;
 8073: }
 8074: 
 8075: sub auto_crsreq_update {
 8076:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8077:         $code,$accessstart,$accessend,$inbound) = @_;
 8078:     my ($homeserver,%crsreqresponse);
 8079:     if ($cdom =~ /^$match_domain$/) {
 8080:         $homeserver = &domain($cdom,'primary');
 8081:     }
 8082:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8083:         my $info;
 8084:         if (ref($inbound) eq 'HASH') {
 8085:             $info = &freeze_escape($inbound);
 8086:         }
 8087:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8088:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8089:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8090:                             &escape($title).':'.&escape($code).':'.
 8091:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8092:                             $homeserver);
 8093:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8094:             my @items = split(/&/,$response);
 8095:             foreach my $item (@items) {
 8096:                 my ($key,$value) = split('=',$item);
 8097:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8098:             }
 8099:         }
 8100:     }
 8101:     return \%crsreqresponse;
 8102: }
 8103: 
 8104: sub check_instcode_cloning {
 8105:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8106:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8107:         return;
 8108:     }
 8109:     my $canclone;
 8110:     if (@{$code_order} > 0) {
 8111:         my $instcoderegexp ='^';
 8112:         my @clonecodes = split(/\&/,$cloner);
 8113:         foreach my $item (@{$code_order}) {
 8114:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8115:                 foreach my $pair (@clonecodes) {
 8116:                     my ($key,$val) = split(/\=/,$pair,2);
 8117:                     $val = &unescape($val);
 8118:                     if ($key eq $item) {
 8119:                         $instcoderegexp .= '('.$val.')';
 8120:                         last;
 8121:                     }
 8122:                 }
 8123:             } else {
 8124:                 $instcoderegexp .= $codedefaults->{$item};
 8125:             }
 8126:         }
 8127:         $instcoderegexp .= '$';
 8128:         my (@from,@to);
 8129:         eval {
 8130:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8131:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8132:         };
 8133:         if ((@from > 0) && (@to > 0)) {
 8134:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8135:             if (!@diffs) {
 8136:                 $canclone = 1;
 8137:             }
 8138:         }
 8139:     }
 8140:     return $canclone;
 8141: }
 8142: 
 8143: sub default_instcode_cloning {
 8144:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8145:     my (%codedefaults,@code_order,$canclone);
 8146:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8147:         %codedefaults = %{$codedefaultsref};
 8148:         @code_order = @{$codeorderref};
 8149:     } elsif ($clonedom) {
 8150:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8151:     }
 8152:     if (($domdefclone) && (@code_order)) {
 8153:         my @clonecodes = split(/\+/,$domdefclone);
 8154:         my $instcoderegexp ='^';
 8155:         foreach my $item (@code_order) {
 8156:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8157:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8158:             } else {
 8159:                 $instcoderegexp .= $codedefaults{$item};
 8160:             }
 8161:         }
 8162:         $instcoderegexp .= '$';
 8163:         my (@from,@to);
 8164:         eval {
 8165:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8166:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 8167:         };
 8168:         if ((@from > 0) && (@to > 0)) {
 8169:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8170:             if (!@diffs) {
 8171:                 $canclone = 1;
 8172:             }
 8173:         }
 8174:     }
 8175:     return $canclone;
 8176: }
 8177: 
 8178: # ------------------------------------------------------- Course Group routines
 8179: 
 8180: sub get_coursegroups {
 8181:     my ($cdom,$cnum,$group,$namespace) = @_;
 8182:     return(&dump($namespace,$cdom,$cnum,$group));
 8183: }
 8184: 
 8185: sub modify_coursegroup {
 8186:     my ($cdom,$cnum,$groupsettings) = @_;
 8187:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8188: }
 8189: 
 8190: sub toggle_coursegroup_status {
 8191:     my ($cdom,$cnum,$group,$action) = @_;
 8192:     my ($from_namespace,$to_namespace);
 8193:     if ($action eq 'delete') {
 8194:         $from_namespace = 'coursegroups';
 8195:         $to_namespace = 'deleted_groups';
 8196:     } else {
 8197:         $from_namespace = 'deleted_groups';
 8198:         $to_namespace = 'coursegroups';
 8199:     }
 8200:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8201:     if (my $tmp = &error(%curr_group)) {
 8202:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8203:         return ('read error',$tmp);
 8204:     } else {
 8205:         my %savedsettings = %curr_group; 
 8206:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8207:         my $deloutcome;
 8208:         if ($result eq 'ok') {
 8209:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8210:         } else {
 8211:             return ('write error',$result);
 8212:         }
 8213:         if ($deloutcome eq 'ok') {
 8214:             return 'ok';
 8215:         } else {
 8216:             return ('delete error',$deloutcome);
 8217:         }
 8218:     }
 8219: }
 8220: 
 8221: sub modify_group_roles {
 8222:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8223:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8224:     my $role = 'gr/'.&escape($userprivs);
 8225:     my ($uname,$udom) = split(/:/,$user);
 8226:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8227:     if ($result eq 'ok') {
 8228:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8229:     }
 8230:     return $result;
 8231: }
 8232: 
 8233: sub modify_coursegroup_membership {
 8234:     my ($cdom,$cnum,$membership) = @_;
 8235:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8236:     return $result;
 8237: }
 8238: 
 8239: sub get_active_groups {
 8240:     my ($udom,$uname,$cdom,$cnum) = @_;
 8241:     my $now = time;
 8242:     my %groups = ();
 8243:     foreach my $key (keys(%env)) {
 8244:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8245:             my ($start,$end) = split(/\./,$env{$key});
 8246:             if (($end!=0) && ($end<$now)) { next; }
 8247:             if (($start!=0) && ($start>$now)) { next; }
 8248:             if ($1 eq $cdom && $2 eq $cnum) {
 8249:                 $groups{$3} = $env{$key} ;
 8250:             }
 8251:         }
 8252:     }
 8253:     return %groups;
 8254: }
 8255: 
 8256: sub get_group_membership {
 8257:     my ($cdom,$cnum,$group) = @_;
 8258:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8259: }
 8260: 
 8261: sub get_users_groups {
 8262:     my ($udom,$uname,$courseid) = @_;
 8263:     my @usersgroups;
 8264:     my $cachetime=1800;
 8265: 
 8266:     my $hashid="$udom:$uname:$courseid";
 8267:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8268:     if (defined($cached)) {
 8269:         @usersgroups = split(/:/,$grouplist);
 8270:     } else {  
 8271:         $grouplist = '';
 8272:         my $courseurl = &courseid_to_courseurl($courseid);
 8273:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8274:         my $access_end = $env{'course.'.$courseid.
 8275:                               '.default_enrollment_end_date'};
 8276:         my $now = time;
 8277:         foreach my $key (keys(%roleshash)) {
 8278:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8279:                 my $group = $1;
 8280:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8281:                     my $start = $2;
 8282:                     my $end = $1;
 8283:                     if ($start == -1) { next; } # deleted from group
 8284:                     if (($start!=0) && ($start>$now)) { next; }
 8285:                     if (($end!=0) && ($end<$now)) {
 8286:                         if ($access_end && $access_end < $now) {
 8287:                             if ($access_end - $end < 86400) {
 8288:                                 push(@usersgroups,$group);
 8289:                             }
 8290:                         }
 8291:                         next;
 8292:                     }
 8293:                     push(@usersgroups,$group);
 8294:                 }
 8295:             }
 8296:         }
 8297:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8298:         $grouplist = join(':',@usersgroups);
 8299:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8300:     }
 8301:     return @usersgroups;
 8302: }
 8303: 
 8304: sub devalidate_getgroups_cache {
 8305:     my ($udom,$uname,$cdom,$cnum)=@_;
 8306:     my $courseid = $cdom.'_'.$cnum;
 8307: 
 8308:     my $hashid="$udom:$uname:$courseid";
 8309:     &devalidate_cache_new('getgroups',$hashid);
 8310: }
 8311: 
 8312: # ------------------------------------------------------------------ Plain Text
 8313: 
 8314: sub plaintext {
 8315:     my ($short,$type,$cid,$forcedefault) = @_;
 8316:     if ($short =~ m{^cr/}) {
 8317: 	return (split('/',$short))[-1];
 8318:     }
 8319:     if (!defined($cid)) {
 8320:         $cid = $env{'request.course.id'};
 8321:     }
 8322:     my %rolenames = (
 8323:                       Course    => 'std',
 8324:                       Community => 'alt1',
 8325:                     );
 8326:     if ($cid ne '') {
 8327:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8328:             unless ($forcedefault) {
 8329:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8330:                 &Apache::lonlocal::mt_escape(\$roletext);
 8331:                 return &Apache::lonlocal::mt($roletext);
 8332:             }
 8333:         }
 8334:     }
 8335:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8336:         (defined($rolenames{$type})) && 
 8337:         (defined($prp{$short}{$rolenames{$type}}))) {
 8338:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8339:     } elsif ($cid ne '') {
 8340:         my $crstype = $env{'course.'.$cid.'.type'};
 8341:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8342:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8343:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8344:         }
 8345:     }
 8346:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8347: }
 8348: 
 8349: # ----------------------------------------------------------------- Assign Role
 8350: 
 8351: sub assignrole {
 8352:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8353:         $context)=@_;
 8354:     my $mrole;
 8355:     if ($role =~ /^cr\//) {
 8356:         my $cwosec=$url;
 8357:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8358: 	unless (&allowed('ccr',$cwosec)) {
 8359:            my $refused = 1;
 8360:            if ($context eq 'requestcourses') {
 8361:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8362:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8363:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8364:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8365:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8366:                            if ($crsenv{'internal.courseowner'} eq
 8367:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8368:                                $refused = '';
 8369:                            }
 8370:                        }
 8371:                    }
 8372:                }
 8373:            }
 8374:            if ($refused) {
 8375:                &logthis('Refused custom assignrole: '.
 8376:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8377:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8378:                return 'refused';
 8379:            }
 8380:         }
 8381:         $mrole='cr';
 8382:     } elsif ($role =~ /^gr\//) {
 8383:         my $cwogrp=$url;
 8384:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8385:         unless (&allowed('mdg',$cwogrp)) {
 8386:             &logthis('Refused group assignrole: '.
 8387:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8388:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8389:             return 'refused';
 8390:         }
 8391:         $mrole='gr';
 8392:     } else {
 8393:         my $cwosec=$url;
 8394:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8395:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8396:             my $refused;
 8397:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8398:                 if (!(&allowed('c'.$role,$url))) {
 8399:                     $refused = 1;
 8400:                 }
 8401:             } else {
 8402:                 $refused = 1;
 8403:             }
 8404:             if ($refused) {
 8405:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8406:                 if (!$selfenroll && $context eq 'course') {
 8407:                     my %crsenv;
 8408:                     if ($role eq 'cc' || $role eq 'co') {
 8409:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8410:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8411:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8412:                                 if ($crsenv{'internal.courseowner'} eq 
 8413:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8414:                                     $refused = '';
 8415:                                 }
 8416:                             }
 8417:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8418:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8419:                                 if ($crsenv{'internal.courseowner'} eq 
 8420:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8421:                                     $refused = '';
 8422:                                 }
 8423:                             }
 8424:                         }
 8425:                     }
 8426:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8427:                     $refused = '';
 8428:                 } elsif ($context eq 'requestcourses') {
 8429:                     my @possroles = ('st','ta','ep','in','cc','co');
 8430:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8431:                         my $wrongcc;
 8432:                         if ($cnum =~ /^$match_community$/) {
 8433:                             $wrongcc = 1 if ($role eq 'cc');
 8434:                         } else {
 8435:                             $wrongcc = 1 if ($role eq 'co');
 8436:                         }
 8437:                         unless ($wrongcc) {
 8438:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8439:                             if ($crsenv{'internal.courseowner'} eq 
 8440:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8441:                                 $refused = '';
 8442:                             }
 8443:                         }
 8444:                     }
 8445:                 } elsif ($context eq 'requestauthor') {
 8446:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8447:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8448:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8449:                             $refused = '';
 8450:                         } else {
 8451:                             my %domdefaults = &get_domain_defaults($udom);
 8452:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8453:                                 my $checkbystatus;
 8454:                                 if ($env{'user.adv'}) { 
 8455:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8456:                                     if ($disposition eq 'automatic') {
 8457:                                         $refused = '';
 8458:                                     } elsif ($disposition eq '') {
 8459:                                         $checkbystatus = 1;
 8460:                                     } 
 8461:                                 } else {
 8462:                                     $checkbystatus = 1;
 8463:                                 }
 8464:                                 if ($checkbystatus) {
 8465:                                     if ($env{'environment.inststatus'}) {
 8466:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8467:                                         foreach my $type (@inststatuses) {
 8468:                                             if (($type ne '') &&
 8469:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8470:                                                 $refused = '';
 8471:                                             }
 8472:                                         }
 8473:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8474:                                         $refused = '';
 8475:                                     }
 8476:                                 }
 8477:                             }
 8478:                         }
 8479:                     }
 8480:                 }
 8481:                 if ($refused) {
 8482:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8483:                              ' '.$role.' '.$end.' '.$start.' by '.
 8484: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8485:                     return 'refused';
 8486:                 }
 8487:             }
 8488:         } elsif ($role eq 'au') {
 8489:             if ($url ne '/'.$udom.'/') {
 8490:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8491:                          ' to assign author role for '.$uname.':'.$udom.
 8492:                          ' in domain: '.$url.' refused (wrong domain).');
 8493:                 return 'refused';
 8494:             }
 8495:         }
 8496:         $mrole=$role;
 8497:     }
 8498:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8499:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8500:     if ($end) { $command.='_'.$end; }
 8501:     if ($start) {
 8502: 	if ($end) { 
 8503:            $command.='_'.$start; 
 8504:         } else {
 8505:            $command.='_0_'.$start;
 8506:         }
 8507:     }
 8508:     my $origstart = $start;
 8509:     my $origend = $end;
 8510:     my $delflag;
 8511: # actually delete
 8512:     if ($deleteflag) {
 8513: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8514: # modify command to delete the role
 8515:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8516:                 "$udom:$uname:$url".'_'."$mrole";
 8517: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8518: # set start and finish to negative values for userrolelog
 8519:            $start=-1;
 8520:            $end=-1;
 8521:            $delflag = 1;
 8522:         }
 8523:     }
 8524: # send command
 8525:     my $answer=&reply($command,&homeserver($uname,$udom));
 8526: # log new user role if status is ok
 8527:     if ($answer eq 'ok') {
 8528: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8529:         if (($role eq 'cc') || ($role eq 'in') ||
 8530:             ($role eq 'ep') || ($role eq 'ad') ||
 8531:             ($role eq 'ta') || ($role eq 'st') ||
 8532:             ($role=~/^cr/) || ($role eq 'gr') ||
 8533:             ($role eq 'co')) {
 8534: # for course roles, perform group memberships changes triggered by role change.
 8535:             unless ($role =~ /^gr/) {
 8536:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8537:                                                  $origstart,$selfenroll,$context);
 8538:             }
 8539:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8540:                            $selfenroll,$context);
 8541:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8542:                  ($role eq 'au') || ($role eq 'dc')) {
 8543:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8544:                            $context);
 8545:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8546:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8547:                              $context); 
 8548:         }
 8549:         if ($role eq 'cc') {
 8550:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8551:         }
 8552:     }
 8553:     return $answer;
 8554: }
 8555: 
 8556: sub autoupdate_coowners {
 8557:     my ($url,$end,$start,$uname,$udom) = @_;
 8558:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8559:     if (($cdom ne '') && ($cnum ne '')) {
 8560:         my $now = time;
 8561:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8562:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8563:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8564:             my $instcode = $coursehash{'internal.coursecode'};
 8565:             if ($instcode ne '') {
 8566:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8567:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8568:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8569:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8570:                         if ($result eq 'valid') {
 8571:                             if ($coursehash{'internal.co-owners'}) {
 8572:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8573:                                     push(@newcoowners,$coowner);
 8574:                                 }
 8575:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8576:                                     push(@newcoowners,$uname.':'.$udom);
 8577:                                 }
 8578:                                 @newcoowners = sort(@newcoowners);
 8579:                             } else {
 8580:                                 push(@newcoowners,$uname.':'.$udom);
 8581:                             }
 8582:                         } else {
 8583:                             if ($coursehash{'internal.co-owners'}) {
 8584:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8585:                                     unless ($coowner eq $uname.':'.$udom) {
 8586:                                         push(@newcoowners,$coowner);
 8587:                                     }
 8588:                                 }
 8589:                                 unless (@newcoowners > 0) {
 8590:                                     $delcoowners = 1;
 8591:                                     $coowners = '';
 8592:                                 }
 8593:                             }
 8594:                         }
 8595:                         if (@newcoowners || $delcoowners) {
 8596:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8597:                                             $delcoowners,@newcoowners);
 8598:                         }
 8599:                     }
 8600:                 }
 8601:             }
 8602:         }
 8603:     }
 8604: }
 8605: 
 8606: sub store_coowners {
 8607:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8608:     my $cid = $cdom.'_'.$cnum;
 8609:     my ($coowners,$delresult,$putresult);
 8610:     if (@newcoowners) {
 8611:         $coowners = join(',',@newcoowners);
 8612:         my %coownershash = (
 8613:                             'internal.co-owners' => $coowners,
 8614:                            );
 8615:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8616:         if ($putresult eq 'ok') {
 8617:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8618:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8619:             }
 8620:         }
 8621:     }
 8622:     if ($delcoowners) {
 8623:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8624:         if ($delresult eq 'ok') {
 8625:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8626:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8627:             }
 8628:         }
 8629:     }
 8630:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8631:         my %crsinfo =
 8632:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8633:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8634:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8635:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8636:         }
 8637:     }
 8638: }
 8639: 
 8640: # -------------------------------------------------- Modify user authentication
 8641: # Overrides without validation
 8642: 
 8643: sub modifyuserauth {
 8644:     my ($udom,$uname,$umode,$upass)=@_;
 8645:     my $uhome=&homeserver($uname,$udom);
 8646:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8647:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8648:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8649:              ' in domain '.$env{'request.role.domain'});  
 8650:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8651: 		     &escape($upass),$uhome);
 8652:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8653:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8654:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8655:     &log($udom,,$uname,$uhome,
 8656:         'Authentication changed by '.$env{'user.domain'}.', '.
 8657:                                      $env{'user.name'}.', '.$umode.
 8658:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8659:     unless ($reply eq 'ok') {
 8660:         &logthis('Authentication mode error: '.$reply);
 8661: 	return 'error: '.$reply;
 8662:     }   
 8663:     return 'ok';
 8664: }
 8665: 
 8666: # --------------------------------------------------------------- Modify a user
 8667: 
 8668: sub modifyuser {
 8669:     my ($udom,    $uname, $uid,
 8670:         $umode,   $upass, $first,
 8671:         $middle,  $last,  $gene,
 8672:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8673:     $udom= &LONCAPA::clean_domain($udom);
 8674:     $uname=&LONCAPA::clean_username($uname);
 8675:     my $showcandelete = 'none';
 8676:     if (ref($candelete) eq 'ARRAY') {
 8677:         if (@{$candelete} > 0) {
 8678:             $showcandelete = join(', ',@{$candelete});
 8679:         }
 8680:     }
 8681:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8682:              $umode.', '.$first.', '.$middle.', '.
 8683: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8684:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8685:                                      ' desiredhome not specified'). 
 8686:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8687:              ' in domain '.$env{'request.role.domain'});
 8688:     my $uhome=&homeserver($uname,$udom,'true');
 8689:     my $newuser;
 8690:     if ($uhome eq 'no_host') {
 8691:         $newuser = 1;
 8692:     }
 8693: # ----------------------------------------------------------------- Create User
 8694:     if (($uhome eq 'no_host') && 
 8695: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8696:         my $unhome='';
 8697:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8698:             $unhome = $desiredhome;
 8699: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8700: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8701:         } else { # load balancing routine for determining $unhome
 8702:             my $loadm=10000000;
 8703: 	    my %servers = &get_servers($udom,'library');
 8704: 	    foreach my $tryserver (keys(%servers)) {
 8705: 		my $answer=reply('load',$tryserver);
 8706: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8707: 		    $loadm=$answer;
 8708: 		    $unhome=$tryserver;
 8709: 		}
 8710: 	    }
 8711:         }
 8712:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8713: 	    return 'error: unable to find a home server for '.$uname.
 8714:                    ' in domain '.$udom;
 8715:         }
 8716:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8717:                          &escape($upass),$unhome);
 8718: 	unless ($reply eq 'ok') {
 8719:             return 'error: '.$reply;
 8720:         }   
 8721:         $uhome=&homeserver($uname,$udom,'true');
 8722:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8723: 	    return 'error: unable verify users home machine.';
 8724:         }
 8725:     }   # End of creation of new user
 8726: # ---------------------------------------------------------------------- Add ID
 8727:     if ($uid) {
 8728:        $uid=~tr/A-Z/a-z/;
 8729:        my %uidhash=&idrget($udom,$uname);
 8730:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8731:          && (!$forceid)) {
 8732: 	  unless ($uid eq $uidhash{$uname}) {
 8733: 	      return 'error: user id "'.$uid.'" does not match '.
 8734:                   'current user id "'.$uidhash{$uname}.'".';
 8735:           }
 8736:        } else {
 8737: 	  &idput($udom,($uname => $uid));
 8738:        }
 8739:     }
 8740: # -------------------------------------------------------------- Add names, etc
 8741:     my @tmp=&get('environment',
 8742: 		   ['firstname','middlename','lastname','generation','id',
 8743:                     'permanentemail','inststatus'],
 8744: 		   $udom,$uname);
 8745:     my (%names,%oldnames);
 8746:     if ($tmp[0] =~ m/^error:.*/) { 
 8747:         %names=(); 
 8748:     } else {
 8749:         %names = @tmp;
 8750:         %oldnames = %names;
 8751:     }
 8752: #
 8753: # If name, email and/or uid are blank (e.g., because an uploaded file
 8754: # of users did not contain them), do not overwrite existing values
 8755: # unless field is in $candelete array ref.  
 8756: #
 8757: 
 8758:     my @fields = ('firstname','middlename','lastname','generation',
 8759:                   'permanentemail','id');
 8760:     my %newvalues;
 8761:     if (ref($candelete) eq 'ARRAY') {
 8762:         foreach my $field (@fields) {
 8763:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8764:                 if ($field eq 'firstname') {
 8765:                     $names{$field} = $first;
 8766:                 } elsif ($field eq 'middlename') {
 8767:                     $names{$field} = $middle;
 8768:                 } elsif ($field eq 'lastname') {
 8769:                     $names{$field} = $last;
 8770:                 } elsif ($field eq 'generation') { 
 8771:                     $names{$field} = $gene;
 8772:                 } elsif ($field eq 'permanentemail') {
 8773:                     $names{$field} = $email;
 8774:                 } elsif ($field eq 'id') {
 8775:                     $names{$field}  = $uid;
 8776:                 }
 8777:             }
 8778:         }
 8779:     }
 8780:     if ($first)  { $names{'firstname'}  = $first; }
 8781:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8782:     if ($last)   { $names{'lastname'}   = $last; }
 8783:     if (defined($gene))   { $names{'generation'} = $gene; }
 8784:     if ($email) {
 8785:        $email=~s/[^\w\@\.\-\,]//gs;
 8786:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8787:     }
 8788:     if ($uid) { $names{'id'}  = $uid; }
 8789:     if (defined($inststatus)) {
 8790:         $names{'inststatus'} = '';
 8791:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8792:         if (ref($usertypes) eq 'HASH') {
 8793:             my @okstatuses; 
 8794:             foreach my $item (split(/:/,$inststatus)) {
 8795:                 if (defined($usertypes->{$item})) {
 8796:                     push(@okstatuses,$item);  
 8797:                 }
 8798:             }
 8799:             if (@okstatuses) {
 8800:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8801:             }
 8802:         }
 8803:     }
 8804:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8805:                  $umode.', '.$first.', '.$middle.', '.
 8806:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8807:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8808:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8809:     } else {
 8810:         $logmsg .= ' during self creation';
 8811:     }
 8812:     my $changed;
 8813:     if ($newuser) {
 8814:         $changed = 1;
 8815:     } else {
 8816:         foreach my $field (@fields) {
 8817:             if ($names{$field} ne $oldnames{$field}) {
 8818:                 $changed = 1;
 8819:                 last;
 8820:             }
 8821:         }
 8822:     }
 8823:     unless ($changed) {
 8824:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8825:         &logthis($logmsg);
 8826:         return 'ok';
 8827:     }
 8828:     my $reply = &put('environment', \%names, $udom,$uname);
 8829:     if ($reply ne 'ok') { 
 8830:         return 'error: '.$reply;
 8831:     }
 8832:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8833:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8834:     }
 8835:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8836:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8837:     $logmsg = 'Success modifying user '.$logmsg;
 8838:     &logthis($logmsg);
 8839:     return 'ok';
 8840: }
 8841: 
 8842: # -------------------------------------------------------------- Modify student
 8843: 
 8844: sub modifystudent {
 8845:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8846:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8847:         $selfenroll,$context,$inststatus,$credits)=@_;
 8848:     if (!$cid) {
 8849: 	unless ($cid=$env{'request.course.id'}) {
 8850: 	    return 'not_in_class';
 8851: 	}
 8852:     }
 8853: # --------------------------------------------------------------- Make the user
 8854:     my $reply=&modifyuser
 8855: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8856:          $desiredhome,$email,$inststatus);
 8857:     unless ($reply eq 'ok') { return $reply; }
 8858:     # This will cause &modify_student_enrollment to get the uid from the
 8859:     # student's environment
 8860:     $uid = undef if (!$forceid);
 8861:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8862:                                         $gene,$usec,$end,$start,$type,$locktype,
 8863:                                         $cid,$selfenroll,$context,$credits);
 8864:     return $reply;
 8865: }
 8866: 
 8867: sub modify_student_enrollment {
 8868:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8869:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8870:     my ($cdom,$cnum,$chome);
 8871:     if (!$cid) {
 8872: 	unless ($cid=$env{'request.course.id'}) {
 8873: 	    return 'not_in_class';
 8874: 	}
 8875: 	$cdom=$env{'course.'.$cid.'.domain'};
 8876: 	$cnum=$env{'course.'.$cid.'.num'};
 8877:     } else {
 8878: 	($cdom,$cnum)=split(/_/,$cid);
 8879:     }
 8880:     $chome=$env{'course.'.$cid.'.home'};
 8881:     if (!$chome) {
 8882: 	$chome=&homeserver($cnum,$cdom);
 8883:     }
 8884:     if (!$chome) { return 'unknown_course'; }
 8885:     # Make sure the user exists
 8886:     my $uhome=&homeserver($uname,$udom);
 8887:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8888: 	return 'error: no such user';
 8889:     }
 8890:     # Get student data if we were not given enough information
 8891:     if (!defined($first)  || $first  eq '' || 
 8892:         !defined($last)   || $last   eq '' || 
 8893:         !defined($uid)    || $uid    eq '' || 
 8894:         !defined($middle) || $middle eq '' || 
 8895:         !defined($gene)   || $gene   eq '') {
 8896:         # They did not supply us with enough data to enroll the student, so
 8897:         # we need to pick up more information.
 8898:         my %tmp = &get('environment',
 8899:                        ['firstname','middlename','lastname', 'generation','id']
 8900:                        ,$udom,$uname);
 8901: 
 8902:         #foreach my $key (keys(%tmp)) {
 8903:         #    &logthis("key $key = ".$tmp{$key});
 8904:         #}
 8905:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8906:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8907:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8908:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8909:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8910:     }
 8911:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8912:     my $user = "$uname:$udom";
 8913:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8914:     my $reply=cput('classlist',
 8915: 		   {$user => 
 8916: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8917: 		   $cdom,$cnum);
 8918:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8919:         &devalidate_getsection_cache($udom,$uname,$cid);
 8920:     } else { 
 8921: 	return 'error: '.$reply;
 8922:     }
 8923:     # Add student role to user
 8924:     my $uurl='/'.$cid;
 8925:     $uurl=~s/\_/\//g;
 8926:     if ($usec) {
 8927: 	$uurl.='/'.$usec;
 8928:     }
 8929:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8930:                              $selfenroll,$context);
 8931:     if ($result ne 'ok') {
 8932:         if ($old_entry{$user} ne '') {
 8933:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8934:         } else {
 8935:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8936:         }
 8937:     }
 8938:     return $result; 
 8939: }
 8940: 
 8941: sub format_name {
 8942:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8943:     my $name;
 8944:     if ($first ne 'lastname') {
 8945: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8946:     } else {
 8947: 	if ($lastname=~/\S/) {
 8948: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8949: 	    $name=~s/\s+,/,/;
 8950: 	} else {
 8951: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8952: 	}
 8953:     }
 8954:     $name=~s/^\s+//;
 8955:     $name=~s/\s+$//;
 8956:     $name=~s/\s+/ /g;
 8957:     return $name;
 8958: }
 8959: 
 8960: # ------------------------------------------------- Write to course preferences
 8961: 
 8962: sub writecoursepref {
 8963:     my ($courseid,%prefs)=@_;
 8964:     $courseid=~s/^\///;
 8965:     $courseid=~s/\_/\//g;
 8966:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8967:     my $chome=homeserver($cnum,$cdomain);
 8968:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8969: 	return 'error: no such course';
 8970:     }
 8971:     my $cstring='';
 8972:     foreach my $pref (keys(%prefs)) {
 8973: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8974:     }
 8975:     $cstring=~s/\&$//;
 8976:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8977: }
 8978: 
 8979: # ---------------------------------------------------------- Make/modify course
 8980: 
 8981: sub createcourse {
 8982:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8983:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8984:     $url=&declutter($url);
 8985:     my $cid='';
 8986:     if ($context eq 'requestcourses') {
 8987:         my $can_create = 0;
 8988:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8989:         if ($udom eq $ownerdom) {
 8990:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8991:                                   $context)) {
 8992:                 $can_create = 1;
 8993:             }
 8994:         } else {
 8995:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8996:                                            $category);
 8997:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8998:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8999:                 if (@curr > 0) {
 9000:                     my @options = qw(approval validate autolimit);
 9001:                     my $optregex = join('|',@options);
 9002:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9003:                         $can_create = 1;
 9004:                     }
 9005:                 }
 9006:             }
 9007:         }
 9008:         if ($can_create) {
 9009:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9010:                 unless (&allowed('ccc',$udom)) {
 9011:                     return 'refused'; 
 9012:                 }
 9013:             }
 9014:         } else {
 9015:             return 'refused';
 9016:         }
 9017:     } elsif (!&allowed('ccc',$udom)) {
 9018:         return 'refused';
 9019:     }
 9020: # --------------------------------------------------------------- Get Unique ID
 9021:     my $uname;
 9022:     if ($cnum =~ /^$match_courseid$/) {
 9023:         my $chome=&homeserver($cnum,$udom,'true');
 9024:         if (($chome eq '') || ($chome eq 'no_host')) {
 9025:             $uname = $cnum;
 9026:         } else {
 9027:             $uname = &generate_coursenum($udom,$crstype);
 9028:         }
 9029:     } else {
 9030:         $uname = &generate_coursenum($udom,$crstype);
 9031:     }
 9032:     return $uname if ($uname =~ /^error/);
 9033: # -------------------------------------------------- Check supplied server name
 9034:     if (!defined($course_server)) {
 9035:         if (defined(&domain($udom,'primary'))) {
 9036:             $course_server = &domain($udom,'primary');
 9037:         } else {
 9038:             $course_server = $env{'user.home'}; 
 9039:         }
 9040:     }
 9041:     my %host_servers =
 9042:         &Apache::lonnet::get_servers($udom,'library');
 9043:     unless ($host_servers{$course_server}) {
 9044:         return 'error: invalid home server for course: '.$course_server;
 9045:     }
 9046: # ------------------------------------------------------------- Make the course
 9047:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9048:                       $course_server);
 9049:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9050:     my $uhome=&homeserver($uname,$udom,'true');
 9051:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9052: 	return 'error: no such course';
 9053:     }
 9054: # ----------------------------------------------------------------- Course made
 9055: # log existence
 9056:     my $now = time;
 9057:     my $newcourse = {
 9058:                     $udom.'_'.$uname => {
 9059:                                      description => $description,
 9060:                                      inst_code   => $inst_code,
 9061:                                      owner       => $course_owner,
 9062:                                      type        => $crstype,
 9063:                                      creator     => $env{'user.name'}.':'.
 9064:                                                     $env{'user.domain'},
 9065:                                      created     => $now,
 9066:                                      context     => $context,
 9067:                                                 },
 9068:                     };
 9069:     &courseidput($udom,$newcourse,$uhome,'notime');
 9070: # set toplevel url
 9071:     my $topurl=$url;
 9072:     unless ($nonstandard) {
 9073: # ------------------------------------------ For standard courses, make top url
 9074:         my $mapurl=&clutter($url);
 9075:         if ($mapurl eq '/res/') { $mapurl=''; }
 9076:         $env{'form.initmap'}=(<<ENDINITMAP);
 9077: <map>
 9078: <resource id="1" type="start"></resource>
 9079: <resource id="2" src="$mapurl"></resource>
 9080: <resource id="3" type="finish"></resource>
 9081: <link index="1" from="1" to="2"></link>
 9082: <link index="2" from="2" to="3"></link>
 9083: </map>
 9084: ENDINITMAP
 9085:         $topurl=&declutter(
 9086:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9087:                           );
 9088:     }
 9089: # ----------------------------------------------------------- Write preferences
 9090:     &writecoursepref($udom.'_'.$uname,
 9091:                      ('description'              => $description,
 9092:                       'url'                      => $topurl,
 9093:                       'internal.creator'         => $env{'user.name'}.':'.
 9094:                                                     $env{'user.domain'},
 9095:                       'internal.created'         => $now,
 9096:                       'internal.creationcontext' => $context)
 9097:                     );
 9098:     return '/'.$udom.'/'.$uname;
 9099: }
 9100: 
 9101: # ------------------------------------------------------------------- Create ID
 9102: sub generate_coursenum {
 9103:     my ($udom,$crstype) = @_;
 9104:     my $domdesc = &domain($udom);
 9105:     return 'error: invalid domain' if ($domdesc eq '');
 9106:     my $first;
 9107:     if ($crstype eq 'Community') {
 9108:         $first = '0';
 9109:     } else {
 9110:         $first = int(1+rand(9)); 
 9111:     } 
 9112:     my $uname=$first.
 9113:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9114:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9115:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9116: # ----------------------------------------------- Make sure that does not exist
 9117:     my $uhome=&homeserver($uname,$udom,'true');
 9118:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9119:         if ($crstype eq 'Community') {
 9120:             $first = '0';
 9121:         } else {
 9122:             $first = int(1+rand(9));
 9123:         }
 9124:         $uname=$first.
 9125:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9126:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9127:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9128:         $uhome=&homeserver($uname,$udom,'true');
 9129:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9130:             return 'error: unable to generate unique course-ID';
 9131:         }
 9132:     }
 9133:     return $uname;
 9134: }
 9135: 
 9136: sub is_course {
 9137:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9138:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9139: 
 9140:     return unless $cdom and $cnum;
 9141: 
 9142:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9143:         '.');
 9144: 
 9145:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9146:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9147: }
 9148: 
 9149: sub store_userdata {
 9150:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9151:     my $result;
 9152:     if ($datakey ne '') {
 9153:         if (ref($storehash) eq 'HASH') {
 9154:             if ($udom eq '' || $uname eq '') {
 9155:                 $udom = $env{'user.domain'};
 9156:                 $uname = $env{'user.name'};
 9157:             }
 9158:             my $uhome=&homeserver($uname,$udom);
 9159:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9160:                 $result = 'error: no_host';
 9161:             } else {
 9162:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9163:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9164: 
 9165:                 my $namevalue='';
 9166:                 foreach my $key (keys(%{$storehash})) {
 9167:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9168:                 }
 9169:                 $namevalue=~s/\&$//;
 9170:                 unless ($namespace eq 'courserequests') {
 9171:                     $datakey = &escape($datakey);
 9172:                 }
 9173:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9174:                                   $namevalue,$uhome);
 9175:             }
 9176:         } else {
 9177:             $result = 'error: data to store was not a hash reference'; 
 9178:         }
 9179:     } else {
 9180:         $result= 'error: invalid requestkey'; 
 9181:     }
 9182:     return $result;
 9183: }
 9184: 
 9185: # ---------------------------------------------------------- Assign Custom Role
 9186: 
 9187: sub assigncustomrole {
 9188:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9189:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9190:                        $end,$start,$deleteflag,$selfenroll,$context);
 9191: }
 9192: 
 9193: # ----------------------------------------------------------------- Revoke Role
 9194: 
 9195: sub revokerole {
 9196:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9197:     my $now=time;
 9198:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9199: }
 9200: 
 9201: # ---------------------------------------------------------- Revoke Custom Role
 9202: 
 9203: sub revokecustomrole {
 9204:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9205:     my $now=time;
 9206:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9207:            $deleteflag,$selfenroll,$context);
 9208: }
 9209: 
 9210: # ------------------------------------------------------------ Disk usage
 9211: sub diskusage {
 9212:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9213:     $directorypath =~ s/\/$//;
 9214:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9215:                        .&escape($getpropath).':'.&escape($uname).':'
 9216:                        .&escape($udom),homeserver($uname,$udom));
 9217:     if ($listing eq 'unknown_cmd') {
 9218:         if ($getpropath) {
 9219:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9220:         }
 9221:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9222:     }
 9223:     return $listing;
 9224: }
 9225: 
 9226: sub is_locked {
 9227:     my ($file_name, $domain, $user, $which) = @_;
 9228:     my @check;
 9229:     my $is_locked;
 9230:     push (@check,$file_name);
 9231:     my %locked = &get('file_permissions',\@check,
 9232: 		      $env{'user.domain'},$env{'user.name'});
 9233:     my ($tmp)=keys(%locked);
 9234:     if ($tmp=~/^error:/) { undef(%locked); }
 9235:     
 9236:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9237:         $is_locked = 'false';
 9238:         foreach my $entry (@{$locked{$file_name}}) {
 9239:            if (ref($entry) eq 'ARRAY') {
 9240:                $is_locked = 'true';
 9241:                if (ref($which) eq 'ARRAY') {
 9242:                    push(@{$which},$entry);
 9243:                } else {
 9244:                    last;
 9245:                }
 9246:            }
 9247:        }
 9248:     } else {
 9249:         $is_locked = 'false';
 9250:     }
 9251:     return $is_locked;
 9252: }
 9253: 
 9254: sub declutter_portfile {
 9255:     my ($file) = @_;
 9256:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9257:     return $file;
 9258: }
 9259: 
 9260: # ------------------------------------------------------------- Mark as Read Only
 9261: 
 9262: sub mark_as_readonly {
 9263:     my ($domain,$user,$files,$what) = @_;
 9264:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9265:     my ($tmp)=keys(%current_permissions);
 9266:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9267:     foreach my $file (@{$files}) {
 9268: 	$file = &declutter_portfile($file);
 9269:         push(@{$current_permissions{$file}},$what);
 9270:     }
 9271:     &put('file_permissions',\%current_permissions,$domain,$user);
 9272:     return;
 9273: }
 9274: 
 9275: # ------------------------------------------------------------Save Selected Files
 9276: 
 9277: sub save_selected_files {
 9278:     my ($user, $path, @files) = @_;
 9279:     my $filename = $user."savedfiles";
 9280:     my @other_files = &files_not_in_path($user, $path);
 9281:     open (OUT, '>'.$tmpdir.$filename);
 9282:     foreach my $file (@files) {
 9283:         print (OUT $env{'form.currentpath'}.$file."\n");
 9284:     }
 9285:     foreach my $file (@other_files) {
 9286:         print (OUT $file."\n");
 9287:     }
 9288:     close (OUT);
 9289:     return 'ok';
 9290: }
 9291: 
 9292: sub clear_selected_files {
 9293:     my ($user) = @_;
 9294:     my $filename = $user."savedfiles";
 9295:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9296:     print (OUT undef);
 9297:     close (OUT);
 9298:     return ("ok");    
 9299: }
 9300: 
 9301: sub files_in_path {
 9302:     my ($user, $path) = @_;
 9303:     my $filename = $user."savedfiles";
 9304:     my %return_files;
 9305:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9306:     while (my $line_in = <IN>) {
 9307:         chomp ($line_in);
 9308:         my @paths_and_file = split (m!/!, $line_in);
 9309:         my $file_part = pop (@paths_and_file);
 9310:         my $path_part = join ('/', @paths_and_file);
 9311:         $path_part.='/';
 9312:         my $path_and_file = $path_part.$file_part;
 9313:         if ($path_part eq $path) {
 9314:             $return_files{$file_part}= 'selected';
 9315:         }
 9316:     }
 9317:     close (IN);
 9318:     return (\%return_files);
 9319: }
 9320: 
 9321: # called in portfolio select mode, to show files selected NOT in current directory
 9322: sub files_not_in_path {
 9323:     my ($user, $path) = @_;
 9324:     my $filename = $user."savedfiles";
 9325:     my @return_files;
 9326:     my $path_part;
 9327:     open(IN, '<'.LONCAPA::.$filename);
 9328:     while (my $line = <IN>) {
 9329:         #ok, I know it's clunky, but I want it to work
 9330:         my @paths_and_file = split(m|/|, $line);
 9331:         my $file_part = pop(@paths_and_file);
 9332:         chomp($file_part);
 9333:         my $path_part = join('/', @paths_and_file);
 9334:         $path_part .= '/';
 9335:         my $path_and_file = $path_part.$file_part;
 9336:         if ($path_part ne $path) {
 9337:             push(@return_files, ($path_and_file));
 9338:         }
 9339:     }
 9340:     close(OUT);
 9341:     return (@return_files);
 9342: }
 9343: 
 9344: #------------------------------Submitted/Handedback Portfolio Files Versioning
 9345:  
 9346: sub portfiles_versioning {
 9347:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
 9348:     my $portfolio_root = '/userfiles/portfolio';
 9349:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
 9350:     foreach my $file (@{$portfiles}) {
 9351:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 9352:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 9353:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
 9354:         my $getpropath = 1;
 9355:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
 9356:                                              $stu_name,$getpropath);
 9357:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 9358:         my $new_answer = 
 9359:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
 9360:         if ($new_answer ne 'problem getting file') {
 9361:             push(@{$versioned_portfiles}, $directory.$new_answer);
 9362:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
 9363:                               [$symb,$env{'request.course.id'},'graded']);
 9364:         }
 9365:     }
 9366: }
 9367: 
 9368: sub get_next_version {
 9369:     my ($answer_name, $answer_ext, $dir_list) = @_;
 9370:     my $version;
 9371:     if (ref($dir_list) eq 'ARRAY') {
 9372:         foreach my $row (@{$dir_list}) {
 9373:             my ($file) = split(/\&/,$row,2);
 9374:             my ($file_name,$file_version,$file_ext) =
 9375:                 &file_name_version_ext($file);
 9376:             if (($file_name eq $answer_name) &&
 9377:                 ($file_ext eq $answer_ext)) {
 9378:                      # gets here if filename and extension match,
 9379:                      # regardless of version
 9380:                 if ($file_version ne '') {
 9381:                     # a versioned file is found  so save it for later
 9382:                     if ($file_version > $version) {
 9383:                         $version = $file_version;
 9384:                     }
 9385:                 }
 9386:             }
 9387:         }
 9388:     }
 9389:     $version ++;
 9390:     return($version);
 9391: }
 9392: 
 9393: sub version_selected_portfile {
 9394:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 9395:     my ($answer_name,$answer_ver,$answer_ext) =
 9396:         &file_name_version_ext($file_name);
 9397:     my $new_answer;
 9398:     $env{'form.copy'} =
 9399:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 9400:     if($env{'form.copy'} eq '-1') {
 9401:         $new_answer = 'problem getting file';
 9402:     } else {
 9403:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 9404:         my $copy_result = 
 9405:             &finishuserfileupload($stu_name,$domain,'copy',
 9406:                                   '/portfolio'.$directory.$new_answer);
 9407:     }
 9408:     undef($env{'form.copy'});
 9409:     return ($new_answer);
 9410: }
 9411: 
 9412: sub file_name_version_ext {
 9413:     my ($file)=@_;
 9414:     my @file_parts = split(/\./, $file);
 9415:     my ($name,$version,$ext);
 9416:     if (@file_parts > 1) {
 9417:         $ext=pop(@file_parts);
 9418:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 9419:             $version=pop(@file_parts);
 9420:         }
 9421:         $name=join('.',@file_parts);
 9422:     } else {
 9423:         $name=join('.',@file_parts);
 9424:     }
 9425:     return($name,$version,$ext);
 9426: }
 9427: 
 9428: #----------------------------------------------Get portfolio file permissions
 9429: 
 9430: sub get_portfile_permissions {
 9431:     my ($domain,$user) = @_;
 9432:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9433:     my ($tmp)=keys(%current_permissions);
 9434:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9435:     return \%current_permissions;
 9436: }
 9437: 
 9438: #---------------------------------------------Get portfolio file access controls
 9439: 
 9440: sub get_access_controls {
 9441:     my ($current_permissions,$group,$file) = @_;
 9442:     my %access;
 9443:     my $real_file = $file;
 9444:     $file =~ s/\.meta$//;
 9445:     if (defined($file)) {
 9446:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9447:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9448:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9449:             }
 9450:         }
 9451:     } else {
 9452:         foreach my $key (keys(%{$current_permissions})) {
 9453:             if ($key =~ /\0accesscontrol$/) {
 9454:                 if (defined($group)) {
 9455:                     if ($key !~ m-^\Q$group\E/-) {
 9456:                         next;
 9457:                     }
 9458:                 }
 9459:                 my ($fullpath) = split(/\0/,$key);
 9460:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9461:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9462:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9463:                     }
 9464:                 }
 9465:             }
 9466:         }
 9467:     }
 9468:     return %access;
 9469: }
 9470: 
 9471: sub modify_access_controls {
 9472:     my ($file_name,$changes,$domain,$user)=@_;
 9473:     my ($outcome,$deloutcome);
 9474:     my %store_permissions;
 9475:     my %new_values;
 9476:     my %new_control;
 9477:     my %translation;
 9478:     my @deletions = ();
 9479:     my $now = time;
 9480:     if (exists($$changes{'activate'})) {
 9481:         if (ref($$changes{'activate'}) eq 'HASH') {
 9482:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9483:             my $numnew = scalar(@newitems);
 9484:             for (my $i=0; $i<$numnew; $i++) {
 9485:                 my $newkey = $newitems[$i];
 9486:                 my $newid = &Apache::loncommon::get_cgi_id();
 9487:                 if ($newkey =~ /^\d+:/) { 
 9488:                     $newkey =~ s/^(\d+)/$newid/;
 9489:                     $translation{$1} = $newid;
 9490:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9491:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9492:                     $translation{$1} = $newid;
 9493:                 }
 9494:                 $new_values{$file_name."\0".$newkey} = 
 9495:                                           $$changes{'activate'}{$newitems[$i]};
 9496:                 $new_control{$newkey} = $now;
 9497:             }
 9498:         }
 9499:     }
 9500:     my %todelete;
 9501:     my %changed_items;
 9502:     foreach my $action ('delete','update') {
 9503:         if (exists($$changes{$action})) {
 9504:             if (ref($$changes{$action}) eq 'HASH') {
 9505:                 foreach my $key (keys(%{$$changes{$action}})) {
 9506:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9507:                     if ($action eq 'delete') { 
 9508:                         $todelete{$itemnum} = 1;
 9509:                     } else {
 9510:                         $changed_items{$itemnum} = $key;
 9511:                     }
 9512:                 }
 9513:             }
 9514:         }
 9515:     }
 9516:     # get lock on access controls for file.
 9517:     my $lockhash = {
 9518:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9519:                                                        ':'.$env{'user.domain'},
 9520:                    }; 
 9521:     my $tries = 0;
 9522:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9523:    
 9524:     while (($gotlock ne 'ok') && $tries < 10) {
 9525:         $tries ++;
 9526:         sleep(0.1);
 9527:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9528:     }
 9529:     if ($gotlock eq 'ok') {
 9530:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9531:         my ($tmp)=keys(%curr_permissions);
 9532:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9533:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9534:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9535:             if (ref($curr_controls) eq 'HASH') {
 9536:                 foreach my $control_item (keys(%{$curr_controls})) {
 9537:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9538:                     if (defined($todelete{$itemnum})) {
 9539:                         push(@deletions,$file_name."\0".$control_item);
 9540:                     } else {
 9541:                         if (defined($changed_items{$itemnum})) {
 9542:                             $new_control{$changed_items{$itemnum}} = $now;
 9543:                             push(@deletions,$file_name."\0".$control_item);
 9544:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9545:                         } else {
 9546:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9547:                         }
 9548:                     }
 9549:                 }
 9550:             }
 9551:         }
 9552:         my ($group);
 9553:         if (&is_course($domain,$user)) {
 9554:             ($group,my $file) = split(/\//,$file_name,2);
 9555:         }
 9556:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9557:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9558:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9559:         #  remove lock
 9560:         my @del_lock = ($file_name."\0".'locked_access_records');
 9561:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9562:         my $sqlresult =
 9563:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9564:                                     $group);
 9565:     } else {
 9566:         $outcome = "error: could not obtain lockfile\n";  
 9567:     }
 9568:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9569: }
 9570: 
 9571: sub make_public_indefinitely {
 9572:     my (@requrl) = @_;
 9573:     return &automated_portfile_access('public',\@requrl);
 9574: }
 9575: 
 9576: sub automated_portfile_access {
 9577:     my ($accesstype,$addsref,$delsref,$info) = @_;
 9578:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
 9579:         return 'invalid';
 9580:     }
 9581:     my %urls;
 9582:     if (ref($addsref) eq 'ARRAY') {
 9583:         foreach my $requrl (@{$addsref}) {
 9584:             if (&is_portfolio_url($requrl)) {
 9585:                 unless (exists($urls{$requrl})) {
 9586:                     $urls{$requrl} = 'add';
 9587:                 }
 9588:             }
 9589:         }
 9590:     }
 9591:     if (ref($delsref) eq 'ARRAY') {
 9592:         foreach my $requrl (@{$delsref}) { 
 9593:             if (&is_portfolio_url($requrl)) {
 9594:                 unless (exists($urls{$requrl})) {
 9595:                     $urls{$requrl} = 'delete'; 
 9596:                 }
 9597:             }
 9598:         }
 9599:     }
 9600:     unless (keys(%urls)) {
 9601:         return 'invalid';
 9602:     }
 9603:     my $ip;
 9604:     if ($accesstype eq 'ip') {
 9605:         if (ref($info) eq 'HASH') {
 9606:             if ($info->{'ip'} ne '') {
 9607:                 $ip = $info->{'ip'};
 9608:             }
 9609:         }
 9610:         if ($ip eq '') {
 9611:             return 'invalid';
 9612:         }
 9613:     }
 9614:     my $errors;
 9615:     my $now = time;
 9616:     my %current_perms;
 9617:     foreach my $requrl (sort(keys(%urls))) {
 9618:         my $action;
 9619:         if ($urls{$requrl} eq 'add') {
 9620:             $action = 'activate';
 9621:         } else {
 9622:             $action = 'none';
 9623:         }
 9624:         my $aclnum = 0;
 9625:         my (undef,$udom,$unum,$file_name,$group) =
 9626:             &parse_portfolio_url($requrl);
 9627:         unless (exists($current_perms{$unum.':'.$udom})) {
 9628:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
 9629:         }
 9630:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
 9631:                                                    $group,$file_name);
 9632:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9633:             my ($num,$scope,$end,$start) = 
 9634:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9635:             if ($scope eq $accesstype) {
 9636:                 if (($start <= $now) && ($end == 0)) {
 9637:                     if ($accesstype eq 'ip') {
 9638:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
 9639:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
 9640:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
 9641:                                     if ($urls{$requrl} eq 'add') {
 9642:                                         $action = 'none';
 9643:                                         last;
 9644:                                     } else {
 9645:                                         $action = 'delete';
 9646:                                         $aclnum = $num;
 9647:                                         last;
 9648:                                     }
 9649:                                 }
 9650:                             }
 9651:                         }
 9652:                     } elsif ($accesstype eq 'public') {
 9653:                         if ($urls{$requrl} eq 'add') {
 9654:                             $action = 'none';
 9655:                             last;
 9656:                         } else {
 9657:                             $action = 'delete';
 9658:                             $aclnum = $num;
 9659:                             last;
 9660:                         }
 9661:                     }
 9662:                 } elsif ($accesstype eq 'public') {
 9663:                     $action = 'update';
 9664:                     $aclnum = $num;
 9665:                     last;
 9666:                 }
 9667:             }
 9668:         }
 9669:         if ($action eq 'none') {
 9670:             next;
 9671:         } else {
 9672:             my %changes;
 9673:             my $newend = 0;
 9674:             my $newstart = $now;
 9675:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
 9676:             $changes{$action}{$newkey} = {
 9677:                 type => $accesstype,
 9678:                 time => {
 9679:                     start => $newstart,
 9680:                     end   => $newend,
 9681:                 },
 9682:             };
 9683:             if ($accesstype eq 'ip') {
 9684:                 $changes{$action}{$newkey}{'ip'} = [$ip];
 9685:             }
 9686:             my ($outcome,$deloutcome,$new_values,$translation) =
 9687:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9688:             unless ($outcome eq 'ok') {
 9689:                 $errors .= $outcome.' ';
 9690:             }
 9691:         }
 9692:     }
 9693:     if ($errors) {
 9694:         $errors =~ s/\s$//;
 9695:         return $errors;
 9696:     } else {
 9697:         return 'ok';
 9698:     }
 9699: }
 9700: 
 9701: #------------------------------------------------------Get Marked as Read Only
 9702: 
 9703: sub get_marked_as_readonly {
 9704:     my ($domain,$user,$what,$group) = @_;
 9705:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9706:     my @readonly_files;
 9707:     my $cmp1=$what;
 9708:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9709:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9710:         if (defined($group)) {
 9711:             if ($file_name !~ m-^\Q$group\E/-) {
 9712:                 next;
 9713:             }
 9714:         }
 9715:         if (ref($value) eq "ARRAY"){
 9716:             foreach my $stored_what (@{$value}) {
 9717:                 my $cmp2=$stored_what;
 9718:                 if (ref($stored_what) eq 'ARRAY') {
 9719:                     $cmp2=join('',@{$stored_what});
 9720:                 }
 9721:                 if ($cmp1 eq $cmp2) {
 9722:                     push(@readonly_files, $file_name);
 9723:                     last;
 9724:                 } elsif (!defined($what)) {
 9725:                     push(@readonly_files, $file_name);
 9726:                     last;
 9727:                 }
 9728:             }
 9729:         }
 9730:     }
 9731:     return @readonly_files;
 9732: }
 9733: #-----------------------------------------------------------Get Marked as Read Only Hash
 9734: 
 9735: sub get_marked_as_readonly_hash {
 9736:     my ($current_permissions,$group,$what) = @_;
 9737:     my %readonly_files;
 9738:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9739:         if (defined($group)) {
 9740:             if ($file_name !~ m-^\Q$group\E/-) {
 9741:                 next;
 9742:             }
 9743:         }
 9744:         if (ref($value) eq "ARRAY"){
 9745:             foreach my $stored_what (@{$value}) {
 9746:                 if (ref($stored_what) eq 'ARRAY') {
 9747:                     foreach my $lock_descriptor(@{$stored_what}) {
 9748:                         if ($lock_descriptor eq 'graded') {
 9749:                             $readonly_files{$file_name} = 'graded';
 9750:                         } elsif ($lock_descriptor eq 'handback') {
 9751:                             $readonly_files{$file_name} = 'handback';
 9752:                         } else {
 9753:                             if (!exists($readonly_files{$file_name})) {
 9754:                                 $readonly_files{$file_name} = 'locked';
 9755:                             }
 9756:                         }
 9757:                     }
 9758:                 } 
 9759:             }
 9760:         } 
 9761:     }
 9762:     return %readonly_files;
 9763: }
 9764: # ------------------------------------------------------------ Unmark as Read Only
 9765: 
 9766: sub unmark_as_readonly {
 9767:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9768:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9769:     my ($domain,$user,$what,$file_name,$group) = @_;
 9770:     $file_name = &declutter_portfile($file_name);
 9771:     my $symb_crs = $what;
 9772:     if (ref($what)) { $symb_crs=join('',@$what); }
 9773:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9774:     my ($tmp)=keys(%current_permissions);
 9775:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9776:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9777:     foreach my $file (@readonly_files) {
 9778: 	my $clean_file = &declutter_portfile($file);
 9779: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9780: 	my $current_locks = $current_permissions{$file};
 9781:         my @new_locks;
 9782:         my @del_keys;
 9783:         if (ref($current_locks) eq "ARRAY"){
 9784:             foreach my $locker (@{$current_locks}) {
 9785:                 my $compare=$locker;
 9786:                 if (ref($locker) eq 'ARRAY') {
 9787:                     $compare=join('',@{$locker});
 9788:                     if ($compare ne $symb_crs) {
 9789:                         push(@new_locks, $locker);
 9790:                     }
 9791:                 }
 9792:             }
 9793:             if (scalar(@new_locks) > 0) {
 9794:                 $current_permissions{$file} = \@new_locks;
 9795:             } else {
 9796:                 push(@del_keys, $file);
 9797:                 &del('file_permissions',\@del_keys, $domain, $user);
 9798:                 delete($current_permissions{$file});
 9799:             }
 9800:         }
 9801:     }
 9802:     &put('file_permissions',\%current_permissions,$domain,$user);
 9803:     return;
 9804: }
 9805: 
 9806: # ------------------------------------------------------------ Directory lister
 9807: 
 9808: sub dirlist {
 9809:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9810:     $uri=~s/^\///;
 9811:     $uri=~s/\/$//;
 9812:     my ($udom, $uname);
 9813:     if ($getuserdir) {
 9814:         $udom = $userdomain;
 9815:         $uname = $username;
 9816:     } else {
 9817:         (undef,$udom,$uname)=split(/\//,$uri);
 9818:         if(defined($userdomain)) {
 9819:             $udom = $userdomain;
 9820:         }
 9821:         if(defined($username)) {
 9822:             $uname = $username;
 9823:         }
 9824:     }
 9825:     my ($dirRoot,$listing,@listing_results);
 9826: 
 9827:     $dirRoot = $perlvar{'lonDocRoot'};
 9828:     if (defined($getpropath)) {
 9829:         $dirRoot = &propath($udom,$uname);
 9830:         $dirRoot =~ s/\/$//;
 9831:     } elsif (defined($getuserdir)) {
 9832:         my $subdir=$uname.'__';
 9833:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9834:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9835:                    ."/$udom/$subdir/$uname";
 9836:     } elsif (defined($alternateRoot)) {
 9837:         $dirRoot = $alternateRoot;
 9838:     }
 9839: 
 9840:     if($udom) {
 9841:         if($uname) {
 9842:             my $uhome = &homeserver($uname,$udom);
 9843:             if ($uhome eq 'no_host') {
 9844:                 return ([],'no_host');
 9845:             }
 9846:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9847:                               .$getuserdir.':'.&escape($dirRoot)
 9848:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9849:             if ($listing eq 'unknown_cmd') {
 9850:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9851:             } else {
 9852:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9853:             }
 9854:             if ($listing eq 'unknown_cmd') {
 9855:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9856:                 @listing_results = split(/:/,$listing);
 9857:             } else {
 9858:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9859:             }
 9860:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9861:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9862:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9863:                 return ([],$listing);
 9864:             } else {
 9865:                 return (\@listing_results);
 9866:             }
 9867:         } elsif(!$alternateRoot) {
 9868:             my (%allusers,%listerror);
 9869: 	    my %servers = &get_servers($udom,'library');
 9870:  	    foreach my $tryserver (keys(%servers)) {
 9871:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9872:                                   &escape($udom),$tryserver);
 9873:                 if ($listing eq 'unknown_cmd') {
 9874: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9875: 				      $udom, $tryserver);
 9876:                 } else {
 9877:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9878:                 }
 9879: 		if ($listing eq 'unknown_cmd') {
 9880: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9881: 				      $udom, $tryserver);
 9882: 		    @listing_results = split(/:/,$listing);
 9883: 		} else {
 9884: 		    @listing_results =
 9885: 			map { &unescape($_); } split(/:/,$listing);
 9886: 		}
 9887:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9888:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9889:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9890:                     $listerror{$tryserver} = $listing;
 9891:                 } else {
 9892: 		    foreach my $line (@listing_results) {
 9893: 			my ($entry) = split(/&/,$line,2);
 9894: 			$allusers{$entry} = 1;
 9895: 		    }
 9896: 		}
 9897:             }
 9898:             my @alluserslist=();
 9899:             foreach my $user (sort(keys(%allusers))) {
 9900:                 push(@alluserslist,$user.'&user');
 9901:             }
 9902:             return (\@alluserslist);
 9903:         } else {
 9904:             return ([],'missing username');
 9905:         }
 9906:     } elsif(!defined($getpropath)) {
 9907:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9908:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9909:         return (\@all_domains);
 9910:     } else {
 9911:         return ([],'missing domain');
 9912:     }
 9913: }
 9914: 
 9915: # --------------------------------------------- GetFileTimestamp
 9916: # This function utilizes dirlist and returns the date stamp for
 9917: # when it was last modified.  It will also return an error of -1
 9918: # if an error occurs
 9919: 
 9920: sub GetFileTimestamp {
 9921:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9922:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9923:     $studentName   = &LONCAPA::clean_username($studentName);
 9924:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9925:                                     undef,$getuserdir);
 9926:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9927:         return -1;
 9928:     }
 9929:     if (ref($fileref) eq 'ARRAY') {
 9930:         my @stats = split('&',$fileref->[0]);
 9931:         # @stats contains first the filename, then the stat output
 9932:         return $stats[10]; # so this is 10 instead of 9.
 9933:     } else {
 9934:         return -1;
 9935:     }
 9936: }
 9937: 
 9938: sub stat_file {
 9939:     my ($uri) = @_;
 9940:     $uri = &clutter_with_no_wrapper($uri);
 9941: 
 9942:     my ($udom,$uname,$file);
 9943:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9944: 	($udom,$uname,$file) =
 9945: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9946: 	$file = 'userfiles/'.$file;
 9947:     }
 9948:     if ($uri =~ m-^/res/-) {
 9949: 	($udom,$uname) = 
 9950: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9951: 	$file = $uri;
 9952:     }
 9953: 
 9954:     if (!$udom || !$uname || !$file) {
 9955: 	# unable to handle the uri
 9956: 	return ();
 9957:     }
 9958:     my $getpropath;
 9959:     if ($file =~ /^userfiles\//) {
 9960:         $getpropath = 1;
 9961:     }
 9962:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9963:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9964:         return ();
 9965:     } else {
 9966:         if (ref($listref) eq 'ARRAY') {
 9967:             my @stats = split('&',$listref->[0]);
 9968: 	    shift(@stats); #filename is first
 9969: 	    return @stats;
 9970:         }
 9971:     }
 9972:     return ();
 9973: }
 9974: 
 9975: # -------------------------------------------------------- Value of a Condition
 9976: 
 9977: # gets the value of a specific preevaluated condition
 9978: #    stored in the string  $env{user.state.<cid>}
 9979: # or looks up a condition reference in the bighash and if if hasn't
 9980: # already been evaluated recurses into docondval to get the value of
 9981: # the condition, then memoizing it to 
 9982: #   $env{user.state.<cid>.<condition>}
 9983: sub directcondval {
 9984:     my $number=shift;
 9985:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9986: 	&Apache::lonuserstate::evalstate();
 9987:     }
 9988:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9989: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9990:     } elsif ($number =~ /^_/) {
 9991: 	my $sub_condition;
 9992: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9993: 		&GDBM_READER(),0640)) {
 9994: 	    $sub_condition=$bighash{'conditions'.$number};
 9995: 	    untie(%bighash);
 9996: 	}
 9997: 	my $value = &docondval($sub_condition);
 9998: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9999: 	return $value;
10000:     }
10001:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10002:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10003:     } else {
10004:        return 2;
10005:     }
10006: }
10007: 
10008: # get the collection of conditions for this resource
10009: sub condval {
10010:     my $condidx=shift;
10011:     my $allpathcond='';
10012:     foreach my $cond (split(/\|/,$condidx)) {
10013: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10014: 	    $allpathcond.=
10015: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10016: 	}
10017:     }
10018:     $allpathcond=~s/\|$//;
10019:     return &docondval($allpathcond);
10020: }
10021: 
10022: #evaluates an expression of conditions
10023: sub docondval {
10024:     my ($allpathcond) = @_;
10025:     my $result=0;
10026:     if ($env{'request.course.id'}
10027: 	&& defined($allpathcond)) {
10028: 	my $operand='|';
10029: 	my @stack;
10030: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10031: 	    if ($chunk eq '(') {
10032: 		push @stack,($operand,$result);
10033: 	    } elsif ($chunk eq ')') {
10034: 		my $before=pop @stack;
10035: 		if (pop @stack eq '&') {
10036: 		    $result=$result>$before?$before:$result;
10037: 		} else {
10038: 		    $result=$result>$before?$result:$before;
10039: 		}
10040: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
10041: 		$operand=$chunk;
10042: 	    } else {
10043: 		my $new=directcondval($chunk);
10044: 		if ($operand eq '&') {
10045: 		    $result=$result>$new?$new:$result;
10046: 		} else {
10047: 		    $result=$result>$new?$result:$new;
10048: 		}
10049: 	    }
10050: 	}
10051:     }
10052:     return $result;
10053: }
10054: 
10055: # ---------------------------------------------------- Devalidate courseresdata
10056: 
10057: sub devalidatecourseresdata {
10058:     my ($coursenum,$coursedomain)=@_;
10059:     my $hashid=$coursenum.':'.$coursedomain;
10060:     &devalidate_cache_new('courseres',$hashid);
10061: }
10062: 
10063: 
10064: # --------------------------------------------------- Course Resourcedata Query
10065: #
10066: #  Parameters:
10067: #      $coursenum    - Number of the course.
10068: #      $coursedomain - Domain at which the course was created.
10069: #  Returns:
10070: #     A hash of the course parameters along (I think) with timestamps
10071: #     and version info.
10072: 
10073: sub get_courseresdata {
10074:     my ($coursenum,$coursedomain)=@_;
10075:     my $coursehom=&homeserver($coursenum,$coursedomain);
10076:     my $hashid=$coursenum.':'.$coursedomain;
10077:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
10078:     my %dumpreply;
10079:     unless (defined($cached)) {
10080: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
10081: 	$result=\%dumpreply;
10082: 	my ($tmp) = keys(%dumpreply);
10083: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10084: 	    &do_cache_new('courseres',$hashid,$result,600);
10085: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10086: 	    return $tmp;
10087: 	} elsif ($tmp =~ /^(error)/) {
10088: 	    $result=undef;
10089: 	    &do_cache_new('courseres',$hashid,$result,600);
10090: 	}
10091:     }
10092:     return $result;
10093: }
10094: 
10095: sub devalidateuserresdata {
10096:     my ($uname,$udom)=@_;
10097:     my $hashid="$udom:$uname";
10098:     &devalidate_cache_new('userres',$hashid);
10099: }
10100: 
10101: sub get_userresdata {
10102:     my ($uname,$udom)=@_;
10103:     #most student don\'t have any data set, check if there is some data
10104:     if (&EXT_cache_status($udom,$uname)) { return undef; }
10105: 
10106:     my $hashid="$udom:$uname";
10107:     my ($result,$cached)=&is_cached_new('userres',$hashid);
10108:     if (!defined($cached)) {
10109: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
10110: 	$result=\%resourcedata;
10111: 	&do_cache_new('userres',$hashid,$result,600);
10112:     }
10113:     my ($tmp)=keys(%$result);
10114:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10115: 	return $result;
10116:     }
10117:     #error 2 occurs when the .db doesn't exist
10118:     if ($tmp!~/error: 2 /) {
10119: 	&logthis("<font color=\"blue\">WARNING:".
10120: 		 " Trying to get resource data for ".
10121: 		 $uname." at ".$udom.": ".
10122: 		 $tmp."</font>");
10123:     } elsif ($tmp=~/error: 2 /) {
10124: 	#&EXT_cache_set($udom,$uname);
10125: 	&do_cache_new('userres',$hashid,undef,600);
10126: 	undef($tmp); # not really an error so don't send it back
10127:     }
10128:     return $tmp;
10129: }
10130: #----------------------------------------------- resdata - return resource data
10131: #  Purpose:
10132: #    Return resource data for either users or for a course.
10133: #  Parameters:
10134: #     $name      - Course/user name.
10135: #     $domain    - Name of the domain the user/course is registered on.
10136: #     $type      - Type of thing $name is (must be 'course' or 'user'
10137: #     @which     - Array of names of resources desired.
10138: #  Returns:
10139: #     The value of the first reasource in @which that is found in the
10140: #     resource hash.
10141: #  Exceptional Conditions:
10142: #     If the $type passed in is not valid (not the string 'course' or 
10143: #     'user', an undefined  reference is returned.
10144: #     If none of the resources are found, an undef is returned
10145: sub resdata {
10146:     my ($name,$domain,$type,@which)=@_;
10147:     my $result;
10148:     if ($type eq 'course') {
10149: 	$result=&get_courseresdata($name,$domain);
10150:     } elsif ($type eq 'user') {
10151: 	$result=&get_userresdata($name,$domain);
10152:     }
10153:     if (!ref($result)) { return $result; }    
10154:     foreach my $item (@which) {
10155: 	if (defined($result->{$item->[0]})) {
10156: 	    return [$result->{$item->[0]},$item->[1]];
10157: 	}
10158:     }
10159:     return undef;
10160: }
10161: 
10162: sub get_numsuppfiles {
10163:     my ($cnum,$cdom,$ignorecache)=@_;
10164:     my $hashid=$cnum.':'.$cdom;
10165:     my ($suppcount,$cached);
10166:     unless ($ignorecache) {
10167:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10168:     }
10169:     unless (defined($cached)) {
10170:         my $chome=&homeserver($cnum,$cdom);
10171:         unless ($chome eq 'no_host') {
10172:             ($suppcount,my $errors) = (0,0);
10173:             my $suppmap = 'supplemental.sequence';
10174:             ($suppcount,$errors) = 
10175:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10176:         }
10177:         &do_cache_new('suppcount',$hashid,$suppcount,600);
10178:     }
10179:     return $suppcount;
10180: }
10181: 
10182: #
10183: # EXT resource caching routines
10184: #
10185: 
10186: sub clear_EXT_cache_status {
10187:     &delenv('cache.EXT.');
10188: }
10189: 
10190: sub EXT_cache_status {
10191:     my ($target_domain,$target_user) = @_;
10192:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10193:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10194:         # We know already the user has no data
10195:         return 1;
10196:     } else {
10197:         return 0;
10198:     }
10199: }
10200: 
10201: sub EXT_cache_set {
10202:     my ($target_domain,$target_user) = @_;
10203:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10204:     #&appenv({$cachename => time});
10205: }
10206: 
10207: # --------------------------------------------------------- Value of a Variable
10208: sub EXT {
10209: 
10210:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10211:     unless ($varname) { return ''; }
10212:     #get real user name/domain, courseid and symb
10213:     my $courseid;
10214:     my $publicuser;
10215:     if ($symbparm) {
10216: 	$symbparm=&get_symb_from_alias($symbparm);
10217:     }
10218:     if (!($uname && $udom)) {
10219:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10220:       if (!$symbparm) {	$symbparm=$cursymb; }
10221:     } else {
10222: 	$courseid=$env{'request.course.id'};
10223:     }
10224:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10225:     my $rest;
10226:     if (defined($therest[0])) {
10227:        $rest=join('.',@therest);
10228:     } else {
10229:        $rest='';
10230:     }
10231: 
10232:     my $qualifierrest=$qualifier;
10233:     if ($rest) { $qualifierrest.='.'.$rest; }
10234:     my $spacequalifierrest=$space;
10235:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10236:     if ($realm eq 'user') {
10237: # --------------------------------------------------------------- user.resource
10238: 	if ($space eq 'resource') {
10239: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10240: 		  || defined($Apache::lonhomework::parsing_a_task))
10241: 		 &&
10242: 		 ($symbparm eq &symbread()) ) {	
10243: 		# if we are in the middle of processing the resource the
10244: 		# get the value we are planning on committing
10245:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10246:                     return $Apache::lonhomework::results{$qualifierrest};
10247:                 } else {
10248:                     return $Apache::lonhomework::history{$qualifierrest};
10249:                 }
10250: 	    } else {
10251: 		my %restored;
10252: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10253: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10254: 		} else {
10255: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10256: 		}
10257: 		return $restored{$qualifierrest};
10258: 	    }
10259: # ----------------------------------------------------------------- user.access
10260:         } elsif ($space eq 'access') {
10261: 	    # FIXME - not supporting calls for a specific user
10262:             return &allowed($qualifier,$rest);
10263: # ------------------------------------------ user.preferences, user.environment
10264:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10265: 	    if (($uname eq $env{'user.name'}) &&
10266: 		($udom eq $env{'user.domain'})) {
10267: 		return $env{join('.',('environment',$qualifierrest))};
10268: 	    } else {
10269: 		my %returnhash;
10270: 		if (!$publicuser) {
10271: 		    %returnhash=&userenvironment($udom,$uname,
10272: 						 $qualifierrest);
10273: 		}
10274: 		return $returnhash{$qualifierrest};
10275: 	    }
10276: # ----------------------------------------------------------------- user.course
10277:         } elsif ($space eq 'course') {
10278: 	    # FIXME - not supporting calls for a specific user
10279:             return $env{join('.',('request.course',$qualifier))};
10280: # ------------------------------------------------------------------- user.role
10281:         } elsif ($space eq 'role') {
10282: 	    # FIXME - not supporting calls for a specific user
10283:             my ($role,$where)=split(/\./,$env{'request.role'});
10284:             if ($qualifier eq 'value') {
10285: 		return $role;
10286:             } elsif ($qualifier eq 'extent') {
10287:                 return $where;
10288:             }
10289: # ----------------------------------------------------------------- user.domain
10290:         } elsif ($space eq 'domain') {
10291:             return $udom;
10292: # ------------------------------------------------------------------- user.name
10293:         } elsif ($space eq 'name') {
10294:             return $uname;
10295: # ---------------------------------------------------- Any other user namespace
10296:         } else {
10297: 	    my %reply;
10298: 	    if (!$publicuser) {
10299: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10300: 	    }
10301: 	    return $reply{$qualifierrest};
10302:         }
10303:     } elsif ($realm eq 'query') {
10304: # ---------------------------------------------- pull stuff out of query string
10305:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10306: 						[$spacequalifierrest]);
10307: 	return $env{'form.'.$spacequalifierrest}; 
10308:    } elsif ($realm eq 'request') {
10309: # ------------------------------------------------------------- request.browser
10310:         if ($space eq 'browser') {
10311:             return $env{'browser.'.$qualifier};
10312: # ------------------------------------------------------------ request.filename
10313:         } else {
10314:             return $env{'request.'.$spacequalifierrest};
10315:         }
10316:     } elsif ($realm eq 'course') {
10317: # ---------------------------------------------------------- course.description
10318:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10319:     } elsif ($realm eq 'resource') {
10320: 
10321: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10322: 	    if (!$symbparm) { $symbparm=&symbread(); }
10323: 	}
10324: 
10325:         if ($qualifier eq '') {
10326: 	    if ($space eq 'title') {
10327: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10328: 	        return &gettitle($symbparm);
10329: 	    }
10330: 	
10331: 	    if ($space eq 'map') {
10332: 	        my ($map) = &decode_symb($symbparm);
10333: 	        return &symbread($map);
10334: 	    }
10335:             if ($space eq 'maptitle') {
10336:                 my ($map) = &decode_symb($symbparm);
10337:                 return &gettitle($map);
10338:             }
10339: 	    if ($space eq 'filename') {
10340: 	        if ($symbparm) {
10341: 		    return &clutter((&decode_symb($symbparm))[2]);
10342: 	        }
10343: 	        return &hreflocation('',$env{'request.filename'});
10344: 	    }
10345: 
10346:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10347:                 if ($space eq 'visibleparts') {
10348:                     my $navmap = Apache::lonnavmaps::navmap->new();
10349:                     my $item;
10350:                     if (ref($navmap)) {
10351:                         my $res = $navmap->getBySymb($symbparm);
10352:                         my $parts = $res->parts();
10353:                         if (ref($parts) eq 'ARRAY') {
10354:                             $item = join(',',@{$parts});
10355:                         }
10356:                         undef($navmap);
10357:                     }
10358:                     return $item;
10359:                 }
10360:             }
10361:         }
10362: 
10363: 	my ($section, $group, @groups);
10364: 	my ($courselevelm,$courselevel);
10365:         if (($courseid eq '') && ($cid)) {
10366:             $courseid = $cid;
10367:         }
10368: 	if (($symbparm && $courseid) && 
10369: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10370: 
10371: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10372: 
10373: # ----------------------------------------------------- Cascading lookup scheme
10374: 	    my $symbp=$symbparm;
10375: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10376: 
10377: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10378: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10379: 
10380: 	    if (($env{'user.name'} eq $uname) &&
10381: 		($env{'user.domain'} eq $udom)) {
10382: 		$section=$env{'request.course.sec'};
10383:                 @groups = split(/:/,$env{'request.course.groups'});  
10384:                 @groups=&sort_course_groups($courseid,@groups); 
10385: 	    } else {
10386: 		if (! defined($usection)) {
10387: 		    $section=&getsection($udom,$uname,$courseid);
10388: 		} else {
10389: 		    $section = $usection;
10390: 		}
10391:                 @groups = &get_users_groups($udom,$uname,$courseid);
10392: 	    }
10393: 
10394: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10395: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10396: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10397: 
10398: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10399: 	    my $courselevelr=$courseid.'.'.$symbparm;
10400: 	    $courselevelm=$courseid.'.'.$mapparm;
10401: 
10402: # ----------------------------------------------------------- first, check user
10403: 
10404: 	    my $userreply=&resdata($uname,$udom,'user',
10405: 				       ([$courselevelr,'resource'],
10406: 					[$courselevelm,'map'     ],
10407: 					[$courselevel, 'course'  ]));
10408: 	    if (defined($userreply)) { return &get_reply($userreply); }
10409: 
10410: # ------------------------------------------------ second, check some of course
10411:             my $coursereply;
10412:             if (@groups > 0) {
10413:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10414:                                        $mapparm,$spacequalifierrest);
10415:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10416:             }
10417: 
10418: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10419: 				  $env{'course.'.$courseid.'.domain'},
10420: 				  'course',
10421: 				  ([$seclevelr,   'resource'],
10422: 				   [$seclevelm,   'map'     ],
10423: 				   [$seclevel,    'course'  ],
10424: 				   [$courselevelr,'resource']));
10425: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10426: 
10427: # ------------------------------------------------------ third, check map parms
10428: 	    my %parmhash=();
10429: 	    my $thisparm='';
10430: 	    if (tie(%parmhash,'GDBM_File',
10431: 		    $env{'request.course.fn'}.'_parms.db',
10432: 		    &GDBM_READER(),0640)) {
10433: 		$thisparm=$parmhash{$symbparm};
10434: 		untie(%parmhash);
10435: 	    }
10436: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10437: 	}
10438: # ------------------------------------------ fourth, look in resource metadata
10439: 
10440: 	$spacequalifierrest=~s/\./\_/;
10441: 	my $filename;
10442: 	if (!$symbparm) { $symbparm=&symbread(); }
10443: 	if ($symbparm) {
10444: 	    $filename=(&decode_symb($symbparm))[2];
10445: 	} else {
10446: 	    $filename=$env{'request.filename'};
10447: 	}
10448: 	my $metadata=&metadata($filename,$spacequalifierrest);
10449: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10450: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10451: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10452: 
10453: # ---------------------------------------------- fourth, look in rest of course
10454: 	if ($symbparm && defined($courseid) && 
10455: 	    $courseid eq $env{'request.course.id'}) {
10456: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10457: 				     $env{'course.'.$courseid.'.domain'},
10458: 				     'course',
10459: 				     ([$courselevelm,'map'   ],
10460: 				      [$courselevel, 'course']));
10461: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10462: 	}
10463: # ------------------------------------------------------------------ Cascade up
10464: 	unless ($space eq '0') {
10465: 	    my @parts=split(/_/,$space);
10466: 	    my $id=pop(@parts);
10467: 	    my $part=join('_',@parts);
10468: 	    if ($part eq '') { $part='0'; }
10469: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10470: 				 $symbparm,$udom,$uname,$section,1);
10471: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10472: 	}
10473: 	if ($recurse) { return undef; }
10474: 	my $pack_def=&packages_tab_default($filename,$varname);
10475: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10476: # ---------------------------------------------------- Any other user namespace
10477:     } elsif ($realm eq 'environment') {
10478: # ----------------------------------------------------------------- environment
10479: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10480: 	    return $env{'environment.'.$spacequalifierrest};
10481: 	} else {
10482: 	    if ($uname eq 'anonymous' && $udom eq '') {
10483: 		return '';
10484: 	    }
10485: 	    my %returnhash=&userenvironment($udom,$uname,
10486: 					    $spacequalifierrest);
10487: 	    return $returnhash{$spacequalifierrest};
10488: 	}
10489:     } elsif ($realm eq 'system') {
10490: # ----------------------------------------------------------------- system.time
10491: 	if ($space eq 'time') {
10492: 	    return time;
10493:         }
10494:     } elsif ($realm eq 'server') {
10495: # ----------------------------------------------------------------- system.time
10496: 	if ($space eq 'name') {
10497: 	    return $ENV{'SERVER_NAME'};
10498:         }
10499:     }
10500:     return '';
10501: }
10502: 
10503: sub get_reply {
10504:     my ($reply_value) = @_;
10505:     if (ref($reply_value) eq 'ARRAY') {
10506:         if (wantarray) {
10507: 	    return @$reply_value;
10508:         }
10509:         return $reply_value->[0];
10510:     } else {
10511:         return $reply_value;
10512:     }
10513: }
10514: 
10515: sub check_group_parms {
10516:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10517:     my @groupitems = ();
10518:     my $resultitem;
10519:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10520:     foreach my $group (@{$groups}) {
10521:         foreach my $level (@levels) {
10522:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10523:              push(@groupitems,[$item,$level->[1]]);
10524:         }
10525:     }
10526:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10527:                             $env{'course.'.$courseid.'.domain'},
10528:                                      'course',@groupitems);
10529:     return $coursereply;
10530: }
10531: 
10532: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10533:     my ($courseid,@groups) = @_;
10534:     @groups = sort(@groups);
10535:     return @groups;
10536: }
10537: 
10538: sub packages_tab_default {
10539:     my ($uri,$varname)=@_;
10540:     my (undef,$part,$name)=split(/\./,$varname);
10541: 
10542:     my (@extension,@specifics,$do_default);
10543:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10544: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10545: 	if ($pack_type eq 'default') {
10546: 	    $do_default=1;
10547: 	} elsif ($pack_type eq 'extension') {
10548: 	    push(@extension,[$package,$pack_type,$pack_part]);
10549: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10550: 	    # only look at packages defaults for packages that this id is
10551: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10552: 	}
10553:     }
10554:     # first look for a package that matches the requested part id
10555:     foreach my $package (@specifics) {
10556: 	my (undef,$pack_type,$pack_part)=@{$package};
10557: 	next if ($pack_part ne $part);
10558: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10559: 	    return $packagetab{"$pack_type&$name&default"};
10560: 	}
10561:     }
10562:     # look for any possible matching non extension_ package
10563:     foreach my $package (@specifics) {
10564: 	my (undef,$pack_type,$pack_part)=@{$package};
10565: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10566: 	    return $packagetab{"$pack_type&$name&default"};
10567: 	}
10568: 	if ($pack_type eq 'part') { $pack_part='0'; }
10569: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10570: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10571: 	}
10572:     }
10573:     # look for any posible extension_ match
10574:     foreach my $package (@extension) {
10575: 	my ($package,$pack_type)=@{$package};
10576: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10577: 	    return $packagetab{"$pack_type&$name&default"};
10578: 	}
10579: 	if (defined($packagetab{$package."&$name&default"})) {
10580: 	    return $packagetab{$package."&$name&default"};
10581: 	}
10582:     }
10583:     # look for a global default setting
10584:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10585: 	return $packagetab{"default&$name&default"};
10586:     }
10587:     return undef;
10588: }
10589: 
10590: sub add_prefix_and_part {
10591:     my ($prefix,$part)=@_;
10592:     my $keyroot;
10593:     if (defined($prefix) && $prefix !~ /^__/) {
10594: 	# prefix that has a part already
10595: 	$keyroot=$prefix;
10596:     } elsif (defined($prefix)) {
10597: 	# prefix that is missing a part
10598: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10599:     } else {
10600: 	# no prefix at all
10601: 	if (defined($part)) { $keyroot='_'.$part; }
10602:     }
10603:     return $keyroot;
10604: }
10605: 
10606: # ---------------------------------------------------------------- Get metadata
10607: 
10608: my %metaentry;
10609: my %importedpartids;
10610: sub metadata {
10611:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10612:     $uri=&declutter($uri);
10613:     # if it is a non metadata possible uri return quickly
10614:     if (($uri eq '') || 
10615: 	(($uri =~ m|^/*adm/|) && 
10616: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10617:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10618: 	return undef;
10619:     }
10620:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10621: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10622: 	return undef;
10623:     }
10624:     my $filename=$uri;
10625:     $uri=~s/\.meta$//;
10626: #
10627: # Is the metadata already cached?
10628: # Look at timestamp of caching
10629: # Everything is cached by the main uri, libraries are never directly cached
10630: #
10631:     if (!defined($liburi)) {
10632: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10633: 	if (defined($cached)) { return $result->{':'.$what}; }
10634:     }
10635:     {
10636: # Imported parts would go here
10637:         my %importedids=();
10638:         my @origfileimportpartids=();
10639:         my $importedparts=0;
10640: #
10641: # Is this a recursive call for a library?
10642: #
10643: #	if (! exists($metacache{$uri})) {
10644: #	    $metacache{$uri}={};
10645: #	}
10646: 	my $cachetime = 60*60;
10647:         if ($liburi) {
10648: 	    $liburi=&declutter($liburi);
10649:             $filename=$liburi;
10650:         } else {
10651: 	    &devalidate_cache_new('meta',$uri);
10652: 	    undef(%metaentry);
10653: 	}
10654:         my %metathesekeys=();
10655:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10656: 	my $metastring;
10657: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10658: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10659: 	    $metastring = 
10660: 		&Apache::lonnet::ssi_body($which,
10661: 					  ('grade_target' => 'meta'));
10662: 	    $cachetime = 1; # only want this cached in the child not long term
10663: 	} elsif (($uri !~ m -^(editupload)/-) && 
10664:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10665: 	    my $file=&filelocation('',&clutter($filename));
10666: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10667: 	    $metastring=&getfile($file);
10668: 	}
10669:         my $parser=HTML::LCParser->new(\$metastring);
10670:         my $token;
10671:         undef %metathesekeys;
10672:         while ($token=$parser->get_token) {
10673: 	    if ($token->[0] eq 'S') {
10674: 		if (defined($token->[2]->{'package'})) {
10675: #
10676: # This is a package - get package info
10677: #
10678: 		    my $package=$token->[2]->{'package'};
10679: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10680: 		    if (defined($token->[2]->{'id'})) { 
10681: 			$keyroot.='_'.$token->[2]->{'id'}; 
10682: 		    }
10683: 		    if ($metaentry{':packages'}) {
10684: 			$metaentry{':packages'}.=','.$package.$keyroot;
10685: 		    } else {
10686: 			$metaentry{':packages'}=$package.$keyroot;
10687: 		    }
10688: 		    foreach my $pack_entry (keys(%packagetab)) {
10689: 			my $part=$keyroot;
10690: 			$part=~s/^\_//;
10691: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10692: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10693: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10694: 			    # ignore package.tab specified default values
10695:                             # here &package_tab_default() will fetch those
10696: 			    if ($subp eq 'default') { next; }
10697: 			    my $value=$packagetab{$pack_entry};
10698: 			    my $unikey;
10699: 			    if ($pack =~ /_0$/) {
10700: 				$unikey='parameter_0_'.$name;
10701: 				$part=0;
10702: 			    } else {
10703: 				$unikey='parameter'.$keyroot.'_'.$name;
10704: 			    }
10705: 			    if ($subp eq 'display') {
10706: 				$value.=' [Part: '.$part.']';
10707: 			    }
10708: 			    $metaentry{':'.$unikey.'.part'}=$part;
10709: 			    $metathesekeys{$unikey}=1;
10710: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10711: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10712: 			    }
10713: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10714: 				$metaentry{':'.$unikey}=
10715: 				    $metaentry{':'.$unikey.'.default'};
10716: 			    }
10717: 			}
10718: 		    }
10719: 		} else {
10720: #
10721: # This is not a package - some other kind of start tag
10722: #
10723: 		    my $entry=$token->[1];
10724: 		    my $unikey='';
10725: 
10726: 		    if ($entry eq 'import') {
10727: #
10728: # Importing a library here
10729: #
10730:                         my $location=$parser->get_text('/import');
10731:                         my $dir=$filename;
10732:                         $dir=~s|[^/]*$||;
10733:                         $location=&filelocation($dir,$location);
10734:                        
10735:                         my $importmode=$token->[2]->{'importmode'};
10736:                         if ($importmode eq 'problem') {
10737: # Import as problem/response
10738:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10739:                         } elsif ($importmode eq 'part') {
10740: # Import as part(s)
10741:                            $importedparts=1;
10742: # We need to get the original file and the imported file to get the part order correct
10743: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10744: # Load and inspect original file
10745:                            if ($#origfileimportpartids<0) {
10746:                               undef(%importedpartids);
10747:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10748:                               my $origfile=&getfile($origfilelocation);
10749:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10750:                            }
10751: 
10752: # Load and inspect imported file
10753:                            my $impfile=&getfile($location);
10754:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10755:                            if ($#impfilepartids>=0) {
10756: # This problem had parts
10757:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10758:                            } else {
10759: # Importing by turning a single problem into a problem part
10760: # It gets the import-tags ID as part-ID
10761:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10762:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10763:                            }
10764:                         } else {
10765: # Normal import
10766:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10767:                            if (defined($token->[2]->{'id'})) {
10768:                               $unikey.='_'.$token->[2]->{'id'};
10769:                            }
10770:                         }
10771: 
10772: 			if ($depthcount<20) {
10773: 			    my $metadata = 
10774: 				&metadata($uri,'keys', $location,$unikey,
10775: 					  $depthcount+1);
10776: 			    foreach my $meta (split(',',$metadata)) {
10777: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10778: 				$metathesekeys{$meta}=1;
10779: 			    }
10780: 			
10781:                         }
10782: 		    } else {
10783: #
10784: # Not importing, some other kind of non-package, non-library start tag
10785: # 
10786:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10787:                         if (defined($token->[2]->{'id'})) {
10788:                             $unikey.='_'.$token->[2]->{'id'};
10789:                         }
10790: 			if (defined($token->[2]->{'name'})) { 
10791: 			    $unikey.='_'.$token->[2]->{'name'}; 
10792: 			}
10793: 			$metathesekeys{$unikey}=1;
10794: 			foreach my $param (@{$token->[3]}) {
10795: 			    $metaentry{':'.$unikey.'.'.$param} =
10796: 				$token->[2]->{$param};
10797: 			}
10798: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10799: 			my $default=$metaentry{':'.$unikey.'.default'};
10800: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10801: 		 # only ws inside the tag, and not in default, so use default
10802: 		 # as value
10803: 			    $metaentry{':'.$unikey}=$default;
10804: 			} elsif ( $internaltext =~ /\S/ ) {
10805: 		  # something interesting inside the tag
10806: 			    $metaentry{':'.$unikey}=$internaltext;
10807: 			} else {
10808: 		  # no interesting values, don't set a default
10809: 			}
10810: # end of not-a-package not-a-library import
10811: 		    }
10812: # end of not-a-package start tag
10813: 		}
10814: # the next is the end of "start tag"
10815: 	    }
10816: 	}
10817: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10818: 	$extension = lc($extension);
10819: 	if ($extension eq 'htm') { $extension='html'; }
10820: 
10821: 	foreach my $key (keys(%packagetab)) {
10822: 	    #no specific packages #how's our extension
10823: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10824: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10825: 					 \%metathesekeys);
10826: 	}
10827: 
10828: 	if (!exists($metaentry{':packages'})
10829: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10830: 	    foreach my $key (keys(%packagetab)) {
10831: 		#no specific packages well let's get default then
10832: 		if ($key!~/^default&/) { next; }
10833: 		&metadata_create_package_def($uri,$key,'default',
10834: 					     \%metathesekeys);
10835: 	    }
10836: 	}
10837: # are there custom rights to evaluate
10838: 	if ($metaentry{':copyright'} eq 'custom') {
10839: 
10840:     #
10841:     # Importing a rights file here
10842:     #
10843: 	    unless ($depthcount) {
10844: 		my $location=$metaentry{':customdistributionfile'};
10845: 		my $dir=$filename;
10846: 		$dir=~s|[^/]*$||;
10847: 		$location=&filelocation($dir,$location);
10848: 		my $rights_metadata =
10849: 		    &metadata($uri,'keys',$location,'_rights',
10850: 			      $depthcount+1);
10851: 		foreach my $rights (split(',',$rights_metadata)) {
10852: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10853: 		    $metathesekeys{$rights}=1;
10854: 		}
10855: 	    }
10856: 	}
10857: 	# uniqifiy package listing
10858: 	my %seen;
10859: 	my @uniq_packages =
10860: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10861: 	$metaentry{':packages'} = join(',',@uniq_packages);
10862: 
10863:         if ($importedparts) {
10864: # We had imported parts and need to rebuild partorder
10865:            $metaentry{':partorder'}='';
10866:            $metathesekeys{'partorder'}=1;
10867:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10868:                if ($origfileimportpartids[$index] eq 'part') {
10869: # original part, part of the problem
10870:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10871:                } else {
10872: # we have imported parts at this position
10873:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10874:                }
10875:            }
10876:            $metaentry{':partorder'}=~s/^\,//;
10877:         }
10878: 
10879: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10880: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10881: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10882: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10883: # this is the end of "was not already recently cached
10884:     }
10885:     return $metaentry{':'.$what};
10886: }
10887: 
10888: sub metadata_create_package_def {
10889:     my ($uri,$key,$package,$metathesekeys)=@_;
10890:     my ($pack,$name,$subp)=split(/\&/,$key);
10891:     if ($subp eq 'default') { next; }
10892:     
10893:     if (defined($metaentry{':packages'})) {
10894: 	$metaentry{':packages'}.=','.$package;
10895:     } else {
10896: 	$metaentry{':packages'}=$package;
10897:     }
10898:     my $value=$packagetab{$key};
10899:     my $unikey;
10900:     $unikey='parameter_0_'.$name;
10901:     $metaentry{':'.$unikey.'.part'}=0;
10902:     $$metathesekeys{$unikey}=1;
10903:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10904: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10905:     }
10906:     if (defined($metaentry{':'.$unikey.'.default'})) {
10907: 	$metaentry{':'.$unikey}=
10908: 	    $metaentry{':'.$unikey.'.default'};
10909:     }
10910: }
10911: 
10912: sub metadata_generate_part0 {
10913:     my ($metadata,$metacache,$uri) = @_;
10914:     my %allnames;
10915:     foreach my $metakey (keys(%$metadata)) {
10916: 	if ($metakey=~/^parameter\_(.*)/) {
10917: 	  my $part=$$metacache{':'.$metakey.'.part'};
10918: 	  my $name=$$metacache{':'.$metakey.'.name'};
10919: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10920: 	    $allnames{$name}=$part;
10921: 	  }
10922: 	}
10923:     }
10924:     foreach my $name (keys(%allnames)) {
10925:       $$metadata{"parameter_0_$name"}=1;
10926:       my $key=":parameter_0_$name";
10927:       $$metacache{"$key.part"}='0';
10928:       $$metacache{"$key.name"}=$name;
10929:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10930: 					   $allnames{$name}.'_'.$name.
10931: 					   '.type'};
10932:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10933: 			     '.display'};
10934:       my $expr='[Part: '.$allnames{$name}.']';
10935:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10936:       $$metacache{"$key.display"}=$olddis;
10937:     }
10938: }
10939: 
10940: # ------------------------------------------------------ Devalidate title cache
10941: 
10942: sub devalidate_title_cache {
10943:     my ($url)=@_;
10944:     if (!$env{'request.course.id'}) { return; }
10945:     my $symb=&symbread($url);
10946:     if (!$symb) { return; }
10947:     my $key=$env{'request.course.id'}."\0".$symb;
10948:     &devalidate_cache_new('title',$key);
10949: }
10950: 
10951: # ------------------------------------------------- Get the title of a course
10952: 
10953: sub current_course_title {
10954:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10955: }
10956: # ------------------------------------------------- Get the title of a resource
10957: 
10958: sub gettitle {
10959:     my $urlsymb=shift;
10960:     my $symb=&symbread($urlsymb);
10961:     if ($symb) {
10962: 	my $key=$env{'request.course.id'}."\0".$symb;
10963: 	my ($result,$cached)=&is_cached_new('title',$key);
10964: 	if (defined($cached)) { 
10965: 	    return $result;
10966: 	}
10967: 	my ($map,$resid,$url)=&decode_symb($symb);
10968: 	my $title='';
10969: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10970: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10971: 	} else {
10972: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10973: 		    &GDBM_READER(),0640)) {
10974: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10975: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10976: 		untie(%bighash);
10977: 	    }
10978: 	}
10979: 	$title=~s/\&colon\;/\:/gs;
10980: 	if ($title) {
10981: # Remember both $symb and $title for dynamic metadata
10982:             $accesshash{$symb.'___crstitle'}=$title;
10983:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10984: # Cache this title and then return it
10985: 	    return &do_cache_new('title',$key,$title,600);
10986: 	}
10987: 	$urlsymb=$url;
10988:     }
10989:     my $title=&metadata($urlsymb,'title');
10990:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10991:     return $title;
10992: }
10993: 
10994: sub get_slot {
10995:     my ($which,$cnum,$cdom)=@_;
10996:     if (!$cnum || !$cdom) {
10997: 	(undef,my $courseid)=&whichuser();
10998: 	$cdom=$env{'course.'.$courseid.'.domain'};
10999: 	$cnum=$env{'course.'.$courseid.'.num'};
11000:     }
11001:     my $key=join("\0",'slots',$cdom,$cnum,$which);
11002:     my %slotinfo;
11003:     if (exists($remembered{$key})) {
11004: 	$slotinfo{$which} = $remembered{$key};
11005:     } else {
11006: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
11007: 	&Apache::lonhomework::showhash(%slotinfo);
11008: 	my ($tmp)=keys(%slotinfo);
11009: 	if ($tmp=~/^error:/) { return (); }
11010: 	$remembered{$key} = $slotinfo{$which};
11011:     }
11012:     if (ref($slotinfo{$which}) eq 'HASH') {
11013: 	return %{$slotinfo{$which}};
11014:     }
11015:     return $slotinfo{$which};
11016: }
11017: 
11018: sub get_reservable_slots {
11019:     my ($cnum,$cdom,$uname,$udom) = @_;
11020:     my $now = time;
11021:     my $reservable_info;
11022:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11023:     if (exists($remembered{$key})) {
11024:         $reservable_info = $remembered{$key};
11025:     } else {
11026:         my %resv;
11027:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11028:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11029:         $reservable_info = \%resv;
11030:         $remembered{$key} = $reservable_info;
11031:     }
11032:     return $reservable_info;
11033: }
11034: 
11035: sub get_course_slots {
11036:     my ($cnum,$cdom) = @_;
11037:     my $hashid=$cnum.':'.$cdom;
11038:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11039:     if (defined($cached)) {
11040:         if (ref($result) eq 'HASH') {
11041:             return %{$result};
11042:         }
11043:     } else {
11044:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11045:         my ($tmp) = keys(%slots);
11046:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11047:             &do_cache_new('allslots',$hashid,\%slots,600);
11048:             return %slots;
11049:         }
11050:     }
11051:     return;
11052: }
11053: 
11054: sub devalidate_slots_cache {
11055:     my ($cnum,$cdom)=@_;
11056:     my $hashid=$cnum.':'.$cdom;
11057:     &devalidate_cache_new('allslots',$hashid);
11058: }
11059: 
11060: sub get_coursechange {
11061:     my ($cdom,$cnum) = @_;
11062:     if ($cdom eq '' || $cnum eq '') {
11063:         return unless ($env{'request.course.id'});
11064:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11065:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11066:     }
11067:     my $hashid=$cdom.'_'.$cnum;
11068:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
11069:     if ((defined($cached)) && ($change ne '')) {
11070:         return $change;
11071:     } else {
11072:         my %crshash;
11073:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11074:         if ($crshash{'internal.contentchange'} eq '') {
11075:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11076:             if ($change eq '') {
11077:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11078:                 $change = $crshash{'internal.created'};
11079:             }
11080:         } else {
11081:             $change = $crshash{'internal.contentchange'};
11082:         }
11083:         my $cachetime = 600;
11084:         &do_cache_new('crschange',$hashid,$change,$cachetime);
11085:     }
11086:     return $change;
11087: }
11088: 
11089: sub devalidate_coursechange_cache {
11090:     my ($cnum,$cdom)=@_;
11091:     my $hashid=$cnum.':'.$cdom;
11092:     &devalidate_cache_new('crschange',$hashid);
11093: }
11094: 
11095: # ------------------------------------------------- Update symbolic store links
11096: 
11097: sub symblist {
11098:     my ($mapname,%newhash)=@_;
11099:     $mapname=&deversion(&declutter($mapname));
11100:     my %hash;
11101:     if (($env{'request.course.fn'}) && (%newhash)) {
11102:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11103:                       &GDBM_WRCREAT(),0640)) {
11104: 	    foreach my $url (keys(%newhash)) {
11105: 		next if ($url eq 'last_known'
11106: 			 && $env{'form.no_update_last_known'});
11107: 		$hash{declutter($url)}=&encode_symb($mapname,
11108: 						    $newhash{$url}->[1],
11109: 						    $newhash{$url}->[0]);
11110:             }
11111:             if (untie(%hash)) {
11112: 		return 'ok';
11113:             }
11114:         }
11115:     }
11116:     return 'error';
11117: }
11118: 
11119: # --------------------------------------------------------------- Verify a symb
11120: 
11121: sub symbverify {
11122:     my ($symb,$thisurl,$encstate)=@_;
11123:     my $thisfn=$thisurl;
11124:     $thisfn=&declutter($thisfn);
11125: # direct jump to resource in page or to a sequence - will construct own symbs
11126:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11127: # check URL part
11128:     my ($map,$resid,$url)=&decode_symb($symb);
11129: 
11130:     unless ($url eq $thisfn) { return 0; }
11131: 
11132:     $symb=&symbclean($symb);
11133:     $thisurl=&deversion($thisurl);
11134:     $thisfn=&deversion($thisfn);
11135: 
11136:     my %bighash;
11137:     my $okay=0;
11138: 
11139:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11140:                             &GDBM_READER(),0640)) {
11141:         my $noclutter;
11142:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11143:             $thisurl =~ s/\?.+$//;
11144:             if ($map =~ m{^uploaded/.+\.page$}) {
11145:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11146:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
11147:                 $noclutter = 1;
11148:             }
11149:         }
11150:         my $ids;
11151:         if ($noclutter) {
11152:             $ids=$bighash{'ids_'.$thisurl};
11153:         } else {
11154:             $ids=$bighash{'ids_'.&clutter($thisurl)};
11155:         }
11156:         unless ($ids) {
11157:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
11158:             $ids=$bighash{$idkey};
11159:         }
11160:         if ($ids) {
11161: # ------------------------------------------------------------------- Has ID(s)
11162:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11163:                 $symb =~ s/\?.+$//;
11164:             }
11165: 	    foreach my $id (split(/\,/,$ids)) {
11166: 	       my ($mapid,$resid)=split(/\./,$id);
11167:                if (
11168:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11169:    eq $symb) {
11170:                    if (ref($encstate)) {
11171:                        $$encstate = $bighash{'encrypted_'.$id};
11172:                    }
11173: 		   if (($env{'request.role.adv'}) ||
11174: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11175:                        ($thisurl eq '/adm/navmaps')) {
11176: 		       $okay=1;
11177:                        last;
11178: 		   }
11179: 	       }
11180: 	   }
11181:         }
11182: 	untie(%bighash);
11183:     }
11184:     return $okay;
11185: }
11186: 
11187: # --------------------------------------------------------------- Clean-up symb
11188: 
11189: sub symbclean {
11190:     my $symb=shift;
11191:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11192: # remove version from map
11193:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11194: 
11195: # remove version from URL
11196:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11197: 
11198: # remove wrapper
11199: 
11200:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11201:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11202:     return $symb;
11203: }
11204: 
11205: # ---------------------------------------------- Split symb to find map and url
11206: 
11207: sub encode_symb {
11208:     my ($map,$resid,$url)=@_;
11209:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11210: }
11211: 
11212: sub decode_symb {
11213:     my $symb=shift;
11214:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11215:     my ($map,$resid,$url)=split(/___/,$symb);
11216:     return (&fixversion($map),$resid,&fixversion($url));
11217: }
11218: 
11219: sub fixversion {
11220:     my $fn=shift;
11221:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11222:     my %bighash;
11223:     my $uri=&clutter($fn);
11224:     my $key=$env{'request.course.id'}.'_'.$uri;
11225: # is this cached?
11226:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11227:     if (defined($cached)) { return $result; }
11228: # unfortunately not cached, or expired
11229:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11230: 	    &GDBM_READER(),0640)) {
11231:  	if ($bighash{'version_'.$uri}) {
11232:  	    my $version=$bighash{'version_'.$uri};
11233:  	    unless (($version eq 'mostrecent') || 
11234: 		    ($version==&getversion($uri))) {
11235:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11236:  	    }
11237:  	}
11238:  	untie %bighash;
11239:     }
11240:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11241: }
11242: 
11243: sub deversion {
11244:     my $url=shift;
11245:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11246:     return $url;
11247: }
11248: 
11249: # ------------------------------------------------------ Return symb list entry
11250: 
11251: sub symbread {
11252:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
11253:     my $cache_str='request.symbread.cached.'.$thisfn;
11254:     if (defined($env{$cache_str})) {
11255:         if ($ignorecachednull) {
11256:             return $env{$cache_str} unless ($env{$cache_str} eq '');
11257:         } else {
11258:             return $env{$cache_str};
11259:         }
11260:     }
11261: # no filename provided? try from environment
11262:     unless ($thisfn) {
11263:         if ($env{'request.symb'}) {
11264: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
11265: 	}
11266: 	$thisfn=$env{'request.filename'};
11267:     }
11268:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11269: # is that filename actually a symb? Verify, clean, and return
11270:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11271: 	if (&symbverify($thisfn,$1)) {
11272: 	    return $env{$cache_str}=&symbclean($thisfn);
11273: 	}
11274:     }
11275:     $thisfn=declutter($thisfn);
11276:     my %hash;
11277:     my %bighash;
11278:     my $syval='';
11279:     if (($env{'request.course.fn'}) && ($thisfn)) {
11280:         my $targetfn = $thisfn;
11281:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11282:             $targetfn = 'adm/wrapper/'.$thisfn;
11283:         }
11284: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11285: 	    $targetfn=$1;
11286: 	}
11287:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11288:                       &GDBM_READER(),0640)) {
11289: 	    $syval=$hash{$targetfn};
11290:             untie(%hash);
11291:         }
11292: # ---------------------------------------------------------- There was an entry
11293:         if ($syval) {
11294: 	    #unless ($syval=~/\_\d+$/) {
11295: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11296: 		    #&appenv({'request.ambiguous' => $thisfn});
11297: 		    #return $env{$cache_str}='';
11298: 		#}    
11299: 		#$syval.=$1;
11300: 	    #}
11301:         } else {
11302: # ------------------------------------------------------- Was not in symb table
11303:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11304:                             &GDBM_READER(),0640)) {
11305: # ---------------------------------------------- Get ID(s) for current resource
11306:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11307:               unless ($ids) { 
11308:                  $ids=$bighash{'ids_/'.$thisfn};
11309:               }
11310:               unless ($ids) {
11311: # alias?
11312: 		  $ids=$bighash{'mapalias_'.$thisfn};
11313:               }
11314:               if ($ids) {
11315: # ------------------------------------------------------------------- Has ID(s)
11316:                  my @possibilities=split(/\,/,$ids);
11317:                  if ($#possibilities==0) {
11318: # ----------------------------------------------- There is only one possibility
11319: 		     my ($mapid,$resid)=split(/\./,$ids);
11320: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11321: 						    $resid,$thisfn);
11322:                      if (ref($possibles) eq 'HASH') {
11323:                          $possibles->{$syval} = 1;    
11324:                      }
11325:                      if ($checkforblock) {
11326:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11327:                          if (@blockers) {
11328:                              $syval = '';
11329:                              return;
11330:                          }
11331:                      }
11332:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
11333: # ------------------------------------------ There is more than one possibility
11334:                      my $realpossible=0;
11335:                      foreach my $id (@possibilities) {
11336: 			 my $file=$bighash{'src_'.$id};
11337:                          my $canaccess;
11338:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11339:                              $canaccess = 1;
11340:                          } else { 
11341:                              $canaccess = &allowed('bre',$file);
11342:                          }
11343:                          if ($canaccess) {
11344:          		     my ($mapid,$resid)=split(/\./,$id);
11345:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
11346:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11347: 						             $resid,$thisfn);
11348:                                  if (ref($possibles) eq 'HASH') {
11349:                                      $possibles->{$syval} = 1;
11350:                                  }
11351:                                  if ($checkforblock) {
11352:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11353:                                      unless (@blockers > 0) {
11354:                                          $syval = $poss_syval;
11355:                                          $realpossible++;
11356:                                      }
11357:                                  } else {
11358:                                      $syval = $poss_syval;
11359:                                      $realpossible++;
11360:                                  }
11361:                              }
11362: 			 }
11363:                      }
11364: 		     if ($realpossible!=1) { $syval=''; }
11365:                  } else {
11366:                      $syval='';
11367:                  }
11368: 	      }
11369:               untie(%bighash);
11370:            }
11371:         }
11372:         if ($syval) {
11373: 	    return $env{$cache_str}=$syval;
11374:         }
11375:     }
11376:     &appenv({'request.ambiguous' => $thisfn});
11377:     return $env{$cache_str}='';
11378: }
11379: 
11380: # ---------------------------------------------------------- Return random seed
11381: 
11382: sub numval {
11383:     my $txt=shift;
11384:     $txt=~tr/A-J/0-9/;
11385:     $txt=~tr/a-j/0-9/;
11386:     $txt=~tr/K-T/0-9/;
11387:     $txt=~tr/k-t/0-9/;
11388:     $txt=~tr/U-Z/0-5/;
11389:     $txt=~tr/u-z/0-5/;
11390:     $txt=~s/\D//g;
11391:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11392:     return int($txt);
11393: }
11394: 
11395: sub numval2 {
11396:     my $txt=shift;
11397:     $txt=~tr/A-J/0-9/;
11398:     $txt=~tr/a-j/0-9/;
11399:     $txt=~tr/K-T/0-9/;
11400:     $txt=~tr/k-t/0-9/;
11401:     $txt=~tr/U-Z/0-5/;
11402:     $txt=~tr/u-z/0-5/;
11403:     $txt=~s/\D//g;
11404:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11405:     my $total;
11406:     foreach my $val (@txts) { $total+=$val; }
11407:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11408:     return int($total);
11409: }
11410: 
11411: sub numval3 {
11412:     use integer;
11413:     my $txt=shift;
11414:     $txt=~tr/A-J/0-9/;
11415:     $txt=~tr/a-j/0-9/;
11416:     $txt=~tr/K-T/0-9/;
11417:     $txt=~tr/k-t/0-9/;
11418:     $txt=~tr/U-Z/0-5/;
11419:     $txt=~tr/u-z/0-5/;
11420:     $txt=~s/\D//g;
11421:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11422:     my $total;
11423:     foreach my $val (@txts) { $total+=$val; }
11424:     if ($_64bit) { $total=(($total<<32)>>32); }
11425:     return $total;
11426: }
11427: 
11428: sub digest {
11429:     my ($data)=@_;
11430:     my $digest=&Digest::MD5::md5($data);
11431:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11432:     my ($e,$f);
11433:     {
11434:         use integer;
11435:         $e=($a+$b);
11436:         $f=($c+$d);
11437:         if ($_64bit) {
11438:             $e=(($e<<32)>>32);
11439:             $f=(($f<<32)>>32);
11440:         }
11441:     }
11442:     if (wantarray) {
11443: 	return ($e,$f);
11444:     } else {
11445: 	my $g;
11446: 	{
11447: 	    use integer;
11448: 	    $g=($e+$f);
11449: 	    if ($_64bit) {
11450: 		$g=(($g<<32)>>32);
11451: 	    }
11452: 	}
11453: 	return $g;
11454:     }
11455: }
11456: 
11457: sub latest_rnd_algorithm_id {
11458:     return '64bit5';
11459: }
11460: 
11461: sub get_rand_alg {
11462:     my ($courseid)=@_;
11463:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11464:     if ($courseid) {
11465: 	return $env{"course.$courseid.rndseed"};
11466:     }
11467:     return &latest_rnd_algorithm_id();
11468: }
11469: 
11470: sub validCODE {
11471:     my ($CODE)=@_;
11472:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11473:     return 0;
11474: }
11475: 
11476: sub getCODE {
11477:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11478:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11479: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11480: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11481: 	return $Apache::lonhomework::history{'resource.CODE'};
11482:     }
11483:     return undef;
11484: }
11485: #
11486: #  Determines the random seed for a specific context:
11487: #
11488: # parameters:
11489: #   symb      - in course context the symb for the seed.
11490: #   course_id - The course id of the form domain_coursenum.
11491: #   domain    - Domain for the user.
11492: #   course    - Course for the user.
11493: #   cenv      - environment of the course.
11494: #
11495: # NOTE:
11496: #   All parameters are picked out of the environment if missing
11497: #   or not defined.
11498: #   If a symb cannot be determined the current time is used instead.
11499: #
11500: #  For a given well defined symb, courside, domain, username,
11501: #  and course environment, the seed is reproducible.
11502: #
11503: sub rndseed {
11504:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11505:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11506:     if (!defined($symb)) {
11507: 	unless ($symb=$wsymb) { return time; }
11508:     }
11509:     if (!defined $courseid) { 
11510: 	$courseid=$wcourseid; 
11511:     }
11512:     if (!defined $domain) { $domain=$wdomain; }
11513:     if (!defined $username) { $username=$wusername }
11514: 
11515:     my $which;
11516:     if (defined($cenv->{'rndseed'})) {
11517: 	$which = $cenv->{'rndseed'};
11518:     } else {
11519: 	$which =&get_rand_alg($courseid);
11520:     }
11521:     if (defined(&getCODE())) {
11522: 
11523: 	if ($which eq '64bit5') {
11524: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11525: 	} elsif ($which eq '64bit4') {
11526: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11527: 	} else {
11528: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11529: 	}
11530:     } elsif ($which eq '64bit5') {
11531: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11532:     } elsif ($which eq '64bit4') {
11533: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11534:     } elsif ($which eq '64bit3') {
11535: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11536:     } elsif ($which eq '64bit2') {
11537: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11538:     } elsif ($which eq '64bit') {
11539: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11540:     }
11541:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11542: }
11543: 
11544: sub rndseed_32bit {
11545:     my ($symb,$courseid,$domain,$username)=@_;
11546:     {
11547: 	use integer;
11548: 	my $symbchck=unpack("%32C*",$symb) << 27;
11549: 	my $symbseed=numval($symb) << 22;
11550: 	my $namechck=unpack("%32C*",$username) << 17;
11551: 	my $nameseed=numval($username) << 12;
11552: 	my $domainseed=unpack("%32C*",$domain) << 7;
11553: 	my $courseseed=unpack("%32C*",$courseid);
11554: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11555: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11556: 	#&logthis("rndseed :$num:$symb");
11557: 	if ($_64bit) { $num=(($num<<32)>>32); }
11558: 	return $num;
11559:     }
11560: }
11561: 
11562: sub rndseed_64bit {
11563:     my ($symb,$courseid,$domain,$username)=@_;
11564:     {
11565: 	use integer;
11566: 	my $symbchck=unpack("%32S*",$symb) << 21;
11567: 	my $symbseed=numval($symb) << 10;
11568: 	my $namechck=unpack("%32S*",$username);
11569: 	
11570: 	my $nameseed=numval($username) << 21;
11571: 	my $domainseed=unpack("%32S*",$domain) << 10;
11572: 	my $courseseed=unpack("%32S*",$courseid);
11573: 	
11574: 	my $num1=$symbchck+$symbseed+$namechck;
11575: 	my $num2=$nameseed+$domainseed+$courseseed;
11576: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11577: 	#&logthis("rndseed :$num:$symb");
11578: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11579: 	return "$num1,$num2";
11580:     }
11581: }
11582: 
11583: sub rndseed_64bit2 {
11584:     my ($symb,$courseid,$domain,$username)=@_;
11585:     {
11586: 	use integer;
11587: 	# strings need to be an even # of cahracters long, it it is odd the
11588:         # last characters gets thrown away
11589: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11590: 	my $symbseed=numval($symb) << 10;
11591: 	my $namechck=unpack("%32S*",$username.' ');
11592: 	
11593: 	my $nameseed=numval($username) << 21;
11594: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11595: 	my $courseseed=unpack("%32S*",$courseid.' ');
11596: 	
11597: 	my $num1=$symbchck+$symbseed+$namechck;
11598: 	my $num2=$nameseed+$domainseed+$courseseed;
11599: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11600: 	#&logthis("rndseed :$num:$symb");
11601: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11602: 	return "$num1,$num2";
11603:     }
11604: }
11605: 
11606: sub rndseed_64bit3 {
11607:     my ($symb,$courseid,$domain,$username)=@_;
11608:     {
11609: 	use integer;
11610: 	# strings need to be an even # of cahracters long, it it is odd the
11611:         # last characters gets thrown away
11612: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11613: 	my $symbseed=numval2($symb) << 10;
11614: 	my $namechck=unpack("%32S*",$username.' ');
11615: 	
11616: 	my $nameseed=numval2($username) << 21;
11617: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11618: 	my $courseseed=unpack("%32S*",$courseid.' ');
11619: 	
11620: 	my $num1=$symbchck+$symbseed+$namechck;
11621: 	my $num2=$nameseed+$domainseed+$courseseed;
11622: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11623: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11624: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11625: 	
11626: 	return "$num1:$num2";
11627:     }
11628: }
11629: 
11630: sub rndseed_64bit4 {
11631:     my ($symb,$courseid,$domain,$username)=@_;
11632:     {
11633: 	use integer;
11634: 	# strings need to be an even # of cahracters long, it it is odd the
11635:         # last characters gets thrown away
11636: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11637: 	my $symbseed=numval3($symb) << 10;
11638: 	my $namechck=unpack("%32S*",$username.' ');
11639: 	
11640: 	my $nameseed=numval3($username) << 21;
11641: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11642: 	my $courseseed=unpack("%32S*",$courseid.' ');
11643: 	
11644: 	my $num1=$symbchck+$symbseed+$namechck;
11645: 	my $num2=$nameseed+$domainseed+$courseseed;
11646: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11647: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11648: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11649: 	
11650: 	return "$num1:$num2";
11651:     }
11652: }
11653: 
11654: sub rndseed_64bit5 {
11655:     my ($symb,$courseid,$domain,$username)=@_;
11656:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11657:     return "$num1:$num2";
11658: }
11659: 
11660: sub rndseed_CODE_64bit {
11661:     my ($symb,$courseid,$domain,$username)=@_;
11662:     {
11663: 	use integer;
11664: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11665: 	my $symbseed=numval2($symb);
11666: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11667: 	my $CODEseed=numval(&getCODE());
11668: 	my $courseseed=unpack("%32S*",$courseid.' ');
11669: 	my $num1=$symbseed+$CODEchck;
11670: 	my $num2=$CODEseed+$courseseed+$symbchck;
11671: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11672: 	#&logthis("rndseed :$num1:$num2:$symb");
11673: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11674: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11675: 	return "$num1:$num2";
11676:     }
11677: }
11678: 
11679: sub rndseed_CODE_64bit4 {
11680:     my ($symb,$courseid,$domain,$username)=@_;
11681:     {
11682: 	use integer;
11683: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11684: 	my $symbseed=numval3($symb);
11685: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11686: 	my $CODEseed=numval3(&getCODE());
11687: 	my $courseseed=unpack("%32S*",$courseid.' ');
11688: 	my $num1=$symbseed+$CODEchck;
11689: 	my $num2=$CODEseed+$courseseed+$symbchck;
11690: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11691: 	#&logthis("rndseed :$num1:$num2:$symb");
11692: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11693: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11694: 	return "$num1:$num2";
11695:     }
11696: }
11697: 
11698: sub rndseed_CODE_64bit5 {
11699:     my ($symb,$courseid,$domain,$username)=@_;
11700:     my $code = &getCODE();
11701:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11702:     return "$num1:$num2";
11703: }
11704: 
11705: sub setup_random_from_rndseed {
11706:     my ($rndseed)=@_;
11707:     if ($rndseed =~/([,:])/) {
11708:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11709:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11710:             &Math::Random::random_set_seed_from_phrase($rndseed);
11711:         } else {
11712:             &Math::Random::random_set_seed($num1,$num2);
11713:         }
11714:     } else {
11715: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11716:     }
11717: }
11718: 
11719: sub latest_receipt_algorithm_id {
11720:     return 'receipt3';
11721: }
11722: 
11723: sub recunique {
11724:     my $fucourseid=shift;
11725:     my $unique;
11726:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11727: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11728: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11729:     } else {
11730: 	$unique=$perlvar{'lonReceipt'};
11731:     }
11732:     return unpack("%32C*",$unique);
11733: }
11734: 
11735: sub recprefix {
11736:     my $fucourseid=shift;
11737:     my $prefix;
11738:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11739: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11740: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11741:     } else {
11742: 	$prefix=$perlvar{'lonHostID'};
11743:     }
11744:     return unpack("%32C*",$prefix);
11745: }
11746: 
11747: sub ireceipt {
11748:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11749: 
11750:     my $return =&recprefix($fucourseid).'-';
11751: 
11752:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11753: 	$env{'request.state'} eq 'construct') {
11754: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11755: 	return $return;
11756:     }
11757: 
11758:     my $cuname=unpack("%32C*",$funame);
11759:     my $cudom=unpack("%32C*",$fudom);
11760:     my $cucourseid=unpack("%32C*",$fucourseid);
11761:     my $cusymb=unpack("%32C*",$fusymb);
11762:     my $cunique=&recunique($fucourseid);
11763:     my $cpart=unpack("%32S*",$part);
11764:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11765: 
11766: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11767: 			       
11768: 	$return.= ($cunique%$cuname+
11769: 		   $cunique%$cudom+
11770: 		   $cusymb%$cuname+
11771: 		   $cusymb%$cudom+
11772: 		   $cucourseid%$cuname+
11773: 		   $cucourseid%$cudom+
11774: 		   $cpart%$cuname+
11775: 		   $cpart%$cudom);
11776:     } else {
11777: 	$return.= ($cunique%$cuname+
11778: 		   $cunique%$cudom+
11779: 		   $cusymb%$cuname+
11780: 		   $cusymb%$cudom+
11781: 		   $cucourseid%$cuname+
11782: 		   $cucourseid%$cudom);
11783:     }
11784:     return $return;
11785: }
11786: 
11787: sub receipt {
11788:     my ($part)=@_;
11789:     my ($symb,$courseid,$domain,$name) = &whichuser();
11790:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11791: }
11792: 
11793: sub whichuser {
11794:     my ($passedsymb)=@_;
11795:     my ($symb,$courseid,$domain,$name,$publicuser);
11796:     if (defined($env{'form.grade_symb'})) {
11797: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11798: 	my $allowed=&allowed('vgr',$tmp_courseid);
11799: 	if (!$allowed &&
11800: 	    exists($env{'request.course.sec'}) &&
11801: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11802: 	    $allowed=&allowed('vgr',$tmp_courseid.
11803: 			      '/'.$env{'request.course.sec'});
11804: 	}
11805: 	if ($allowed) {
11806: 	    ($symb)=&get_env_multiple('form.grade_symb');
11807: 	    $courseid=$tmp_courseid;
11808: 	    ($domain)=&get_env_multiple('form.grade_domain');
11809: 	    ($name)=&get_env_multiple('form.grade_username');
11810: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11811: 	}
11812:     }
11813:     if (!$passedsymb) {
11814: 	$symb=&symbread();
11815:     } else {
11816: 	$symb=$passedsymb;
11817:     }
11818:     $courseid=$env{'request.course.id'};
11819:     $domain=$env{'user.domain'};
11820:     $name=$env{'user.name'};
11821:     if ($name eq 'public' && $domain eq 'public') {
11822: 	if (!defined($env{'form.username'})) {
11823: 	    $env{'form.username'}.=time.rand(10000000);
11824: 	}
11825: 	$name.=$env{'form.username'};
11826:     }
11827:     return ($symb,$courseid,$domain,$name,$publicuser);
11828: 
11829: }
11830: 
11831: # ------------------------------------------------------------ Serves up a file
11832: # returns either the contents of the file or 
11833: # -1 if the file doesn't exist
11834: #
11835: # if the target is a file that was uploaded via DOCS, 
11836: # a check will be made to see if a current copy exists on the local server,
11837: # if it does this will be served, otherwise a copy will be retrieved from
11838: # the home server for the course and stored in /home/httpd/html/userfiles on
11839: # the local server.   
11840: 
11841: sub getfile {
11842:     my ($file) = @_;
11843:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11844:     &repcopy($file);
11845:     return &readfile($file);
11846: }
11847: 
11848: sub repcopy_userfile {
11849:     my ($file)=@_;
11850:     my $londocroot = $perlvar{'lonDocRoot'};
11851:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11852:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11853:     my ($cdom,$cnum,$filename) = 
11854: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11855:     my $uri="/uploaded/$cdom/$cnum/$filename";
11856:     if (-e "$file") {
11857: # we already have a local copy, check it out
11858: 	my @fileinfo = stat($file);
11859: 	my $rtncode;
11860: 	my $info;
11861: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11862: 	if ($lwpresp ne 'ok') {
11863: # there is no such file anymore, even though we had a local copy
11864: 	    if ($rtncode eq '404') {
11865: 		unlink($file);
11866: 	    }
11867: 	    return -1;
11868: 	}
11869: 	if ($info < $fileinfo[9]) {
11870: # nice, the file we have is up-to-date, just say okay
11871: 	    return 'ok';
11872: 	} else {
11873: # the file is outdated, get rid of it
11874: 	    unlink($file);
11875: 	}
11876:     }
11877: # one way or the other, at this point, we don't have the file
11878: # construct the correct path for the file
11879:     my @parts = ($cdom,$cnum); 
11880:     if ($filename =~ m|^(.+)/[^/]+$|) {
11881: 	push @parts, split(/\//,$1);
11882:     }
11883:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11884:     foreach my $part (@parts) {
11885: 	$path .= '/'.$part;
11886: 	if (!-e $path) {
11887: 	    mkdir($path,0770);
11888: 	}
11889:     }
11890: # now the path exists for sure
11891: # get a user agent
11892:     my $ua=new LWP::UserAgent;
11893:     my $transferfile=$file.'.in.transfer';
11894: # FIXME: this should flock
11895:     if (-e $transferfile) { return 'ok'; }
11896:     my $request;
11897:     $uri=~s/^\///;
11898:     my $homeserver = &homeserver($cnum,$cdom);
11899:     my $protocol = $protocol{$homeserver};
11900:     $protocol = 'http' if ($protocol ne 'https');
11901:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11902:     my $response=$ua->request($request,$transferfile);
11903: # did it work?
11904:     if ($response->is_error()) {
11905: 	unlink($transferfile);
11906: 	&logthis("Userfile repcopy failed for $uri");
11907: 	return -1;
11908:     }
11909: # worked, rename the transfer file
11910:     rename($transferfile,$file);
11911:     return 'ok';
11912: }
11913: 
11914: sub tokenwrapper {
11915:     my $uri=shift;
11916:     $uri=~s|^https?\://([^/]+)||;
11917:     $uri=~s|^/||;
11918:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11919:     my $token=$1;
11920:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11921:     if ($udom && $uname && $file) {
11922: 	$file=~s|(\?\.*)*$||;
11923:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11924:         my $homeserver = &homeserver($uname,$udom);
11925:         my $protocol = $protocol{$homeserver};
11926:         $protocol = 'http' if ($protocol ne 'https');
11927:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11928:                (($uri=~/\?/)?'&':'?').'token='.$token.
11929:                                '&tokenissued='.$perlvar{'lonHostID'};
11930:     } else {
11931:         return '/adm/notfound.html';
11932:     }
11933: }
11934: 
11935: # call with reqtype HEAD: get last modification time
11936: # call with reqtype GET: get the file contents
11937: # Do not call this with reqtype GET for large files! It loads everything into memory
11938: #
11939: sub getuploaded {
11940:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11941:     $uri=~s/^\///;
11942:     my $homeserver = &homeserver($cnum,$cdom);
11943:     my $protocol = $protocol{$homeserver};
11944:     $protocol = 'http' if ($protocol ne 'https');
11945:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11946:     my $ua=new LWP::UserAgent;
11947:     my $request=new HTTP::Request($reqtype,$uri);
11948:     my $response=$ua->request($request);
11949:     $$rtncode = $response->code;
11950:     if (! $response->is_success()) {
11951: 	return 'failed';
11952:     }      
11953:     if ($reqtype eq 'HEAD') {
11954: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11955:     } elsif ($reqtype eq 'GET') {
11956: 	$$info = $response->content;
11957:     }
11958:     return 'ok';
11959: }
11960: 
11961: sub readfile {
11962:     my $file = shift;
11963:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11964:     my $fh;
11965:     open($fh,"<$file");
11966:     my $a='';
11967:     while (my $line = <$fh>) { $a .= $line; }
11968:     return $a;
11969: }
11970: 
11971: sub filelocation {
11972:     my ($dir,$file) = @_;
11973:     my $location;
11974:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11975: 
11976:     if ($file =~ m-^/adm/-) {
11977: 	$file=~s-^/adm/wrapper/-/-;
11978: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11979:     }
11980: 
11981:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11982:         $location = $file;
11983:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11984:         my ($udom,$uname,$filename)=
11985:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11986:         my $home=&homeserver($uname,$udom);
11987:         my $is_me=0;
11988:         my @ids=&current_machine_ids();
11989:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11990:         if ($is_me) {
11991:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11992:         } else {
11993:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11994:   	      $udom.'/'.$uname.'/'.$filename;
11995:         }
11996:     } elsif ($file =~ m-^/adm/-) {
11997: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11998:     } else {
11999:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
12000:         $file=~s:^/(res|priv)/:/:;
12001:         my $space=$1;
12002:         if ( !( $file =~ m:^/:) ) {
12003:             $location = $dir. '/'.$file;
12004:         } else {
12005:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
12006:         }
12007:     }
12008:     $location=~s://+:/:g; # remove duplicate /
12009:     while ($location=~m{/\.\./}) {
12010: 	if ($location =~ m{/[^/]+/\.\./}) {
12011: 	    $location=~ s{/[^/]+/\.\./}{/}g;
12012: 	} else {
12013: 	    $location=~ s{/\.\./}{/}g;
12014: 	}
12015:     } #remove dir/..
12016:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12017:     return $location;
12018: }
12019: 
12020: sub hreflocation {
12021:     my ($dir,$file)=@_;
12022:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
12023: 	$file=filelocation($dir,$file);
12024:     } elsif ($file=~m-^/adm/-) {
12025: 	$file=~s-^/adm/wrapper/-/-;
12026: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12027:     }
12028:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12029: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12030:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
12031: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12032: 	        {/uploaded/$1/$2/}x;
12033:     }
12034:     if ($file=~ m{^/userfiles/}) {
12035: 	$file =~ s{^/userfiles/}{/uploaded/};
12036:     }
12037:     return $file;
12038: }
12039: 
12040: 
12041: 
12042: 
12043: 
12044: sub current_machine_domains {
12045:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
12046: }
12047: 
12048: sub machine_domains {
12049:     my ($hostname) = @_;
12050:     my @domains;
12051:     my %hostname = &all_hostnames();
12052:     while( my($id, $name) = each(%hostname)) {
12053: #	&logthis("-$id-$name-$hostname-");
12054: 	if ($hostname eq $name) {
12055: 	    push(@domains,&host_domain($id));
12056: 	}
12057:     }
12058:     return @domains;
12059: }
12060: 
12061: sub current_machine_ids {
12062:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
12063: }
12064: 
12065: sub machine_ids {
12066:     my ($hostname) = @_;
12067:     $hostname ||= &hostname($perlvar{'lonHostID'});
12068:     my @ids;
12069:     my %name_to_host = &all_names();
12070:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12071: 	return @{ $name_to_host{$hostname} };
12072:     }
12073:     return;
12074: }
12075: 
12076: sub additional_machine_domains {
12077:     my @domains;
12078:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12079:     while( my $line = <$fh>) {
12080:         $line =~ s/\s//g;
12081:         push(@domains,$line);
12082:     }
12083:     return @domains;
12084: }
12085: 
12086: sub default_login_domain {
12087:     my $domain = $perlvar{'lonDefDomain'};
12088:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12089:     foreach my $posdom (&current_machine_domains(),
12090:                         &additional_machine_domains()) {
12091:         if (lc($posdom) eq lc($testdomain)) {
12092:             $domain=$posdom;
12093:             last;
12094:         }
12095:     }
12096:     return $domain;
12097: }
12098: 
12099: # ------------------------------------------------------------- Declutters URLs
12100: 
12101: sub declutter {
12102:     my $thisfn=shift;
12103:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12104:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12105:         $thisfn=~s{^/home/httpd/html}{};
12106:     }
12107:     $thisfn=~s/^\///;
12108:     $thisfn=~s|^adm/wrapper/||;
12109:     $thisfn=~s|^adm/coursedocs/showdoc/||;
12110:     $thisfn=~s/^res\///;
12111:     $thisfn=~s/^priv\///;
12112:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12113:         $thisfn=~s/\?.+$//;
12114:     }
12115:     return $thisfn;
12116: }
12117: 
12118: # ------------------------------------------------------------- Clutter up URLs
12119: 
12120: sub clutter {
12121:     my $thisfn='/'.&declutter(shift);
12122:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
12123: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
12124:        $thisfn='/res'.$thisfn; 
12125:     }
12126:     if ($thisfn !~m|^/adm|) {
12127: 	if ($thisfn =~ m|^/ext/|) {
12128: 	    $thisfn='/adm/wrapper'.$thisfn;
12129: 	} else {
12130: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
12131: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
12132: 	    if ($embstyle eq 'ssi'
12133: 		|| ($embstyle eq 'hdn')
12134: 		|| ($embstyle eq 'rat')
12135: 		|| ($embstyle eq 'prv')
12136: 		|| ($embstyle eq 'ign')) {
12137: 		#do nothing with these
12138: 	    } elsif (($embstyle eq 'img') 
12139: 		|| ($embstyle eq 'emb')
12140: 		|| ($embstyle eq 'wrp')) {
12141: 		$thisfn='/adm/wrapper'.$thisfn;
12142: 	    } elsif ($embstyle eq 'unk'
12143: 		     && $thisfn!~/\.(sequence|page)$/) {
12144: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
12145: 	    } else {
12146: #		&logthis("Got a blank emb style");
12147: 	    }
12148: 	}
12149:     }
12150:     return $thisfn;
12151: }
12152: 
12153: sub clutter_with_no_wrapper {
12154:     my $uri = &clutter(shift);
12155:     if ($uri =~ m-^/adm/-) {
12156: 	$uri =~ s-^/adm/wrapper/-/-;
12157: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
12158:     }
12159:     return $uri;
12160: }
12161: 
12162: sub freeze_escape {
12163:     my ($value)=@_;
12164:     if (ref($value)) {
12165: 	$value=&nfreeze($value);
12166: 	return '__FROZEN__'.&escape($value);
12167:     }
12168:     return &escape($value);
12169: }
12170: 
12171: 
12172: sub thaw_unescape {
12173:     my ($value)=@_;
12174:     if ($value =~ /^__FROZEN__/) {
12175: 	substr($value,0,10,undef);
12176: 	$value=&unescape($value);
12177: 	return &thaw($value);
12178:     }
12179:     return &unescape($value);
12180: }
12181: 
12182: sub correct_line_ends {
12183:     my ($result)=@_;
12184:     $$result =~s/\r\n/\n/mg;
12185:     $$result =~s/\r/\n/mg;
12186: }
12187: # ================================================================ Main Program
12188: 
12189: sub goodbye {
12190:    &logthis("Starting Shut down");
12191: #not converted to using infrastruture and probably shouldn't be
12192:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
12193: #converted
12194: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
12195:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12196: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12197: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
12198: #1.1 only
12199: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12200: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12201: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12202: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12203:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12204:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12205:    &logthis(sprintf("%-20s is %s",'hits',$hits));
12206:    &flushcourselogs();
12207:    &logthis("Shutting down");
12208: }
12209: 
12210: sub get_dns {
12211:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12212:     if (!$ignore_cache) {
12213: 	my ($content,$cached)=
12214: 	    &Apache::lonnet::is_cached_new('dns',$url);
12215: 	if ($cached) {
12216: 	    &$func($content,$hashref);
12217: 	    return;
12218: 	}
12219:     }
12220: 
12221:     my %alldns;
12222:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12223:     foreach my $dns (<$config>) {
12224: 	next if ($dns !~ /^\^(\S*)/x);
12225:         my $line = $1;
12226:         my ($host,$protocol) = split(/:/,$line);
12227:         if ($protocol ne 'https') {
12228:             $protocol = 'http';
12229:         }
12230: 	$alldns{$host} = $protocol;
12231:     }
12232:     while (%alldns) {
12233: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12234: 	my $ua=new LWP::UserAgent;
12235:         $ua->timeout(30);
12236: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12237: 	my $response=$ua->request($request);
12238:         delete($alldns{$dns});
12239: 	next if ($response->is_error());
12240: 	my @content = split("\n",$response->content);
12241: 	unless ($nocache) {
12242: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12243: 	}
12244: 	&$func(\@content,$hashref);
12245: 	return;
12246:     }
12247:     close($config);
12248:     my $which = (split('/',$url))[3];
12249:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12250:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12251:     my @content = <$config>;
12252:     &$func(\@content,$hashref);
12253:     return;
12254: }
12255: 
12256: # ------------------------------------------------------Get DNS checksums file
12257: sub parse_dns_checksums_tab {
12258:     my ($lines,$hashref) = @_;
12259:     my $lonhost = $perlvar{'lonHostID'};
12260:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12261:     my $loncaparev = &get_server_loncaparev($machine_dom);
12262:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12263:     my $webconfdir = '/etc/httpd/conf';
12264:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12265:         $webconfdir = '/etc/apache2';
12266:     } elsif ($distro =~ /^sles(\d+)$/) {
12267:         if ($1 >= 10) {
12268:             $webconfdir = '/etc/apache2';
12269:         }
12270:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12271:         if ($1 >= 10.0) {
12272:             $webconfdir = '/etc/apache2';
12273:         }
12274:     }
12275:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12276:     my (%chksum,%revnum);
12277:     if (ref($lines) eq 'ARRAY') {
12278:         chomp(@{$lines});
12279:         my $version = shift(@{$lines});
12280:         if ($version eq $release) {  
12281:             foreach my $line (@{$lines}) {
12282:                 my ($file,$version,$shasum) = split(/,/,$line);
12283:                 if ($file =~ m{^/etc/httpd/conf}) {
12284:                     if ($webconfdir eq '/etc/apache2') {
12285:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12286:                     }
12287:                 }
12288:                 $chksum{$file} = $shasum;
12289:                 $revnum{$file} = $version;
12290:             }
12291:             if (ref($hashref) eq 'HASH') {
12292:                 %{$hashref} = (
12293:                                 sums     => \%chksum,
12294:                                 versions => \%revnum,
12295:                               );
12296:             }
12297:         }
12298:     }
12299:     return;
12300: }
12301: 
12302: sub fetch_dns_checksums {
12303:     my %checksums;
12304:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12305:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12306:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12307:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12308:              \%checksums);
12309:     return \%checksums;
12310: }
12311: 
12312: # ------------------------------------------------------------ Read domain file
12313: {
12314:     my $loaded;
12315:     my %domain;
12316: 
12317:     sub parse_domain_tab {
12318: 	my ($lines) = @_;
12319: 	foreach my $line (@$lines) {
12320: 	    next if ($line =~ /^(\#|\s*$ )/x);
12321: 
12322: 	    chomp($line);
12323: 	    my ($name,@elements) = split(/:/,$line,9);
12324: 	    my %this_domain;
12325: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12326: 			       'lang_def', 'city', 'longi', 'lati',
12327: 			       'primary') {
12328: 		$this_domain{$field} = shift(@elements);
12329: 	    }
12330: 	    $domain{$name} = \%this_domain;
12331: 	}
12332:     }
12333: 
12334:     sub reset_domain_info {
12335: 	undef($loaded);
12336: 	undef(%domain);
12337:     }
12338: 
12339:     sub load_domain_tab {
12340: 	my ($ignore_cache) = @_;
12341: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
12342: 	my $fh;
12343: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12344: 	    my @lines = <$fh>;
12345: 	    &parse_domain_tab(\@lines);
12346: 	}
12347: 	close($fh);
12348: 	$loaded = 1;
12349:     }
12350: 
12351:     sub domain {
12352: 	&load_domain_tab() if (!$loaded);
12353: 
12354: 	my ($name,$what) = @_;
12355: 	return if ( !exists($domain{$name}) );
12356: 
12357: 	if (!$what) {
12358: 	    return $domain{$name}{'description'};
12359: 	}
12360: 	return $domain{$name}{$what};
12361:     }
12362: 
12363:     sub domain_info {
12364:         &load_domain_tab() if (!$loaded);
12365:         return %domain;
12366:     }
12367: 
12368: }
12369: 
12370: 
12371: # ------------------------------------------------------------- Read hosts file
12372: {
12373:     my %hostname;
12374:     my %hostdom;
12375:     my %libserv;
12376:     my $loaded;
12377:     my %name_to_host;
12378:     my %internetdom;
12379:     my %LC_dns_serv;
12380: 
12381:     sub parse_hosts_tab {
12382: 	my ($file) = @_;
12383: 	foreach my $configline (@$file) {
12384: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12385:             chomp($configline);
12386: 	    if ($configline =~ /^\^/) {
12387:                 if ($configline =~ /^\^([\w.\-]+)/) {
12388:                     $LC_dns_serv{$1} = 1;
12389:                 }
12390:                 next;
12391:             }
12392: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12393: 	    $name=~s/\s//g;
12394: 	    if ($id && $domain && $role && $name) {
12395: 		$hostname{$id}=$name;
12396: 		push(@{$name_to_host{$name}}, $id);
12397: 		$hostdom{$id}=$domain;
12398: 		if ($role eq 'library') { $libserv{$id}=$name; }
12399:                 if (defined($protocol)) {
12400:                     if ($protocol eq 'https') {
12401:                         $protocol{$id} = $protocol;
12402:                     } else {
12403:                         $protocol{$id} = 'http'; 
12404:                     }
12405:                 } else {
12406:                     $protocol{$id} = 'http';
12407:                 }
12408:                 if (defined($intdom)) {
12409:                     $internetdom{$id} = $intdom;
12410:                 }
12411: 	    }
12412: 	}
12413:     }
12414:     
12415:     sub reset_hosts_info {
12416: 	&purge_remembered();
12417: 	&reset_domain_info();
12418: 	&reset_hosts_ip_info();
12419: 	undef(%name_to_host);
12420: 	undef(%hostname);
12421: 	undef(%hostdom);
12422: 	undef(%libserv);
12423: 	undef($loaded);
12424:     }
12425: 
12426:     sub load_hosts_tab {
12427: 	my ($ignore_cache) = @_;
12428: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12429: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12430: 	my @config = <$config>;
12431: 	&parse_hosts_tab(\@config);
12432: 	close($config);
12433: 	$loaded=1;
12434:     }
12435: 
12436:     sub hostname {
12437: 	&load_hosts_tab() if (!$loaded);
12438: 
12439: 	my ($lonid) = @_;
12440: 	return $hostname{$lonid};
12441:     }
12442: 
12443:     sub all_hostnames {
12444: 	&load_hosts_tab() if (!$loaded);
12445: 
12446: 	return %hostname;
12447:     }
12448: 
12449:     sub all_names {
12450: 	&load_hosts_tab() if (!$loaded);
12451: 
12452: 	return %name_to_host;
12453:     }
12454: 
12455:     sub all_host_domain {
12456:         &load_hosts_tab() if (!$loaded);
12457:         return %hostdom;
12458:     }
12459: 
12460:     sub is_library {
12461: 	&load_hosts_tab() if (!$loaded);
12462: 
12463: 	return exists($libserv{$_[0]});
12464:     }
12465: 
12466:     sub all_library {
12467: 	&load_hosts_tab() if (!$loaded);
12468: 
12469: 	return %libserv;
12470:     }
12471: 
12472:     sub unique_library {
12473: 	#2x reverse removes all hostnames that appear more than once
12474:         my %unique = reverse &all_library();
12475:         return reverse %unique;
12476:     }
12477: 
12478:     sub get_servers {
12479: 	&load_hosts_tab() if (!$loaded);
12480: 
12481: 	my ($domain,$type) = @_;
12482: 	my %possible_hosts = ($type eq 'library') ? %libserv
12483: 	                                          : %hostname;
12484: 	my %result;
12485: 	if (ref($domain) eq 'ARRAY') {
12486: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12487: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12488: 		    $result{$host} = $hostname;
12489: 		}
12490: 	    }
12491: 	} else {
12492: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12493: 		if ($hostdom{$host} eq $domain) {
12494: 		    $result{$host} = $hostname;
12495: 		}
12496: 	    }
12497: 	}
12498: 	return %result;
12499:     }
12500: 
12501:     sub get_unique_servers {
12502:         my %unique = reverse &get_servers(@_);
12503: 	return reverse %unique;
12504:     }
12505: 
12506:     sub host_domain {
12507: 	&load_hosts_tab() if (!$loaded);
12508: 
12509: 	my ($lonid) = @_;
12510: 	return $hostdom{$lonid};
12511:     }
12512: 
12513:     sub all_domains {
12514: 	&load_hosts_tab() if (!$loaded);
12515: 
12516: 	my %seen;
12517: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12518: 	return @uniq;
12519:     }
12520: 
12521:     sub internet_dom {
12522:         &load_hosts_tab() if (!$loaded);
12523: 
12524:         my ($lonid) = @_;
12525:         return $internetdom{$lonid};
12526:     }
12527: 
12528:     sub is_LC_dns {
12529:         &load_hosts_tab() if (!$loaded);
12530: 
12531:         my ($hostname) = @_;
12532:         return exists($LC_dns_serv{$hostname});
12533:     }
12534: 
12535: }
12536: 
12537: { 
12538:     my %iphost;
12539:     my %name_to_ip;
12540:     my %lonid_to_ip;
12541: 
12542:     sub get_hosts_from_ip {
12543: 	my ($ip) = @_;
12544: 	my %iphosts = &get_iphost();
12545: 	if (ref($iphosts{$ip})) {
12546: 	    return @{$iphosts{$ip}};
12547: 	}
12548: 	return;
12549:     }
12550:     
12551:     sub reset_hosts_ip_info {
12552: 	undef(%iphost);
12553: 	undef(%name_to_ip);
12554: 	undef(%lonid_to_ip);
12555:     }
12556: 
12557:     sub get_host_ip {
12558: 	my ($lonid) = @_;
12559: 	if (exists($lonid_to_ip{$lonid})) {
12560: 	    return $lonid_to_ip{$lonid};
12561: 	}
12562: 	my $name=&hostname($lonid);
12563:    	my $ip = gethostbyname($name);
12564: 	return if (!$ip || length($ip) ne 4);
12565: 	$ip=inet_ntoa($ip);
12566: 	$name_to_ip{$name}   = $ip;
12567: 	$lonid_to_ip{$lonid} = $ip;
12568: 	return $ip;
12569:     }
12570:     
12571:     sub get_iphost {
12572: 	my ($ignore_cache) = @_;
12573: 
12574: 	if (!$ignore_cache) {
12575: 	    if (%iphost) {
12576: 		return %iphost;
12577: 	    }
12578: 	    my ($ip_info,$cached)=
12579: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12580: 	    if ($cached) {
12581: 		%iphost      = %{$ip_info->[0]};
12582: 		%name_to_ip  = %{$ip_info->[1]};
12583: 		%lonid_to_ip = %{$ip_info->[2]};
12584: 		return %iphost;
12585: 	    }
12586: 	}
12587: 
12588: 	# get yesterday's info for fallback
12589: 	my %old_name_to_ip;
12590: 	my ($ip_info,$cached)=
12591: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12592: 	if ($cached) {
12593: 	    %old_name_to_ip = %{$ip_info->[1]};
12594: 	}
12595: 
12596: 	my %name_to_host = &all_names();
12597: 	foreach my $name (keys(%name_to_host)) {
12598: 	    my $ip;
12599: 	    if (!exists($name_to_ip{$name})) {
12600: 		$ip = gethostbyname($name);
12601: 		if (!$ip || length($ip) ne 4) {
12602: 		    if (defined($old_name_to_ip{$name})) {
12603: 			$ip = $old_name_to_ip{$name};
12604: 			&logthis("Can't find $name defaulting to old $ip");
12605: 		    } else {
12606: 			&logthis("Name $name no IP found");
12607: 			next;
12608: 		    }
12609: 		} else {
12610: 		    $ip=inet_ntoa($ip);
12611: 		}
12612: 		$name_to_ip{$name} = $ip;
12613: 	    } else {
12614: 		$ip = $name_to_ip{$name};
12615: 	    }
12616: 	    foreach my $id (@{ $name_to_host{$name} }) {
12617: 		$lonid_to_ip{$id} = $ip;
12618: 	    }
12619: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12620: 	}
12621: 	&do_cache_new('iphost','iphost',
12622: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12623: 		      48*60*60);
12624: 
12625: 	return %iphost;
12626:     }
12627: 
12628:     #
12629:     #  Given a DNS returns the loncapa host name for that DNS 
12630:     # 
12631:     sub host_from_dns {
12632:         my ($dns) = @_;
12633:         my @hosts;
12634:         my $ip;
12635: 
12636:         if (exists($name_to_ip{$dns})) {
12637:             $ip = $name_to_ip{$dns};
12638:         }
12639:         if (!$ip) {
12640:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12641:             if (length($ip) == 4) { 
12642: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12643:             }
12644:         }
12645:         if ($ip) {
12646: 	    @hosts = get_hosts_from_ip($ip);
12647: 	    return $hosts[0];
12648:         }
12649:         return undef;
12650:     }
12651: 
12652:     sub get_internet_names {
12653:         my ($lonid) = @_;
12654:         return if ($lonid eq '');
12655:         my ($idnref,$cached)=
12656:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12657:         if ($cached) {
12658:             return $idnref;
12659:         }
12660:         my $ip = &get_host_ip($lonid);
12661:         my @hosts = &get_hosts_from_ip($ip);
12662:         my %iphost = &get_iphost();
12663:         my (@idns,%seen);
12664:         foreach my $id (@hosts) {
12665:             my $dom = &host_domain($id);
12666:             my $prim_id = &domain($dom,'primary');
12667:             my $prim_ip = &get_host_ip($prim_id);
12668:             next if ($seen{$prim_ip});
12669:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12670:                 foreach my $id (@{$iphost{$prim_ip}}) {
12671:                     my $intdom = &internet_dom($id);
12672:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12673:                         push(@idns,$intdom);
12674:                     }
12675:                 }
12676:             }
12677:             $seen{$prim_ip} = 1;
12678:         }
12679:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12680:     }
12681: 
12682: }
12683: 
12684: sub all_loncaparevs {
12685:     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);
12686: }
12687: 
12688: # ---------------------------------------------------------- Read loncaparev table
12689: {
12690:     sub load_loncaparevs { 
12691:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12692:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12693:                 while (my $configline=<$config>) {
12694:                     chomp($configline);
12695:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12696:                     $loncaparevs{$hostid}=$loncaparev;
12697:                 }
12698:                 close($config);
12699:             }
12700:         }
12701:     }
12702: }
12703: 
12704: # ---------------------------------------------------------- Read serverhostID table
12705: {
12706:     sub load_serverhomeIDs {
12707:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12708:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12709:                 while (my $configline=<$config>) {
12710:                     chomp($configline);
12711:                     my ($name,$id)=split(/:/,$configline);
12712:                     $serverhomeIDs{$name}=$id;
12713:                 }
12714:                 close($config);
12715:             }
12716:         }
12717:     }
12718: }
12719: 
12720: 
12721: BEGIN {
12722: 
12723: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12724:     unless ($readit) {
12725: {
12726:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12727:     %perlvar = (%perlvar,%{$configvars});
12728: }
12729: 
12730: 
12731: # ------------------------------------------------------ Read spare server file
12732: {
12733:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12734: 
12735:     while (my $configline=<$config>) {
12736:        chomp($configline);
12737:        if ($configline) {
12738: 	   my ($host,$type) = split(':',$configline,2);
12739: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12740: 	   push(@{ $spareid{$type} }, $host);
12741:        }
12742:     }
12743:     close($config);
12744: }
12745: # ------------------------------------------------------------ Read permissions
12746: {
12747:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12748: 
12749:     while (my $configline=<$config>) {
12750: 	chomp($configline);
12751: 	if ($configline) {
12752: 	    my ($role,$perm)=split(/ /,$configline);
12753: 	    if ($perm ne '') { $pr{$role}=$perm; }
12754: 	}
12755:     }
12756:     close($config);
12757: }
12758: 
12759: # -------------------------------------------- Read plain texts for permissions
12760: {
12761:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12762: 
12763:     while (my $configline=<$config>) {
12764: 	chomp($configline);
12765: 	if ($configline) {
12766: 	    my ($short,@plain)=split(/:/,$configline);
12767:             %{$prp{$short}} = ();
12768: 	    if (@plain > 0) {
12769:                 $prp{$short}{'std'} = $plain[0];
12770:                 for (my $i=1; $i<@plain; $i++) {
12771:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12772:                 }
12773:             }
12774: 	}
12775:     }
12776:     close($config);
12777: }
12778: 
12779: # ---------------------------------------------------------- Read package table
12780: {
12781:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12782: 
12783:     while (my $configline=<$config>) {
12784: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12785: 	chomp($configline);
12786: 	my ($short,$plain)=split(/:/,$configline);
12787: 	my ($pack,$name)=split(/\&/,$short);
12788: 	if ($plain ne '') {
12789: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12790: 	    $packagetab{$short}=$plain; 
12791: 	}
12792:     }
12793:     close($config);
12794: }
12795: 
12796: # ---------------------------------------------------------- Read loncaparev table
12797: 
12798: &load_loncaparevs();
12799: 
12800: # ---------------------------------------------------------- Read serverhostID table
12801: 
12802: &load_serverhomeIDs();
12803: 
12804: # ---------------------------------------------------------- Read releaseslist XML
12805: {
12806:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12807:     if (-e $file) {
12808:         my $parser = HTML::LCParser->new($file);
12809:         while (my $token = $parser->get_token()) {
12810:             if ($token->[0] eq 'S') {
12811:                 my $item = $token->[1];
12812:                 my $name = $token->[2]{'name'};
12813:                 my $value = $token->[2]{'value'};
12814:                 my $valuematch = $token->[2]{'valuematch'};
12815:                 if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
12816:                     my $release = $parser->get_text();
12817:                     $release =~ s/(^\s*|\s*$ )//gx;
12818:                     $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
12819:                 }
12820:             }
12821:         }
12822:     }
12823: }
12824: 
12825: # ---------------------------------------------------------- Read managers table
12826: {
12827:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12828:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12829:             while (my $configline=<$config>) {
12830:                 chomp($configline);
12831:                 next if ($configline =~ /^\#/);
12832:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12833:                     $managerstab{$configline} = 1;
12834:                 }
12835:             }
12836:             close($config);
12837:         }
12838:     }
12839: }
12840: 
12841: # ------------- set up temporary directory
12842: {
12843:     $tmpdir = LONCAPA::tempdir();
12844: 
12845: }
12846: 
12847: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12848: 				'compress_threshold'=> 20_000,
12849:  			        });
12850: 
12851: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12852: $dumpcount=0;
12853: $locknum=0;
12854: 
12855: &logtouch();
12856: &logthis('<font color="yellow">INFO: Read configuration</font>');
12857: $readit=1;
12858:     {
12859: 	use integer;
12860: 	my $test=(2**32)+1;
12861: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12862: 	&logthis(" Detected 64bit platform ($_64bit)");
12863:     }
12864: }
12865: }
12866: 
12867: 1;
12868: __END__
12869: 
12870: =pod
12871: 
12872: =head1 NAME
12873: 
12874: Apache::lonnet - Subroutines to ask questions about things in the network.
12875: 
12876: =head1 SYNOPSIS
12877: 
12878: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12879: 
12880:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12881: 
12882: Common parameters:
12883: 
12884: =over 4
12885: 
12886: =item *
12887: 
12888: $uname : an internal username (if $cname expecting a course Id specifically)
12889: 
12890: =item *
12891: 
12892: $udom : a domain (if $cdom expecting a course's domain specifically)
12893: 
12894: =item *
12895: 
12896: $symb : a resource instance identifier
12897: 
12898: =item *
12899: 
12900: $namespace : the name of a .db file that contains the data needed or
12901: being set.
12902: 
12903: =back
12904: 
12905: =head1 OVERVIEW
12906: 
12907: lonnet provides subroutines which interact with the
12908: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12909: about classes, users, and resources.
12910: 
12911: For many of these objects you can also use this to store data about
12912: them or modify them in various ways.
12913: 
12914: =head2 Symbs
12915: 
12916: To identify a specific instance of a resource, LON-CAPA uses symbols
12917: or "symbs"X<symb>. These identifiers are built from the URL of the
12918: map, the resource number of the resource in the map, and the URL of
12919: the resource itself. The latter is somewhat redundant, but might help
12920: if maps change.
12921: 
12922: An example is
12923: 
12924:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12925: 
12926: The respective map entry is
12927: 
12928:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12929:   title="Problem 2">
12930:  </resource>
12931: 
12932: Symbs are used by the random number generator, as well as to store and
12933: restore data specific to a certain instance of for example a problem.
12934: 
12935: =head2 Storing And Retrieving Data
12936: 
12937: X<store()>X<cstore()>X<restore()>Three of the most important functions
12938: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12939: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12940: is is the non-critical message twin of cstore. These functions are for
12941: handlers to store a perl hash to a user's permanent data space in an
12942: easy manner, and to retrieve it again on another call. It is expected
12943: that a handler would use this once at the beginning to retrieve data,
12944: and then again once at the end to send only the new data back.
12945: 
12946: The data is stored in the user's data directory on the user's
12947: homeserver under the ID of the course.
12948: 
12949: The hash that is returned by restore will have all of the previous
12950: value for all of the elements of the hash.
12951: 
12952: Example:
12953: 
12954:  #creating a hash
12955:  my %hash;
12956:  $hash{'foo'}='bar';
12957: 
12958:  #storing it
12959:  &Apache::lonnet::cstore(\%hash);
12960: 
12961:  #changing a value
12962:  $hash{'foo'}='notbar';
12963: 
12964:  #adding a new value
12965:  $hash{'bar'}='foo';
12966:  &Apache::lonnet::cstore(\%hash);
12967: 
12968:  #retrieving the hash
12969:  my %history=&Apache::lonnet::restore();
12970: 
12971:  #print the hash
12972:  foreach my $key (sort(keys(%history))) {
12973:    print("\%history{$key} = $history{$key}");
12974:  }
12975: 
12976: Will print out:
12977: 
12978:  %history{1:foo} = bar
12979:  %history{1:keys} = foo:timestamp
12980:  %history{1:timestamp} = 990455579
12981:  %history{2:bar} = foo
12982:  %history{2:foo} = notbar
12983:  %history{2:keys} = foo:bar:timestamp
12984:  %history{2:timestamp} = 990455580
12985:  %history{bar} = foo
12986:  %history{foo} = notbar
12987:  %history{timestamp} = 990455580
12988:  %history{version} = 2
12989: 
12990: Note that the special hash entries C<keys>, C<version> and
12991: C<timestamp> were added to the hash. C<version> will be equal to the
12992: total number of versions of the data that have been stored. The
12993: C<timestamp> attribute will be the UNIX time the hash was
12994: stored. C<keys> is available in every historical section to list which
12995: keys were added or changed at a specific historical revision of a
12996: hash.
12997: 
12998: B<Warning>: do not store the hash that restore returns directly. This
12999: will cause a mess since it will restore the historical keys as if the
13000: were new keys. I.E. 1:foo will become 1:1:foo etc.
13001: 
13002: Calling convention:
13003: 
13004:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
13005:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
13006: 
13007: For more detailed information, see lonnet specific documentation.
13008: 
13009: =head1 RETURN MESSAGES
13010: 
13011: =over 4
13012: 
13013: =item * B<con_lost>: unable to contact remote host
13014: 
13015: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13016: when the connection is brought back up
13017: 
13018: =item * B<con_failed>: unable to contact remote host and unable to save message
13019: for later delivery
13020: 
13021: =item * B<error:>: an error a occurred, a description of the error follows the :
13022: 
13023: =item * B<no_such_host>: unable to fund a host associated with the user/domain
13024: that was requested
13025: 
13026: =back
13027: 
13028: =head1 PUBLIC SUBROUTINES
13029: 
13030: =head2 Session Environment Functions
13031: 
13032: =over 4
13033: 
13034: =item * 
13035: X<appenv()>
13036: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
13037: the user envirnoment file, and will be restored for each access this
13038: user makes during this session, also modifies the %env for the current
13039: process. Optional rolesarrayref - if defined contains a reference to an array
13040: of roles which are exempt from the restriction on modifying user.role entries 
13041: in the user's environment.db and in %env.    
13042: 
13043: =item *
13044: X<delenv()>
13045: B<delenv($delthis,$regexp)>: removes all items from the session
13046: environment file that begin with $delthis. If the 
13047: optional second arg - $regexp - is true, $delthis is treated as a 
13048: regular expression, otherwise \Q$delthis\E is used. 
13049: The values are also deleted from the current processes %env.
13050: 
13051: =item * get_env_multiple($name) 
13052: 
13053: gets $name from the %env hash, it seemlessly handles the cases where multiple
13054: values may be defined and end up as an array ref.
13055: 
13056: returns an array of values
13057: 
13058: =back
13059: 
13060: =head2 User Information
13061: 
13062: =over 4
13063: 
13064: =item *
13065: X<queryauthenticate()>
13066: B<queryauthenticate($uname,$udom)>: try to determine user's current 
13067: authentication scheme
13068: 
13069: =item *
13070: X<authenticate()>
13071: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
13072: authenticate user from domain's lib servers (first use the current
13073: one). C<$upass> should be the users password.
13074: $checkdefauth is optional (value is 1 if a check should be made to
13075:    authenticate user using default authentication method, and allow
13076:    account creation if username does not have account in the domain).
13077: $clientcancheckhost is optional (value is 1 if checking whether the
13078:    server can host will occur on the client side in lonauth.pm).   
13079: 
13080: =item *
13081: X<homeserver()>
13082: B<homeserver($uname,$udom)>: find the server which has
13083: the user's directory and files (there must be only one), this caches
13084: the answer, and also caches if there is a borken connection.
13085: 
13086: =item *
13087: X<idget()>
13088: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13089: (IDs are a unique resource in a domain, there must be only 1 ID per
13090: username, and only 1 username per ID in a specific domain) (returns
13091: hash: id=>name,id=>name)
13092: 
13093: =item *
13094: X<idrget()>
13095: B<idrget($udom,@unames)>: find the IDs behind a list of
13096: usernames (returns hash: name=>id,name=>id)
13097: 
13098: =item *
13099: X<idput()>
13100: B<idput($udom,%ids)>: store away a list of names and associated IDs
13101: 
13102: =item *
13103: X<rolesinit()>
13104: B<rolesinit($udom,$username)>: get user privileges.
13105: returns user role, first access and timer interval hashes
13106: 
13107: =item *
13108: X<privileged()>
13109: B<privileged($username,$domain)>: returns a true if user has a
13110: privileged and active role (i.e. su or dc), false otherwise.
13111: 
13112: =item *
13113: X<getsection()>
13114: B<getsection($udom,$uname,$cname)>: finds the section of student in the
13115: course $cname, return section name/number or '' for "not in course"
13116: and '-1' for "no section"
13117: 
13118: =item *
13119: X<userenvironment()>
13120: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
13121: passed in @what from the requested user's environment, returns a hash
13122: 
13123: =item * 
13124: X<userlog_query()>
13125: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13126: activity.log file. %filters defines filters applied when parsing the
13127: log file. These can be start or end timestamps, or the type of action
13128: - log to look for Login or Logout events, check for Checkin or
13129: Checkout, role for role selection. The response is in the form
13130: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
13131: escaped strings of the action recorded in the activity.log file.
13132: 
13133: =back
13134: 
13135: =head2 User Roles
13136: 
13137: =over 4
13138: 
13139: =item *
13140: 
13141: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
13142: returns codes for allowed actions.
13143: 
13144: The first argument is required, all others are optional.
13145: 
13146: $priv is the privilege being checked.
13147: $uri contains additional information about what is being checked for access (e.g.,
13148: URL, course ID etc.). 
13149: $symb is the unique resource instance identifier in a course; if needed,
13150: but not provided, it will be retrieved via a call to &symbread(). 
13151: $role is the role for which a priv is being checked (only used if priv is evb). 
13152: $clientip is the user's IP address (only used when checking for access to portfolio 
13153: files).
13154: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
13155: prevents recursive calls to &allowed.
13156: 
13157:  F: full access
13158:  U,I,K: authentication modes (cxx only)
13159:  '': forbidden
13160:  1: user needs to choose course
13161:  2: browse allowed
13162:  A: passphrase authentication needed
13163:  B: access temporarily blocked because of a blocking event in a course.
13164: 
13165: =item *
13166: 
13167: constructaccess($url,$setpriv) : check for access to construction space URL
13168: 
13169: See if the owner domain and name in the URL match those in the
13170: expected environment.  If so, return three element list
13171: ($ownername,$ownerdomain,$ownerhome).
13172: 
13173: Otherwise return the null string.
13174: 
13175: If second argument 'setpriv' is true, it assigns the privileges,
13176: and returns the same three element list, unless the owner has
13177: blocked "ad hoc" Domain Coordinator access to the Author Space,
13178: in which case the null string is returned.
13179: 
13180: =item *
13181: 
13182: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13183: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13184: and course level
13185: 
13186: =item *
13187: 
13188: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
13189: (rolesplain.tab); plain text explanation of a user role term.
13190: $type is Course (default) or Community.
13191: If $forcedefault evaluates to true, text returned will be default 
13192: text for $type. Otherwise, if this is a course, the text returned 
13193: will be a custom name for the role (if defined in the course's 
13194: environment).  If no custom name is defined the default is returned.
13195:    
13196: =item *
13197: 
13198: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
13199: All arguments are optional. Returns a hash of a roles, either for
13200: co-author/assistant author roles for a user's Construction Space
13201: (default), or if $context is 'userroles', roles for the user himself,
13202: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13203: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13204: For each key, value is set to colon-separated start and end times for
13205: the role.  If no username and domain are specified, will default to
13206: current user/domain. Types, roles, and roledoms are references to arrays
13207: of role statuses (active, future or previous), roles 
13208: (e.g., cc,in, st etc.) and domains of the roles which can be used
13209: to restrict the list of roles reported. If no array ref is 
13210: provided for types, will default to return only active roles.
13211: 
13212: =item *
13213: 
13214: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13215: user: $uname:$udom has a role in the course: $cdom_$cnum. 
13216: 
13217: Additional optional arguments are: $type (if role checking is to be restricted 
13218: to certain user status types -- previous (expired roles), active (currently
13219: available roles) or future (roles available in the future), and
13220: $hideprivileged -- if true will not report course roles for users who
13221: have active Domain Coordinator role in course's domain or in additional
13222: domains (specified in 'Domains to check for privileged users' in course
13223: environment -- set via:  Course Settings -> Classlists and staff listing).
13224: 
13225: =item *
13226: 
13227: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13228: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13229: $possdomains and $possroles are optional array refs -- to domains to check and
13230: roles to check.  If $possdomains is not specified, a dump will be done of the
13231: users' roles.db to check for a dc or su role in any domain. This can be
13232: time consuming if &privileged is called repeatedly (e.g., when displaying a
13233: classlist), so in such cases, supplying a $possdomains array is preferred, as
13234: this then allows &privileged_by_domain() to be used, which caches the identity
13235: of privileged users, eliminating the need for repeated calls to &dump().
13236: 
13237: =item *
13238: 
13239: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13240: where the outer hash keys are domains specified in the $possdomains array ref,
13241: next inner hash keys are privileged roles specified in the $roles array ref,
13242: and the innermost hash contains key = value pairs for username:domain = end:start
13243: for active or future "privileged" users with that role in that domain. To avoid
13244: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13245: innerhash are cached using priv_$role and $dom as the identifiers.
13246: 
13247: =back
13248: 
13249: =head2 User Modification
13250: 
13251: =over 4
13252: 
13253: =item *
13254: 
13255: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13256: user for the level given by URL.  Optional start and end dates (leave empty
13257: string or zero for "no date")
13258: 
13259: =item *
13260: 
13261: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13262: change a users, password, possible return values are: ok,
13263: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13264: refused
13265: 
13266: =item *
13267: 
13268: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13269: 
13270: =item *
13271: 
13272: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13273:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13274: 
13275: will update user information (firstname,middlename,lastname,generation,
13276: permanentemail), and if forceid is true, student/employee ID also.
13277: A user's institutional affiliation(s) can also be updated.
13278: User information fields will not be overwritten with empty entries 
13279: unless the field is included in the $candelete array reference.
13280: This array is included when a single user is modified via "Manage Users",
13281: or when Autoupdate.pl is run by cron in a domain.
13282: 
13283: =item *
13284: 
13285: modifystudent
13286: 
13287: modify a student's enrollment and identification information.
13288: The course id is resolved based on the current user's environment.  
13289: This means the invoking user must be a course coordinator or otherwise
13290: associated with a course.
13291: 
13292: This call is essentially a wrapper for lonnet::modifyuser and
13293: lonnet::modify_student_enrollment
13294: 
13295: Inputs: 
13296: 
13297: =over 4
13298: 
13299: =item B<$udom> Student's loncapa domain
13300: 
13301: =item B<$uname> Student's loncapa login name
13302: 
13303: =item B<$uid> Student/Employee ID
13304: 
13305: =item B<$umode> Student's authentication mode
13306: 
13307: =item B<$upass> Student's password
13308: 
13309: =item B<$first> Student's first name
13310: 
13311: =item B<$middle> Student's middle name
13312: 
13313: =item B<$last> Student's last name
13314: 
13315: =item B<$gene> Student's generation
13316: 
13317: =item B<$usec> Student's section in course
13318: 
13319: =item B<$end> Unix time of the roles expiration
13320: 
13321: =item B<$start> Unix time of the roles start date
13322: 
13323: =item B<$forceid> If defined, allow $uid to be changed
13324: 
13325: =item B<$desiredhome> server to use as home server for student
13326: 
13327: =item B<$email> Student's permanent e-mail address
13328: 
13329: =item B<$type> Type of enrollment (auto or manual)
13330: 
13331: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13332: 
13333: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13334: 
13335: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13336: 
13337: =item B<$context> role change context (shown in User Management Logs display in a course)
13338: 
13339: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13340: 
13341: =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.
13342: 
13343: =back
13344: 
13345: =item *
13346: 
13347: modify_student_enrollment
13348: 
13349: Change a student's enrollment status in a class.  The environment variable
13350: 'role.request.course' must be defined for this function to proceed.
13351: 
13352: Inputs:
13353: 
13354: =over 4
13355: 
13356: =item $udom, student's domain
13357: 
13358: =item $uname, student's name
13359: 
13360: =item $uid, student's user id
13361: 
13362: =item $first, student's first name
13363: 
13364: =item $middle
13365: 
13366: =item $last
13367: 
13368: =item $gene
13369: 
13370: =item $usec
13371: 
13372: =item $end
13373: 
13374: =item $start
13375: 
13376: =item $type
13377: 
13378: =item $locktype
13379: 
13380: =item $cid
13381: 
13382: =item $selfenroll
13383: 
13384: =item $context
13385: 
13386: =item $credits, number of credits student will earn from this class
13387: 
13388: =back
13389: 
13390: 
13391: =item *
13392: 
13393: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13394: custom role; give a custom role to a user for the level given by URL.  Specify
13395: name and domain of role author, and role name
13396: 
13397: =item *
13398: 
13399: revokerole($udom,$uname,$url,$role) : revoke a role for url
13400: 
13401: =item *
13402: 
13403: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13404: 
13405: =back
13406: 
13407: =head2 Course Infomation
13408: 
13409: =over 4
13410: 
13411: =item *
13412: 
13413: coursedescription($courseid,$options) : returns a hash of information about the
13414: specified course id, including all environment settings for the
13415: course, the description of the course will be in the hash under the
13416: key 'description'
13417: 
13418: $options is an optional parameter that if supplied is a hash reference that controls
13419: what how this function works.  It has the following key/values:
13420: 
13421: =over 4
13422: 
13423: =item freshen_cache
13424: 
13425: If defined, and the environment cache for the course is valid, it is 
13426: returned in the returned hash.
13427: 
13428: =item one_time
13429: 
13430: If defined, the last cache time is set to _now_
13431: 
13432: =item user
13433: 
13434: If defined, the supplied username is used instead of the current user.
13435: 
13436: 
13437: =back
13438: 
13439: =item *
13440: 
13441: resdata($name,$domain,$type,@which) : request for current parameter
13442: setting for a specific $type, where $type is either 'course' or 'user',
13443: @what should be a list of parameters to ask about. This routine caches
13444: answers for 10 minutes.
13445: 
13446: =item *
13447: 
13448: get_courseresdata($courseid, $domain) : dump the entire course resource
13449: data base, returning a hash that is keyed by the resource name and has
13450: values that are the resource value.  I believe that the timestamps and
13451: versions are also returned.
13452: 
13453: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13454: supplemental content area. This routine caches the number of files for 
13455: 10 minutes.
13456: 
13457: =back
13458: 
13459: =head2 Course Modification
13460: 
13461: =over 4
13462: 
13463: =item *
13464: 
13465: writecoursepref($courseid,%prefs) : write preferences (environment
13466: database) for a course
13467: 
13468: =item *
13469: 
13470: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13471: 
13472: =item *
13473: 
13474: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13475: 
13476: =item *
13477: 
13478: is_course($courseid), is_course($cdom, $cnum)
13479: 
13480: Accepts either a combined $courseid (in the form of domain_courseid) or the
13481: two component version $cdom, $cnum. It checks if the specified course exists.
13482: 
13483: Returns:
13484:     undef if the course doesn't exist, otherwise
13485:     in scalar context the combined courseid.
13486:     in list context the two components of the course identifier, domain and 
13487:     courseid.    
13488: 
13489: =back
13490: 
13491: =head2 Resource Subroutines
13492: 
13493: =over 4
13494: 
13495: =item *
13496: 
13497: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13498: 
13499: =item *
13500: 
13501: repcopy($filename) : subscribes to the requested file, and attempts to
13502: replicate from the owning library server, Might return
13503: 'unavailable', 'not_found', 'forbidden', 'ok', or
13504: 'bad_request', also attempts to grab the metadata for the
13505: resource. Expects the local filesystem pathname
13506: (/home/httpd/html/res/....)
13507: 
13508: =back
13509: 
13510: =head2 Resource Information
13511: 
13512: =over 4
13513: 
13514: =item *
13515: 
13516: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13517: and returns the value of a variety of different possible values,
13518: $varname should be a request string, and the other parameters can be
13519: used to specify who and what one is asking about. Ordinarily, $cid 
13520: does not need to be specified, as it is retrived from 
13521: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13522: within lonuserstate::loadmap() when initializing a course, before
13523: $env{'request.course.id'} has been set, so it needs to be provided
13524: in that one case.
13525: 
13526: Possible values for $varname are environment.lastname (or other item
13527: from the envirnment hash), user.name (or someother aspect about the
13528: user), resource.0.maxtries (or some other part and parameter of a
13529: resource)
13530: 
13531: =item *
13532: 
13533: directcondval($number) : get current value of a condition; reads from a state
13534: string
13535: 
13536: =item *
13537: 
13538: condval($condidx) : value of condition index based on state
13539: 
13540: =item *
13541: 
13542: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13543: resource's metadata, $what should be either a specific key, or either
13544: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13545: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13546: 
13547: this function automatically caches all requests
13548: 
13549: =item *
13550: 
13551: metadata_query($query,$custom,$customshow) : make a metadata query against the
13552: network of library servers; returns file handle of where SQL and regex results
13553: will be stored for query
13554: 
13555: =item *
13556: 
13557: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
13558: return symbolic list entry (all arguments optional). 
13559: 
13560: Args: filename is the filename (including path) for the file for which a symb 
13561: is required; donotrecurse, if true will prevent calls to allowed() being made 
13562: to check access status if more than one resource was found in the bighash 
13563: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
13564: a randompick); ignorecachednull, if true will prevent a symb of '' being 
13565: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13566: cause possible symbs to be checked to determine if they are subject to content
13567: blocking, if so they will not be included as possible symbs; possibles is a
13568: ref to a hash, which, as a side effect, will be populated with all possible 
13569: symbs (content blocking not tested).
13570:  
13571: returns the data handle
13572: 
13573: =item *
13574: 
13575: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13576: and is a possible symb for the URL in $thisfn, and if is an encrypted
13577: resource that the user accessed using /enc/ returns a 1 on success, 0
13578: on failure, user must be in a course, as it assumes the existence of
13579: the course initial hash, and uses $env('request.course.id'}.  The third
13580: arg is an optional reference to a scalar.  If this arg is passed in the 
13581: call to symbverify, it will be set to 1 if the symb has been set to be 
13582: encrypted; otherwise it will be null.  
13583: 
13584: =item *
13585: 
13586: symbclean($symb) : removes versions numbers from a symb, returns the
13587: cleaned symb
13588: 
13589: =item *
13590: 
13591: is_on_map($uri) : checks if the $uri is somewhere on the current
13592: course map, user must be in a course for it to work.
13593: 
13594: =item *
13595: 
13596: numval($salt) : return random seed value (addend for rndseed)
13597: 
13598: =item *
13599: 
13600: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13601: a random seed, all arguments are optional, if they aren't sent it uses the
13602: environment to derive them. Note: if symb isn't sent and it can't get one
13603: from &symbread it will use the current time as its return value
13604: 
13605: =item *
13606: 
13607: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13608: unfakeable, receipt
13609: 
13610: =item *
13611: 
13612: receipt() : API to ireceipt working off of env values; given out to users
13613: 
13614: =item *
13615: 
13616: countacc($url) : count the number of accesses to a given URL
13617: 
13618: =item *
13619: 
13620: 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
13621: 
13622: =item *
13623: 
13624: 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)
13625: 
13626: =item *
13627: 
13628: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13629: 
13630: =item *
13631: 
13632: devalidate($symb) : devalidate temporary spreadsheet calculations,
13633: forcing spreadsheet to reevaluate the resource scores next time.
13634: 
13635: =item * 
13636: 
13637: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13638: when viewing in course context.
13639: 
13640:  input: six args -- filename (decluttered), course number, course domain,
13641:                     url, symb (if registered) and group (if this is a 
13642:                     group item -- e.g., bulletin board, group page etc.).
13643: 
13644:  output: array of five scalars --
13645:          $cfile -- url for file editing if editable on current server
13646:          $home -- homeserver of resource (i.e., for author if published,
13647:                                           or course if uploaded.).
13648:          $switchserver --  1 if server switch will be needed.
13649:          $forceedit -- 1 if icon/link should be to go to edit mode 
13650:          $forceview -- 1 if icon/link should be to go to view mode
13651: 
13652: =item *
13653: 
13654: is_course_upload($file,$cnum,$cdom)
13655: 
13656: Used in course context to determine if current file was uploaded to 
13657: the course (i.e., would be found in /userfiles/docs on the course's 
13658: homeserver.
13659: 
13660:   input: 3 args -- filename (decluttered), course number and course domain.
13661:   output: boolean -- 1 if file was uploaded.
13662: 
13663: =back
13664: 
13665: =head2 Storing/Retreiving Data
13666: 
13667: =over 4
13668: 
13669: =item *
13670: 
13671: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13672: permanently for this url; hashref needs to be given and should be a \%hashname;
13673: the remaining args aren't required and if they aren't passed or are '' they will
13674: be derived from the env (with the exception of $laststore, which is an 
13675: optional arg used when a user's submission is stored in grading).
13676: $laststore is $version=$timestamp, where $version is the most recent version
13677: number retrieved for the corresponding $symb in the $namespace db file, and
13678: $timestamp is the timestamp for that transaction (UNIX time).
13679: $laststore is currently only passed when cstore() is called by 
13680: structuretags::finalize_storage().
13681: 
13682: =item *
13683: 
13684: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13685: but uses critical subroutine
13686: 
13687: =item *
13688: 
13689: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13690: all args are optional
13691: 
13692: =item *
13693: 
13694: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13695: dumps the complete (or key matching regexp) namespace into a hash
13696: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13697: normally &store()ed into
13698: 
13699: $range should be either an integer '100' (give me the first 100
13700:                                            matching records)
13701:               or be  two integers sperated by a - with no spaces
13702:                  '30-50' (give me the 30th through the 50th matching
13703:                           records)
13704: 
13705: 
13706: =item *
13707: 
13708: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13709: replaces a &store() version of data with a replacement set of data
13710: for a particular resource in a namespace passed in the $storehash hash 
13711: reference. If $tolog is true, the transaction is logged in the courselog
13712: with an action=PUTSTORE.
13713: 
13714: =item *
13715: 
13716: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13717: works very similar to store/cstore, but all data is stored in a
13718: temporary location and can be reset using tmpreset, $storehash should
13719: be a hash reference, returns nothing on success
13720: 
13721: =item *
13722: 
13723: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13724: similar to restore, but all data is stored in a temporary location and
13725: can be reset using tmpreset. Returns a hash of values on success,
13726: error string otherwise.
13727: 
13728: =item *
13729: 
13730: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13731: deltes all keys for $symb form the temporary storage hash.
13732: 
13733: =item *
13734: 
13735: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13736: reference filled in from namesp ($udom and $uname are optional)
13737: 
13738: =item *
13739: 
13740: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13741: namesp ($udom and $uname are optional)
13742: 
13743: =item *
13744: 
13745: dump($namespace,$udom,$uname,$regexp,$range) : 
13746: dumps the complete (or key matching regexp) namespace into a hash
13747: ($udom, $uname, $regexp, $range are optional)
13748: 
13749: $range should be either an integer '100' (give me the first 100
13750:                                            matching records)
13751:               or be  two integers sperated by a - with no spaces
13752:                  '30-50' (give me the 30th through the 50th matching
13753:                           records)
13754: =item *
13755: 
13756: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13757: $store can be a scalar, an array reference, or if the amount to be 
13758: incremented is > 1, a hash reference.
13759: 
13760: ($udom and $uname are optional)
13761: 
13762: =item *
13763: 
13764: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13765: ($udom and $uname are optional)
13766: 
13767: =item *
13768: 
13769: cput($namespace,$storehash,$udom,$uname) : critical put
13770: ($udom and $uname are optional)
13771: 
13772: =item *
13773: 
13774: newput($namespace,$storehash,$udom,$uname) :
13775: 
13776: Attempts to store the items in the $storehash, but only if they don't
13777: currently exist, if this succeeds you can be certain that you have 
13778: successfully created a new key value pair in the $namespace db.
13779: 
13780: 
13781: Args:
13782:  $namespace: name of database to store values to
13783:  $storehash: hashref to store to the db
13784:  $udom: (optional) domain of user containing the db
13785:  $uname: (optional) name of user caontaining the db
13786: 
13787: Returns:
13788:  'ok' -> succeeded in storing all keys of $storehash
13789:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13790:                         least <key> already existed in the db (other
13791:                         requested keys may also already exist)
13792:  'error: <msg>' -> unable to tie the DB or other error occurred
13793:  'con_lost' -> unable to contact request server
13794:  'refused' -> action was not allowed by remote machine
13795: 
13796: 
13797: =item *
13798: 
13799: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13800: reference filled in from namesp (encrypts the return communication)
13801: ($udom and $uname are optional)
13802: 
13803: =item *
13804: 
13805: log($udom,$name,$home,$message) : write to permanent log for user; use
13806: critical subroutine
13807: 
13808: =item *
13809: 
13810: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13811: array reference filled in from namespace found in domain level on either
13812: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13813: 
13814: =item *
13815: 
13816: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13817: domain level either on specified domain server ($uhome) or primary domain 
13818: server ($udom and $uhome are optional)
13819: 
13820: =item * 
13821: 
13822: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13823: for: authentication, language, quotas, timezone, date locale, and portal URL in
13824: the target domain.
13825: 
13826: May also include additional key => value pairs for the following groups:
13827: 
13828: =over
13829: 
13830: =item
13831: disk quotas (MB allocated by default to portfolios and authoring spaces).
13832: 
13833: =over
13834: 
13835: =item defaultquota, authorquota
13836: 
13837: =back
13838: 
13839: =item
13840: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13841: portfolio for users).
13842: 
13843: =over
13844: 
13845: =item
13846: aboutme, blog, webdav, portfolio
13847: 
13848: =back
13849: 
13850: =item
13851: requestcourses: ability to request courses, and how requests are processed.
13852: 
13853: =over
13854: 
13855: =item
13856: official, unofficial, community, textbook
13857: 
13858: =back
13859: 
13860: =item
13861: inststatus: types of institutional affiliation, and order in which they are displayed.
13862: 
13863: =over
13864: 
13865: =item
13866: inststatustypes, inststatusorder, inststatusguest
13867: 
13868: =back
13869: 
13870: =item
13871: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13872: for course's uploaded content.
13873: 
13874: =over
13875: 
13876: =item
13877: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13878: communityquota, textbookquota
13879: 
13880: =back
13881: 
13882: =item
13883: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13884: on your servers.
13885: 
13886: =over
13887: 
13888: =item 
13889: remotesessions, hostedsessions
13890: 
13891: =back
13892: 
13893: =back
13894: 
13895: In cases where a domain coordinator has never used the "Set Domain Configuration"
13896: utility to create a configuration.db file on a domain's primary library server 
13897: only the following domain defaults: auth_def, auth_arg_def, lang_def
13898: -- corresponding values are authentication type (internal, krb4, krb5,
13899: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13900: will be available. Values are retrieved from cache (if current), unless the
13901: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13902: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13903: 
13904: Typical usage:
13905: 
13906: %domdefaults = &get_domain_defaults($target_domain);
13907: 
13908: =back
13909: 
13910: =head2 Network Status Functions
13911: 
13912: =over 4
13913: 
13914: =item *
13915: 
13916: dirlist() : return directory list based on URI (first arg).
13917: 
13918: Inputs: 1 required, 5 optional.
13919: 
13920: =over
13921: 
13922: =item 
13923: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13924: 
13925: =item
13926: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13927: 
13928: =item
13929: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13930: 
13931: =item
13932: $getpropath - boolean: 1 if prepend path using &propath(). 
13933: 
13934: =item
13935: $getuserdir - boolean: 1 if prepend path for "userfiles".
13936: 
13937: =item 
13938: $alternateRoot - path to prepend in place of path from $uri.
13939: 
13940: =back
13941: 
13942: Returns: Array of up to two items.
13943: 
13944: =over
13945: 
13946: a reference to an array of files/subdirectories
13947: 
13948: =over
13949: 
13950: Each element in the array of files/subdirectories is a & separated list of
13951: item name and the result of running stat on the item.  If dirlist was requested
13952: for a file instead of a directory, the item name will be ''. For a directory 
13953: listing, if the item is a metadata file, the element will end &N&M 
13954: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13955: default copyright set (1).  
13956: 
13957: =back
13958: 
13959: a scalar containing error condition (if encountered).
13960: 
13961: =over
13962: 
13963: =item 
13964: no_host (no homeserver identified for $username:$domain).
13965: 
13966: =item 
13967: no_such_host (server contacted for listing not identified as valid host).
13968: 
13969: =item 
13970: con_lost (connection to remote server failed).
13971: 
13972: =item 
13973: refused (invalid $username:$domain received on lond side).
13974: 
13975: =item 
13976: no_such_dir (directory at specified path on lond side does not exist). 
13977: 
13978: =item 
13979: empty (directory at specified path on lond side is empty).
13980: 
13981: =over
13982: 
13983: This is currently not encountered because the &ls3, &ls2, 
13984: &ls (_handler) routines on the lond side do not filter out
13985: . and .. from a directory listing. 
13986: 
13987: =back
13988: 
13989: =back
13990: 
13991: =back
13992: 
13993: =item *
13994: 
13995: spareserver() : find server with least workload from spare.tab
13996: 
13997: 
13998: =item *
13999: 
14000: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14001: if there is no corresponding loncapa host.
14002: 
14003: =back
14004: 
14005: 
14006: =head2 Apache Request
14007: 
14008: =over 4
14009: 
14010: =item *
14011: 
14012: ssi($url,%hash) : server side include, does a complete request cycle on url to
14013: localhost, posts hash
14014: 
14015: =back
14016: 
14017: =head2 Data to String to Data
14018: 
14019: =over 4
14020: 
14021: =item *
14022: 
14023: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14024: and '&' separators, supports elements that are arrayrefs and hashrefs
14025: 
14026: =item *
14027: 
14028: hashref2str($hashref) : convert a hashref into a string complete with
14029: escaping and '=' and '&' separators, supports elements that are
14030: arrayrefs and hashrefs
14031: 
14032: =item *
14033: 
14034: arrayref2str($arrayref) : convert an arrayref into a string complete
14035: with escaping and '&' separators, supports elements that are arrayrefs
14036: and hashrefs
14037: 
14038: =item *
14039: 
14040: str2hash($string) : convert string to hash using unescaping and
14041: splitting on '=' and '&', supports elements that are arrayrefs and
14042: hashrefs
14043: 
14044: =item *
14045: 
14046: str2array($string) : convert string to hash using unescaping and
14047: splitting on '&', supports elements that are arrayrefs and hashrefs
14048: 
14049: =back
14050: 
14051: =head2 Logging Routines
14052: 
14053: 
14054: These routines allow one to make log messages in the lonnet.log and
14055: lonnet.perm logfiles.
14056: 
14057: =over 4
14058: 
14059: =item *
14060: 
14061: logtouch() : make sure the logfile, lonnet.log, exists
14062: 
14063: =item *
14064: 
14065: logthis() : append message to the normal lonnet.log file, it gets
14066: preiodically rolled over and deleted.
14067: 
14068: =item *
14069: 
14070: logperm() : append a permanent message to lonnet.perm.log, this log
14071: file never gets deleted by any automated portion of the system, only
14072: messages of critical importance should go in here.
14073: 
14074: 
14075: =back
14076: 
14077: =head2 General File Helper Routines
14078: 
14079: =over 4
14080: 
14081: =item *
14082: 
14083: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14084: (a) files in /uploaded
14085:   (i) If a local copy of the file exists - 
14086:       compares modification date of local copy with last-modified date for 
14087:       definitive version stored on home server for course. If local copy is 
14088:       stale, requests a new version from the home server and stores it. 
14089:       If the original has been removed from the home server, then local copy 
14090:       is unlinked.
14091:   (ii) If local copy does not exist -
14092:       requests the file from the home server and stores it. 
14093:   
14094:   If $caller is 'uploadrep':  
14095:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14096:     for request for files originally uploaded via DOCS. 
14097:      - returns 'ok' if fresh local copy now available, -1 otherwise.
14098:   
14099:   Otherwise:
14100:      This indicates a call from the content generation phase of the request.
14101:      -  returns the entire contents of the file or -1.
14102:      
14103: (b) files in /res
14104:    - returns the entire contents of a file or -1; 
14105:    it properly subscribes to and replicates the file if neccessary.
14106: 
14107: 
14108: =item *
14109: 
14110: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14111:                   reference
14112: 
14113: returns either a stat() list of data about the file or an empty list
14114: if the file doesn't exist or couldn't find out about it (connection
14115: problems or user unknown)
14116: 
14117: =item *
14118: 
14119: filelocation($dir,$file) : returns file system location of a file
14120: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14121: directory that relative $file lookups are to looked in ($dir of /a/dir
14122: and a file of ../bob will become /a/bob)
14123: 
14124: =item *
14125: 
14126: hreflocation($dir,$file) : returns file system location or a URL; same as
14127: filelocation except for hrefs
14128: 
14129: =item *
14130: 
14131: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14132: also removes beginning /home/httpd/html unless /priv/ follows it.
14133: 
14134: =back
14135: 
14136: =head2 Usererfile file routines (/uploaded*)
14137: 
14138: =over 4
14139: 
14140: =item *
14141: 
14142: userfileupload(): main rotine for putting a file in a user or course's
14143:                   filespace, arguments are,
14144: 
14145:  formname - required - this is the name of the element in $env where the
14146:            filename, and the contents of the file to create/modifed exist
14147:            the filename is in $env{'form.'.$formname.'.filename'} and the
14148:            contents of the file is located in $env{'form.'.$formname}
14149:  context - if coursedoc, store the file in the course of the active role
14150:              of the current user; 
14151:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14152:            if 'canceloverwrite': delete file in tmp/overwrites directory
14153:  subdir - required - subdirectory to put the file in under ../userfiles/
14154:          if undefined, it will be placed in "unknown"
14155: 
14156:  (This routine calls clean_filename() to remove any dangerous
14157:  characters from the filename, and then calls finuserfileupload() to
14158:  complete the transaction)
14159: 
14160:  returns either the url of the uploaded file (/uploaded/....) if successful
14161:  and /adm/notfound.html if unsuccessful
14162: 
14163: =item *
14164: 
14165: clean_filename(): routine for cleaing a filename up for storage in
14166:                  userfile space, argument is:
14167: 
14168:  filename - proposed filename
14169: 
14170: returns: the new clean filename
14171: 
14172: =item *
14173: 
14174: finishuserfileupload(): routine that creates and sends the file to
14175: userspace, probably shouldn't be called directly
14176: 
14177:   docuname: username or courseid of destination for the file
14178:   docudom: domain of user/course of destination for the file
14179:   formname: same as for userfileupload()
14180:   fname: filename (including subdirectories) for the file
14181:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14182:   allfiles: reference to hash used to store objects found by parser
14183:   codebase: reference to hash used for codebases of java objects found by parser
14184:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14185:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
14186:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
14187:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
14188:   context: if 'overwrite', will move the uploaded file from its temporary location to
14189:             userfiles to facilitate overwriting a previously uploaded file with same name.
14190:   mimetype: reference to scalar to accommodate mime type determined
14191:             from File::MMagic if $parser = parse.
14192: 
14193:  returns either the url of the uploaded file (/uploaded/....) if successful
14194:  and /adm/notfound.html if unsuccessful (or an error message if context 
14195:  was 'overwrite').
14196:  
14197: 
14198: =item *
14199: 
14200: renameuserfile(): renames an existing userfile to a new name
14201: 
14202:   Args:
14203:    docuname: username or courseid of destination for the file
14204:    docudom: domain of user/course of destination for the file
14205:    old: current file name (including any subdirs under userfiles)
14206:    new: desired file name (including any subdirs under userfiles)
14207: 
14208: =item *
14209: 
14210: mkdiruserfile(): creates a directory is a userfiles dir
14211: 
14212:   Args:
14213:    docuname: username or courseid of destination for the file
14214:    docudom: domain of user/course of destination for the file
14215:    dir: dir to create (including any subdirs under userfiles)
14216: 
14217: =item *
14218: 
14219: removeuserfile(): removes a file that exists in userfiles
14220: 
14221:   Args:
14222:    docuname: username or courseid of destination for the file
14223:    docudom: domain of user/course of destination for the file
14224:    fname: filname to delete (including any subdirs under userfiles)
14225: 
14226: =item *
14227: 
14228: removeuploadedurl(): convience function for removeuserfile()
14229: 
14230:   Args:
14231:    url:  a full /uploaded/... url to delete
14232: 
14233: =item * 
14234: 
14235: get_portfile_permissions():
14236:   Args:
14237:     domain: domain of user or course contain the portfolio files
14238:     user: name of user or num of course contain the portfolio files
14239:   Returns:
14240:     hashref of a dump of the proper file_permissions.db
14241:    
14242: 
14243: =item * 
14244: 
14245: get_access_controls():
14246: 
14247: Args:
14248:   current_permissions: the hash ref returned from get_portfile_permissions()
14249:   group: (optional) the group you want the files associated with
14250:   file: (optional) the file you want access info on
14251: 
14252: Returns:
14253:     a hash (keys are file names) of hashes containing
14254:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14255:         values are XML containing access control settings (see below) 
14256: 
14257: Internal notes:
14258: 
14259:  access controls are stored in file_permissions.db as key=value pairs.
14260:     key -> path to file/file_name\0uniqueID:scope_end_start
14261:         where scope -> public,guest,course,group,domains or users.
14262:               end -> UNIX time for end of access (0 -> no end date)
14263:               start -> UNIX time for start of access
14264: 
14265:     value -> XML description of access control
14266:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14267:             <start></start>
14268:             <end></end>
14269: 
14270:             <password></password>  for scope type = guest
14271: 
14272:             <domain></domain>     for scope type = course or group
14273:             <number></number>
14274:             <roles id="">
14275:              <role></role>
14276:              <access></access>
14277:              <section></section>
14278:              <group></group>
14279:             </roles>
14280: 
14281:             <dom></dom>         for scope type = domains
14282: 
14283:             <users>             for scope type = users
14284:              <user>
14285:               <uname></uname>
14286:               <udom></udom>
14287:              </user>
14288:             </users>
14289:            </scope> 
14290:               
14291:  Access data is also aggregated for each file in an additional key=value pair:
14292:  key -> path to file/file_name\0accesscontrol 
14293:  value -> reference to hash
14294:           hash contains key = value pairs
14295:           where key = uniqueID:scope_end_start
14296:                 value = UNIX time record was last updated
14297: 
14298:           Used to improve speed of look-ups of access controls for each file.  
14299:  
14300:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14301: 
14302: =item *
14303: 
14304: modify_access_controls():
14305: 
14306: Modifies access controls for a portfolio file
14307: Args
14308: 1. file name
14309: 2. reference to hash of required changes,
14310: 3. domain
14311: 4. username
14312:   where domain,username are the domain of the portfolio owner 
14313:   (either a user or a course) 
14314: 
14315: Returns:
14316: 1. result of additions or updates ('ok' or 'error', with error message). 
14317: 2. result of deletions ('ok' or 'error', with error message).
14318: 3. reference to hash of any new or updated access controls.
14319: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14320:    key = integer (inbound ID)
14321:    value = uniqueID
14322: 
14323: =item *
14324: 
14325: get_timebased_id():
14326: 
14327: Attempts to get a unique timestamp-based suffix for use with items added to a 
14328: course via the Course Editor (e.g., folders, composite pages, 
14329: group bulletin boards).
14330: 
14331: Args: (first three required; six others optional)
14332: 
14333: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14334:    docssequence, or name of group
14335: 
14336: 2. keyid (alphanumeric): name of temporary locking key in hash,
14337:    e.g., num, boardids
14338: 
14339: 3. namespace: name of gdbm file used to store suffixes already assigned;  
14340:    file will be named nohist_namespace.db
14341: 
14342: 4. cdom: domain of course; default is current course domain from %env
14343: 
14344: 5. cnum: course number; default is current course number from %env
14345: 
14346: 6. idtype: set to concat if an additional digit is to be appended to the 
14347:    unix timestamp to form the suffix, if the plain timestamp is already
14348:    in use.  Default is to not do this, but simply increment the unix 
14349:    timestamp by 1 until a unique key is obtained.
14350: 
14351: 7. who: holder of locking key; defaults to user:domain for user.
14352: 
14353: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
14354:    retrying); default is 3.
14355: 
14356: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
14357: 
14358: Returns:
14359: 
14360: 1. suffix obtained (numeric)
14361: 
14362: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14363: 
14364: 3. error: contains (localized) error message if an error occurred.
14365: 
14366: 
14367: =back
14368: 
14369: =head2 HTTP Helper Routines
14370: 
14371: =over 4
14372: 
14373: =item *
14374: 
14375: escape() : unpack non-word characters into CGI-compatible hex codes
14376: 
14377: =item *
14378: 
14379: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14380: 
14381: =back
14382: 
14383: =head1 PRIVATE SUBROUTINES
14384: 
14385: =head2 Underlying communication routines (Shouldn't call)
14386: 
14387: =over 4
14388: 
14389: =item *
14390: 
14391: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14392: 
14393: =item *
14394: 
14395: reply() : uses subreply to send a message to remote machine, logs all failures
14396: 
14397: =item *
14398: 
14399: critical() : passes a critical message to another server; if cannot
14400: get through then place message in connection buffer directory and
14401: returns con_delayed, if incapable of saving message, returns
14402: con_failed
14403: 
14404: =item *
14405: 
14406: reconlonc() : tries to reconnect lonc client processes.
14407: 
14408: =back
14409: 
14410: =head2 Resource Access Logging
14411: 
14412: =over 4
14413: 
14414: =item *
14415: 
14416: flushcourselogs() : flush (save) buffer logs and access logs
14417: 
14418: =item *
14419: 
14420: courselog($what) : save message for course in hash
14421: 
14422: =item *
14423: 
14424: courseacclog($what) : save message for course using &courselog().  Perform
14425: special processing for specific resource types (problems, exams, quizzes, etc).
14426: 
14427: =item *
14428: 
14429: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14430: as a PerlChildExitHandler
14431: 
14432: =back
14433: 
14434: =head2 Other
14435: 
14436: =over 4
14437: 
14438: =item *
14439: 
14440: symblist($mapname,%newhash) : update symbolic storage links
14441: 
14442: =back
14443: 
14444: =cut
14445: 

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