File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1286: download - view: text, annotated - select for diffs
Thu May 21 23:10:57 2015 UTC (9 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Course default (applies to all courses), which can be overridden
  by course settings in a specific course, for who, besides owner
  and coordinator(s) may clone a course.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1286 2015/05/21 23:10:57 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  853:                                              $try_server));
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     next unless (&spare_can_host($udom,$uint_dom,
  865:                                                  $remotesessions,$try_server));
  866: 	            ($spare_server, $lowest_load) =
  867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  868:                 }
  869: 	    }
  870:         }
  871:     }
  872: 
  873:     if (!$want_server_name) {
  874:         my $protocol = 'http';
  875:         if ($protocol{$spare_server} eq 'https') {
  876:             $protocol = $protocol{$spare_server};
  877:         }
  878:         if (defined($spare_server)) {
  879:             my $hostname = &hostname($spare_server);
  880:             if (defined($hostname)) {
  881: 	        $spare_server = $protocol.'://'.$hostname;
  882:             }
  883:         }
  884:     }
  885:     return $spare_server;
  886: }
  887: 
  888: sub compare_server_load {
  889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  890: 
  891:     if ($required) {
  892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  895:         if (($major eq '' && $minor eq '') ||
  896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  897:             return ($spare_server,$lowest_load);
  898:         }
  899:     }
  900: 
  901:     my $loadans     = &reply('load',    $try_server);
  902:     my $userloadans = &reply('userload',$try_server);
  903: 
  904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  906:     }
  907: 
  908:     my $load;
  909:     if ($loadans =~ /\d/) {
  910: 	if ($userloadans =~ /\d/) {
  911: 	    #both are numbers, pick the bigger one
  912: 	    $load = ($loadans > $userloadans) ? $loadans 
  913: 		                              : $userloadans;
  914: 	} else {
  915: 	    $load = $loadans;
  916: 	}
  917:     } else {
  918: 	$load = $userloadans;
  919:     }
  920: 
  921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  922: 	$spare_server = $try_server;
  923: 	$lowest_load  = $load;
  924:     }
  925:     return ($spare_server,$lowest_load);
  926: }
  927: 
  928: # --------------------------- ask offload servers if user already has a session
  929: sub find_existing_session {
  930:     my ($udom,$uname) = @_;
  931:     my $spareshash = &this_host_spares($udom);
  932:     if (ref($spareshash) eq 'HASH') {
  933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  941:             }
  942:         }
  943:     }
  944:     return;
  945: }
  946: 
  947: # -------------------------------- ask if server already has a session for user
  948: sub has_user_session {
  949:     my ($lonid,$udom,$uname) = @_;
  950:     my $result = &reply(join(':','userhassession',
  951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  952:     return 1 if ($result eq 'ok');
  953: 
  954:     return 0;
  955: }
  956: 
  957: # --------- determine least loaded server in a user's domain which allows login
  958: 
  959: sub choose_server {
  960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  962:     my %servers = &get_servers($udom);
  963:     my $lowest_load = 30000;
  964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  965:     if ($skiploadbal) {
  966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  967:         unless (defined($cached)) {
  968:             my $cachetime = 60*60*24;
  969:             my %domconfig =
  970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  973:                                            $cachetime);
  974:             }
  975:         }
  976:     }
  977:     foreach my $lonhost (keys(%servers)) {
  978:         if ($skiploadbal) {
  979:             if (ref($balancers) eq 'HASH') {
  980:                 next if (exists($balancers->{$lonhost}));
  981:             }
  982:         }   
  983:         my $loginvia;
  984:         if ($checkloginvia) {
  985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  986:             if ($loginvia) {
  987:                 my ($server,$path) = split(/:/,$loginvia);
  988:                 ($login_host, $lowest_load) =
  989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  990:                 if ($login_host eq $server) {
  991:                     $portal_path = $path;
  992:                     $isredirect = 1;
  993:                 }
  994:             } else {
  995:                 ($login_host, $lowest_load) =
  996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  997:                 if ($login_host eq $lonhost) {
  998:                     $portal_path = '';
  999:                     $isredirect = ''; 
 1000:                 }
 1001:             }
 1002:         } else {
 1003:             ($login_host, $lowest_load) =
 1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1005:         }
 1006:     }
 1007:     if ($login_host ne '') {
 1008:         $hostname = &hostname($login_host);
 1009:     }
 1010:     return ($login_host,$hostname,$portal_path,$isredirect);
 1011: }
 1012: 
 1013: # --------------------------------------------- Try to change a user's password
 1014: 
 1015: sub changepass {
 1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1017:     $currentpass = &escape($currentpass);
 1018:     $newpass     = &escape($newpass);
 1019:     my $lonhost = $perlvar{'lonHostID'};
 1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1021: 		       $server);
 1022:     if (! $answer) {
 1023: 	&logthis("No reply on password change request to $server ".
 1024: 		 "by $uname in domain $udom.");
 1025:     } elsif ($answer =~ "^ok") {
 1026:         &logthis("$uname in $udom successfully changed their password ".
 1027: 		 "on $server.");
 1028:     } elsif ($answer =~ "^pwchange_failure") {
 1029: 	&logthis("$uname in $udom was unable to change their password ".
 1030: 		 "on $server.  The action was blocked by either lcpasswd ".
 1031: 		 "or pwchange");
 1032:     } elsif ($answer =~ "^non_authorized") {
 1033:         &logthis("$uname in $udom did not get their password correct when ".
 1034: 		 "attempting to change it on $server.");
 1035:     } elsif ($answer =~ "^auth_mode_error") {
 1036:         &logthis("$uname in $udom attempted to change their password despite ".
 1037: 		 "not being locally or internally authenticated on $server.");
 1038:     } elsif ($answer =~ "^unknown_user") {
 1039:         &logthis("$uname in $udom attempted to change their password ".
 1040: 		 "on $server but were unable to because $server is not ".
 1041: 		 "their home server.");
 1042:     } elsif ($answer =~ "^refused") {
 1043: 	&logthis("$server refused to change $uname in $udom password because ".
 1044: 		 "it was sent an unencrypted request to change the password.");
 1045:     } elsif ($answer =~ "invalid_client") {
 1046:         &logthis("$server refused to change $uname in $udom password because ".
 1047:                  "it was a reset by e-mail originating from an invalid server.");
 1048:     }
 1049:     return $answer;
 1050: }
 1051: 
 1052: # ----------------------- Try to determine user's current authentication scheme
 1053: 
 1054: sub queryauthenticate {
 1055:     my ($uname,$udom)=@_;
 1056:     my $uhome=&homeserver($uname,$udom);
 1057:     if (!$uhome) {
 1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1059: 	return 'no_host';
 1060:     }
 1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1064:     }
 1065:     return $answer;
 1066: }
 1067: 
 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
 1069: 
 1070: sub authenticate {
 1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1072:     $upass=&escape($upass);
 1073:     $uname= &LONCAPA::clean_username($uname);
 1074:     my $uhome=&homeserver($uname,$udom,1);
 1075:     my $newhome;
 1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1077: # Maybe the machine was offline and only re-appeared again recently?
 1078:         &reconlonc();
 1079: # One more
 1080: 	$uhome=&homeserver($uname,$udom,1);
 1081:         if (($uhome eq 'no_host') && $checkdefauth) {
 1082:             if (defined(&domain($udom,'primary'))) {
 1083:                 $newhome=&domain($udom,'primary');
 1084:             }
 1085:             if ($newhome ne '') {
 1086:                 $uhome = $newhome;
 1087:             }
 1088:         }
 1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1091: 	    return 'no_host';
 1092:         }
 1093:     }
 1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1095:     if ($answer eq 'authorized') {
 1096:         if ($newhome) {
 1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1098:             return 'no_account_on_host'; 
 1099:         } else {
 1100:             &logthis("User $uname at $udom authorized by $uhome");
 1101:             return $uhome;
 1102:         }
 1103:     }
 1104:     if ($answer eq 'non_authorized') {
 1105: 	&logthis("User $uname at $udom rejected by $uhome");
 1106: 	return 'no_host'; 
 1107:     }
 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1109:     return 'no_host';
 1110: }
 1111: 
 1112: sub can_host_session {
 1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1114:     my $canhost = 1;
 1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1116:     if (ref($remotesessions) eq 'HASH') {
 1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1119:                 $canhost = 0;
 1120:             } else {
 1121:                 $canhost = 1;
 1122:             }
 1123:         }
 1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1126:                 $canhost = 1;
 1127:             } else {
 1128:                 $canhost = 0;
 1129:             }
 1130:         }
 1131:         if ($canhost) {
 1132:             if ($remotesessions->{'version'} ne '') {
 1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1134:                 if ($reqmajor ne '' && $reqminor ne '') {
 1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1136:                         my $major = $1;
 1137:                         my $minor = $2;
 1138:                         if (($major < $reqmajor ) ||
 1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1140:                             $canhost = 0;
 1141:                         }
 1142:                     } else {
 1143:                         $canhost = 0;
 1144:                     }
 1145:                 }
 1146:             }
 1147:         }
 1148:     }
 1149:     if ($canhost) {
 1150:         if (ref($hostedsessions) eq 'HASH') {
 1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1154:                 if (($uint_dom ne '') && 
 1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1156:                     $canhost = 0;
 1157:                 } else {
 1158:                     $canhost = 1;
 1159:                 }
 1160:             }
 1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1162:                 if (($uint_dom ne '') && 
 1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1164:                     $canhost = 1;
 1165:                 } else {
 1166:                     $canhost = 0;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return $canhost;
 1172: }
 1173: 
 1174: sub spare_can_host {
 1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1176:     my $canhost=1;
 1177:     my $try_server_hostname = &hostname($try_server);
 1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1179:     my $serverhomedom = &host_domain($serverhomeID);
 1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1183:             $canhost = 0;
 1184:         }
 1185:     }
 1186:     if (($canhost) && ($uint_dom)) {
 1187:         my @intdoms;
 1188:         my $internet_names = &get_internet_names($try_server);
 1189:         if (ref($internet_names) eq 'ARRAY') {
 1190:             @intdoms = @{$internet_names};
 1191:         }
 1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1195:                                          $remotesessions,
 1196:                                          $defdomdefaults{'hostedsessions'});
 1197:         }
 1198:     }
 1199:     return $canhost;
 1200: }
 1201: 
 1202: sub this_host_spares {
 1203:     my ($dom) = @_;
 1204:     my ($dom_in_use,$lonhost_in_use,$result);
 1205:     my @hosts = &current_machine_ids();
 1206:     foreach my $lonhost (@hosts) {
 1207:         if (&host_domain($lonhost) eq $dom) {
 1208:             $dom_in_use = $dom;
 1209:             $lonhost_in_use = $lonhost;
 1210:             last;
 1211:         }
 1212:     }
 1213:     if ($dom_in_use ne '') {
 1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1215:     }
 1216:     if (ref($result) ne 'HASH') {
 1217:         $lonhost_in_use = $perlvar{'lonHostID'};
 1218:         $dom_in_use = &host_domain($lonhost_in_use);
 1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1220:         if (ref($result) ne 'HASH') {
 1221:             $result = \%spareid;
 1222:         }
 1223:     }
 1224:     return $result;
 1225: }
 1226: 
 1227: sub spares_for_offload  {
 1228:     my ($dom_in_use,$lonhost_in_use) = @_;
 1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1230:     if (defined($cached)) {
 1231:         return $result;
 1232:     } else {
 1233:         my $cachetime = 60*60*24;
 1234:         my %domconfig =
 1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1240:                 }
 1241:             }
 1242:         }
 1243:     }
 1244:     return;
 1245: }
 1246: 
 1247: sub get_lonbalancer_config {
 1248:     my ($servers) = @_;
 1249:     my ($currbalancer,$currtargets);
 1250:     if (ref($servers) eq 'HASH') {
 1251:         foreach my $server (keys(%{$servers})) {
 1252:             my %what = (
 1253:                          spareid => 1,
 1254:                          perlvar => 1,
 1255:                        );
 1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1257:             if ($result eq 'ok') {
 1258:                 if (ref($returnhash) eq 'HASH') {
 1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1261:                             $currbalancer = $server;
 1262:                             $currtargets = {};
 1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1266:                                 }
 1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1269:                                 }
 1270:                             }
 1271:                             last;
 1272:                         }
 1273:                     }
 1274:                 }
 1275:             }
 1276:         }
 1277:     }
 1278:     return ($currbalancer,$currtargets);
 1279: }
 1280: 
 1281: sub check_loadbalancing {
 1282:     my ($uname,$udom) = @_;
 1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1284:         $rule_in_effect,$offloadto,$otherserver);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my @hosts = &current_machine_ids();
 1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1290:     my $serverhomedom = &host_domain($lonhost);
 1291: 
 1292:     my $cachetime = 60*60*24;
 1293: 
 1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1295:         $dom_in_use = $udom;
 1296:         $homeintdom = 1;
 1297:     } else {
 1298:         $dom_in_use = $serverhomedom;
 1299:     }
 1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1301:     unless (defined($cached)) {
 1302:         my %domconfig =
 1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1306:         }
 1307:     }
 1308:     if (ref($result) eq 'HASH') {
 1309:         ($is_balancer,$currtargets,$currrules) = 
 1310:             &check_balancer_result($result,@hosts);
 1311:         if ($is_balancer) {
 1312:             if (ref($currrules) eq 'HASH') {
 1313:                 if ($homeintdom) {
 1314:                     if ($uname ne '') {
 1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1321:                             }
 1322:                         }
 1323:                         if ($rule_in_effect eq '') {
 1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1325:                             if ($userenv{'inststatus'} ne '') {
 1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1327:                                 my ($othertitle,$usertypes,$types) =
 1328:                                     &Apache::loncommon::sorted_inst_types($udom);
 1329:                                 if (ref($types) eq 'ARRAY') {
 1330:                                     foreach my $type (@{$types}) {
 1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1332:                                             if (exists($currrules->{$type})) {
 1333:                                                 $rule_in_effect = $currrules->{$type};
 1334:                                             }
 1335:                                         }
 1336:                                     }
 1337:                                 }
 1338:                             } else {
 1339:                                 if (exists($currrules->{'default'})) {
 1340:                                     $rule_in_effect = $currrules->{'default'};
 1341:                                 }
 1342:                             }
 1343:                         }
 1344:                     } else {
 1345:                         if (exists($currrules->{'default'})) {
 1346:                             $rule_in_effect = $currrules->{'default'};
 1347:                         }
 1348:                     }
 1349:                 } else {
 1350:                     if ($currrules->{'_LC_external'} ne '') {
 1351:                         $rule_in_effect = $currrules->{'_LC_external'};
 1352:                     }
 1353:                 }
 1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1355:                                                        $uname,$udom);
 1356:             }
 1357:         }
 1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1360:         unless (defined($cached)) {
 1361:             my %domconfig =
 1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1365:             }
 1366:         }
 1367:         if (ref($result) eq 'HASH') {
 1368:             ($is_balancer,$currtargets,$currrules) = 
 1369:                 &check_balancer_result($result,@hosts);
 1370:             if ($is_balancer) {
 1371:                 if (ref($currrules) eq 'HASH') {
 1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1374:                     }
 1375:                 }
 1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1377:                                                        $uname,$udom);
 1378:             }
 1379:         } else {
 1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1381:                 $is_balancer = 1;
 1382:                 $offloadto = &this_host_spares($dom_in_use);
 1383:             }
 1384:         }
 1385:     } else {
 1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1387:             $is_balancer = 1;
 1388:             $offloadto = &this_host_spares($dom_in_use);
 1389:         }
 1390:     }
 1391:     if ($is_balancer) {
 1392:         my $lowest_load = 30000;
 1393:         if (ref($offloadto) eq 'HASH') {
 1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1396:                     ($otherserver,$lowest_load) =
 1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1398:                 }
 1399:             }
 1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1401: 
 1402:             if (!$found_server) {
 1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1405:                         ($otherserver,$lowest_load) =
 1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1407:                     }
 1408:                 }
 1409:             }
 1410:         } elsif (ref($offloadto) eq 'ARRAY') {
 1411:             if (@{$offloadto} == 1) {
 1412:                 $otherserver = $offloadto->[0];
 1413:             } elsif (@{$offloadto} > 1) {
 1414:                 foreach my $try_server (@{$offloadto}) {
 1415:                     ($otherserver,$lowest_load) =
 1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1417:                 }
 1418:             }
 1419:         }
 1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1421:             $is_balancer = 0;
 1422:             if ($uname ne '' && $udom ne '') {
 1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1424:                     
 1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1426:                              'user.loadbalcheck.time' => time});
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return ($is_balancer,$otherserver);
 1432: }
 1433: 
 1434: sub check_balancer_result {
 1435:     my ($result,@hosts) = @_;
 1436:     my ($is_balancer,$currtargets,$currrules);
 1437:     if (ref($result) eq 'HASH') {
 1438:         if ($result->{'lonhost'} ne '') {
 1439:             my $currbalancer = $result->{'lonhost'};
 1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1441:                 $is_balancer = 1;
 1442:                 $currtargets = $result->{'targets'};
 1443:                 $currrules = $result->{'rules'};
 1444:             }
 1445:         } else {
 1446:             foreach my $key (keys(%{$result})) {
 1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1448:                     (ref($result->{$key}) eq 'HASH')) {
 1449:                     $is_balancer = 1;
 1450:                     $currrules = $result->{$key}{'rules'};
 1451:                     $currtargets = $result->{$key}{'targets'};
 1452:                     last;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     return ($is_balancer,$currtargets,$currrules);
 1458: }
 1459: 
 1460: sub get_loadbalancer_targets {
 1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1462:     my $offloadto;
 1463:     if ($rule_in_effect eq 'none') {
 1464:         return [$perlvar{'lonHostID'}];
 1465:     } elsif ($rule_in_effect eq '') {
 1466:         $offloadto = $currtargets;
 1467:     } else {
 1468:         if ($rule_in_effect eq 'homeserver') {
 1469:             my $homeserver = &homeserver($uname,$udom);
 1470:             if ($homeserver ne 'no_host') {
 1471:                 $offloadto = [$homeserver];
 1472:             }
 1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1474:             my %domconfig =
 1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1480:                     }
 1481:                 }
 1482:             } else {
 1483:                 my %servers = &internet_dom_servers($udom);
 1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1485:                 if (&hostname($remotebalancer) ne '') {
 1486:                     $offloadto = [$remotebalancer];
 1487:                 }
 1488:             }
 1489:         } elsif (&hostname($rule_in_effect) ne '') {
 1490:             $offloadto = [$rule_in_effect];
 1491:         }
 1492:     }
 1493:     return $offloadto;
 1494: }
 1495: 
 1496: sub internet_dom_servers {
 1497:     my ($dom) = @_;
 1498:     my (%uniqservers,%servers);
 1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1500:     my @machinedoms = &machine_domains($primaryserver);
 1501:     foreach my $mdom (@machinedoms) {
 1502:         my %currservers = %servers;
 1503:         my %server = &get_servers($mdom);
 1504:         %servers = (%currservers,%server);
 1505:     }
 1506:     my %by_hostname;
 1507:     foreach my $id (keys(%servers)) {
 1508:         push(@{$by_hostname{$servers{$id}}},$id);
 1509:     }
 1510:     foreach my $hostname (sort(keys(%by_hostname))) {
 1511:         if (@{$by_hostname{$hostname}} > 1) {
 1512:             my $match = 0;
 1513:             foreach my $id (@{$by_hostname{$hostname}}) {
 1514:                 if (&host_domain($id) eq $dom) {
 1515:                     $uniqservers{$id} = $hostname;
 1516:                     $match = 1;
 1517:                 }
 1518:             }
 1519:             unless ($match) {
 1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1521:             }
 1522:         } else {
 1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1524:         }
 1525:     }
 1526:     return %uniqservers;
 1527: }
 1528: 
 1529: # ---------------------- Find the homebase for a user from domain's lib servers
 1530: 
 1531: my %homecache;
 1532: sub homeserver {
 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
 1534:     my $index="$uname:$udom";
 1535: 
 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1537: 
 1538:     my %servers = &get_servers($udom,'library');
 1539:     foreach my $tryserver (keys(%servers)) {
 1540:         next if ($ignoreBadCache ne 'true' && 
 1541: 		 exists($badServerCache{$tryserver}));
 1542: 
 1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1544: 	if ($answer eq 'found') {
 1545: 	    delete($badServerCache{$tryserver}); 
 1546: 	    return $homecache{$index}=$tryserver;
 1547: 	} elsif ($answer eq 'no_host') {
 1548: 	    $badServerCache{$tryserver}=1;
 1549: 	}
 1550:     }    
 1551:     return 'no_host';
 1552: }
 1553: 
 1554: # ------------------------------------- Find the usernames behind a list of IDs
 1555: 
 1556: sub idget {
 1557:     my ($udom,@ids)=@_;
 1558:     my %returnhash=();
 1559:     
 1560:     my %servers = &get_servers($udom,'library');
 1561:     foreach my $tryserver (keys(%servers)) {
 1562: 	my $idlist=join('&',@ids);
 1563: 	$idlist=~tr/A-Z/a-z/; 
 1564: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1565: 	my @answer=();
 1566: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1567: 	    @answer=split(/\&/,$reply);
 1568: 	}                    ;
 1569: 	my $i;
 1570: 	for ($i=0;$i<=$#ids;$i++) {
 1571: 	    if ($answer[$i]) {
 1572: 		$returnhash{$ids[$i]}=$answer[$i];
 1573: 	    } 
 1574: 	}
 1575:     } 
 1576:     return %returnhash;
 1577: }
 1578: 
 1579: # ------------------------------------- Find the IDs behind a list of usernames
 1580: 
 1581: sub idrget {
 1582:     my ($udom,@unames)=@_;
 1583:     my %returnhash=();
 1584:     foreach my $uname (@unames) {
 1585:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1586:     }
 1587:     return %returnhash;
 1588: }
 1589: 
 1590: # ------------------------------- Store away a list of names and associated IDs
 1591: 
 1592: sub idput {
 1593:     my ($udom,%ids)=@_;
 1594:     my %servers=();
 1595:     foreach my $uname (keys(%ids)) {
 1596: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1597:         my $uhom=&homeserver($uname,$udom);
 1598:         if ($uhom ne 'no_host') {
 1599:             my $id=&escape($ids{$uname});
 1600:             $id=~tr/A-Z/a-z/;
 1601:             my $esc_unam=&escape($uname);
 1602: 	    if ($servers{$uhom}) {
 1603: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1604:             } else {
 1605:                 $servers{$uhom}=$id.'='.$esc_unam;
 1606:             }
 1607:         }
 1608:     }
 1609:     foreach my $server (keys(%servers)) {
 1610:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1611:     }
 1612: }
 1613: 
 1614: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1615: 
 1616: sub iddel {
 1617:     my ($udom,$idshashref,$uhome)=@_;
 1618:     my %result=();
 1619:     unless (ref($idshashref) eq 'HASH') {
 1620:         return %result;
 1621:     }
 1622:     my %servers=();
 1623:     while (my ($id,$uname) = each(%{$idshashref})) {
 1624:         my $uhom;
 1625:         if ($uhome) {
 1626:             $uhom = $uhome;
 1627:         } else {
 1628:             $uhom=&homeserver($uname,$udom);
 1629:         }
 1630:         if ($uhom ne 'no_host') {
 1631:             if ($servers{$uhom}) {
 1632:                 $servers{$uhom}.='&'.&escape($id);
 1633:             } else {
 1634:                 $servers{$uhom}=&escape($id);
 1635:             }
 1636:         }
 1637:     }
 1638:     foreach my $server (keys(%servers)) {
 1639:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1640:     }
 1641:     return %result;
 1642: }
 1643: 
 1644: # ------------------------------dump from db file owned by domainconfig user
 1645: sub dump_dom {
 1646:     my ($namespace, $udom, $regexp) = @_;
 1647: 
 1648:     $udom ||= $env{'user.domain'};
 1649: 
 1650:     return () unless $udom;
 1651: 
 1652:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1653: }
 1654: 
 1655: # ------------------------------------------ get items from domain db files   
 1656: 
 1657: sub get_dom {
 1658:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1659:     return if ($udom eq 'public');
 1660:     my $items='';
 1661:     foreach my $item (@$storearr) {
 1662:         $items.=&escape($item).'&';
 1663:     }
 1664:     $items=~s/\&$//;
 1665:     if (!$udom) {
 1666:         $udom=$env{'user.domain'};
 1667:         return if ($udom eq 'public');
 1668:         if (defined(&domain($udom,'primary'))) {
 1669:             $uhome=&domain($udom,'primary');
 1670:         } else {
 1671:             undef($uhome);
 1672:         }
 1673:     } else {
 1674:         if (!$uhome) {
 1675:             if (defined(&domain($udom,'primary'))) {
 1676:                 $uhome=&domain($udom,'primary');
 1677:             }
 1678:         }
 1679:     }
 1680:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1681:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1682:         my %returnhash;
 1683:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1684:             return %returnhash;
 1685:         }
 1686:         my @pairs=split(/\&/,$rep);
 1687:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1688:             return @pairs;
 1689:         }
 1690:         my $i=0;
 1691:         foreach my $item (@$storearr) {
 1692:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1693:             $i++;
 1694:         }
 1695:         return %returnhash;
 1696:     } else {
 1697:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1698:     }
 1699: }
 1700: 
 1701: # -------------------------------------------- put items in domain db files 
 1702: 
 1703: sub put_dom {
 1704:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1705:     if (!$udom) {
 1706:         $udom=$env{'user.domain'};
 1707:         if (defined(&domain($udom,'primary'))) {
 1708:             $uhome=&domain($udom,'primary');
 1709:         } else {
 1710:             undef($uhome);
 1711:         }
 1712:     } else {
 1713:         if (!$uhome) {
 1714:             if (defined(&domain($udom,'primary'))) {
 1715:                 $uhome=&domain($udom,'primary');
 1716:             }
 1717:         }
 1718:     } 
 1719:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1720:         my $items='';
 1721:         foreach my $item (keys(%$storehash)) {
 1722:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1723:         }
 1724:         $items=~s/\&$//;
 1725:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1726:     } else {
 1727:         &logthis("put_dom failed - no homeserver and/or domain");
 1728:     }
 1729: }
 1730: 
 1731: # --------------------- newput for items in db file owned by domainconfig user
 1732: sub newput_dom {
 1733:     my ($namespace,$storehash,$udom) = @_;
 1734:     my $result;
 1735:     if (!$udom) {
 1736:         $udom=$env{'user.domain'};
 1737:     }
 1738:     if ($udom) {
 1739:         my $uname = &get_domainconfiguser($udom);
 1740:         $result = &newput($namespace,$storehash,$udom,$uname);
 1741:     }
 1742:     return $result;
 1743: }
 1744: 
 1745: # --------------------- delete for items in db file owned by domainconfig user
 1746: sub del_dom {
 1747:     my ($namespace,$storearr,$udom)=@_;
 1748:     if (ref($storearr) eq 'ARRAY') {
 1749:         if (!$udom) {
 1750:             $udom=$env{'user.domain'};
 1751:         }
 1752:         if ($udom) {
 1753:             my $uname = &get_domainconfiguser($udom); 
 1754:             return &del($namespace,$storearr,$udom,$uname);
 1755:         }
 1756:     }
 1757: }
 1758: 
 1759: # ----------------------------------construct domainconfig user for a domain 
 1760: sub get_domainconfiguser {
 1761:     my ($udom) = @_;
 1762:     return $udom.'-domainconfig';
 1763: }
 1764: 
 1765: sub retrieve_inst_usertypes {
 1766:     my ($udom) = @_;
 1767:     my (%returnhash,@order);
 1768:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1769:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1770:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1771:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1772:     } else {
 1773:         if (defined(&domain($udom,'primary'))) {
 1774:             my $uhome=&domain($udom,'primary');
 1775:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1776:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1777:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1778:                 return (\%returnhash,\@order);
 1779:             }
 1780:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1781:             my @pairs=split(/\&/,$hashitems);
 1782:             foreach my $item (@pairs) {
 1783:                 my ($key,$value)=split(/=/,$item,2);
 1784:                 $key = &unescape($key);
 1785:                 next if ($key =~ /^error: 2 /);
 1786:                 $returnhash{$key}=&thaw_unescape($value);
 1787:             }
 1788:             my @esc_order = split(/\&/,$orderitems);
 1789:             foreach my $item (@esc_order) {
 1790:                 push(@order,&unescape($item));
 1791:             }
 1792:         } else {
 1793:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1794:         }
 1795:         return (\%returnhash,\@order);
 1796:     }
 1797: }
 1798: 
 1799: sub is_domainimage {
 1800:     my ($url) = @_;
 1801:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1802:         if (&domain($1) ne '') {
 1803:             return '1';
 1804:         }
 1805:     }
 1806:     return;
 1807: }
 1808: 
 1809: sub inst_directory_query {
 1810:     my ($srch) = @_;
 1811:     my $udom = $srch->{'srchdomain'};
 1812:     my %results;
 1813:     my $homeserver = &domain($udom,'primary');
 1814:     my $outcome;
 1815:     if ($homeserver ne '') {
 1816: 	my $queryid=&reply("querysend:instdirsearch:".
 1817: 			   &escape($srch->{'srchby'}).':'.
 1818: 			   &escape($srch->{'srchterm'}).':'.
 1819: 			   &escape($srch->{'srchtype'}),$homeserver);
 1820: 	my $host=&hostname($homeserver);
 1821: 	if ($queryid !~/^\Q$host\E\_/) {
 1822: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1823: 	    return;
 1824: 	}
 1825: 	my $response = &get_query_reply($queryid);
 1826: 	my $maxtries = 5;
 1827: 	my $tries = 1;
 1828: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1829: 	    $response = &get_query_reply($queryid);
 1830: 	    $tries ++;
 1831: 	}
 1832: 
 1833:         if (!&error($response) && $response ne 'refused') {
 1834:             if ($response eq 'unavailable') {
 1835:                 $outcome = $response;
 1836:             } else {
 1837:                 $outcome = 'ok';
 1838:                 my @matches = split(/\n/,$response);
 1839:                 foreach my $match (@matches) {
 1840:                     my ($key,$value) = split(/=/,$match);
 1841:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1842:                 }
 1843:             }
 1844:         }
 1845:     }
 1846:     return ($outcome,%results);
 1847: }
 1848: 
 1849: sub usersearch {
 1850:     my ($srch) = @_;
 1851:     my $dom = $srch->{'srchdomain'};
 1852:     my %results;
 1853:     my %libserv = &all_library();
 1854:     my $query = 'usersearch';
 1855:     foreach my $tryserver (keys(%libserv)) {
 1856:         if (&host_domain($tryserver) eq $dom) {
 1857:             my $host=&hostname($tryserver);
 1858:             my $queryid=
 1859:                 &reply("querysend:".&escape($query).':'.
 1860:                        &escape($srch->{'srchby'}).':'.
 1861:                        &escape($srch->{'srchtype'}).':'.
 1862:                        &escape($srch->{'srchterm'}),$tryserver);
 1863:             if ($queryid !~/^\Q$host\E\_/) {
 1864:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1865:                 next;
 1866:             }
 1867:             my $reply = &get_query_reply($queryid);
 1868:             my $maxtries = 1;
 1869:             my $tries = 1;
 1870:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1871:                 $reply = &get_query_reply($queryid);
 1872:                 $tries ++;
 1873:             }
 1874:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1875:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1876:             } else {
 1877:                 my @matches;
 1878:                 if ($reply =~ /\n/) {
 1879:                     @matches = split(/\n/,$reply);
 1880:                 } else {
 1881:                     @matches = split(/\&/,$reply);
 1882:                 }
 1883:                 foreach my $match (@matches) {
 1884:                     my ($uname,$udom,%userhash);
 1885:                     foreach my $entry (split(/:/,$match)) {
 1886:                         my ($key,$value) =
 1887:                             map {&unescape($_);} split(/=/,$entry);
 1888:                         $userhash{$key} = $value;
 1889:                         if ($key eq 'username') {
 1890:                             $uname = $value;
 1891:                         } elsif ($key eq 'domain') {
 1892:                             $udom = $value;
 1893:                         }
 1894:                     }
 1895:                     $results{$uname.':'.$udom} = \%userhash;
 1896:                 }
 1897:             }
 1898:         }
 1899:     }
 1900:     return %results;
 1901: }
 1902: 
 1903: sub get_instuser {
 1904:     my ($udom,$uname,$id) = @_;
 1905:     my $homeserver = &domain($udom,'primary');
 1906:     my ($outcome,%results);
 1907:     if ($homeserver ne '') {
 1908:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1909:                            &escape($id).':'.&escape($udom),$homeserver);
 1910:         my $host=&hostname($homeserver);
 1911:         if ($queryid !~/^\Q$host\E\_/) {
 1912:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1913:             return;
 1914:         }
 1915:         my $response = &get_query_reply($queryid);
 1916:         my $maxtries = 5;
 1917:         my $tries = 1;
 1918:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1919:             $response = &get_query_reply($queryid);
 1920:             $tries ++;
 1921:         }
 1922:         if (!&error($response) && $response ne 'refused') {
 1923:             if ($response eq 'unavailable') {
 1924:                 $outcome = $response;
 1925:             } else {
 1926:                 $outcome = 'ok';
 1927:                 my @matches = split(/\n/,$response);
 1928:                 foreach my $match (@matches) {
 1929:                     my ($key,$value) = split(/=/,$match);
 1930:                     $results{&unescape($key)} = &thaw_unescape($value);
 1931:                 }
 1932:             }
 1933:         }
 1934:     }
 1935:     my %userinfo;
 1936:     if (ref($results{$uname}) eq 'HASH') {
 1937:         %userinfo = %{$results{$uname}};
 1938:     } 
 1939:     return ($outcome,%userinfo);
 1940: }
 1941: 
 1942: sub inst_rulecheck {
 1943:     my ($udom,$uname,$id,$item,$rules) = @_;
 1944:     my %returnhash;
 1945:     if ($udom ne '') {
 1946:         if (ref($rules) eq 'ARRAY') {
 1947:             @{$rules} = map {&escape($_);} (@{$rules});
 1948:             my $rulestr = join(':',@{$rules});
 1949:             my $homeserver=&domain($udom,'primary');
 1950:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1951:                 my $response;
 1952:                 if ($item eq 'username') {                
 1953:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1954:                                               ':'.&escape($uname).':'.$rulestr,
 1955:                                               $homeserver));
 1956:                 } elsif ($item eq 'id') {
 1957:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1958:                                               ':'.&escape($id).':'.$rulestr,
 1959:                                               $homeserver));
 1960:                 } elsif ($item eq 'selfcreate') {
 1961:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1962:                                                &escape($udom).':'.&escape($uname).
 1963:                                               ':'.$rulestr,$homeserver));
 1964:                 }
 1965:                 if ($response ne 'refused') {
 1966:                     my @pairs=split(/\&/,$response);
 1967:                     foreach my $item (@pairs) {
 1968:                         my ($key,$value)=split(/=/,$item,2);
 1969:                         $key = &unescape($key);
 1970:                         next if ($key =~ /^error: 2 /);
 1971:                         $returnhash{$key}=&thaw_unescape($value);
 1972:                     }
 1973:                 }
 1974:             }
 1975:         }
 1976:     }
 1977:     return %returnhash;
 1978: }
 1979: 
 1980: sub inst_userrules {
 1981:     my ($udom,$check) = @_;
 1982:     my (%ruleshash,@ruleorder);
 1983:     if ($udom ne '') {
 1984:         my $homeserver=&domain($udom,'primary');
 1985:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1986:             my $response;
 1987:             if ($check eq 'id') {
 1988:                 $response=&reply('instidrules:'.&escape($udom),
 1989:                                  $homeserver);
 1990:             } elsif ($check eq 'email') {
 1991:                 $response=&reply('instemailrules:'.&escape($udom),
 1992:                                  $homeserver);
 1993:             } else {
 1994:                 $response=&reply('instuserrules:'.&escape($udom),
 1995:                                  $homeserver);
 1996:             }
 1997:             if (($response ne 'refused') && ($response ne 'error') && 
 1998:                 ($response ne 'unknown_cmd') && 
 1999:                 ($response ne 'no_such_host')) {
 2000:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2001:                 my @pairs=split(/\&/,$hashitems);
 2002:                 foreach my $item (@pairs) {
 2003:                     my ($key,$value)=split(/=/,$item,2);
 2004:                     $key = &unescape($key);
 2005:                     next if ($key =~ /^error: 2 /);
 2006:                     $ruleshash{$key}=&thaw_unescape($value);
 2007:                 }
 2008:                 my @esc_order = split(/\&/,$orderitems);
 2009:                 foreach my $item (@esc_order) {
 2010:                     push(@ruleorder,&unescape($item));
 2011:                 }
 2012:             }
 2013:         }
 2014:     }
 2015:     return (\%ruleshash,\@ruleorder);
 2016: }
 2017: 
 2018: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2019: 
 2020: sub get_domain_defaults {
 2021:     my ($domain,$ignore_cache) = @_;
 2022:     return if (($domain eq '') || ($domain eq 'public'));
 2023:     my $cachetime = 60*60*24;
 2024:     unless ($ignore_cache) {
 2025:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2026:         if (defined($cached)) {
 2027:             if (ref($result) eq 'HASH') {
 2028:                 return %{$result};
 2029:             }
 2030:         }
 2031:     }
 2032:     my %domdefaults;
 2033:     my %domconfig =
 2034:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2035:                                   'requestcourses','inststatus',
 2036:                                   'coursedefaults','usersessions',
 2037:                                   'requestauthor','selfenrollment',
 2038:                                   'coursecategories'],$domain);
 2039:     my @coursetypes = ('official','unofficial','community','textbook');
 2040:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2041:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2042:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2043:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2044:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2045:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2046:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2047:     } else {
 2048:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2049:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2050:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2051:     }
 2052:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2053:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2054:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2055:         } else {
 2056:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2057:         }
 2058:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2059:         foreach my $item (@usertools) {
 2060:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2061:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2062:             }
 2063:         }
 2064:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2065:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2066:         }
 2067:     }
 2068:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2069:         foreach my $item ('official','unofficial','community','textbook') {
 2070:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2071:         }
 2072:     }
 2073:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2074:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2075:     }
 2076:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2077:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2078:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2079:         }
 2080:     }
 2081:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2082:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2083:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2084:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2085:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2086:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2087:         }
 2088:         foreach my $type (@coursetypes) {
 2089:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2090:                 unless ($type eq 'community') {
 2091:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2092:                 }
 2093:             }
 2094:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2095:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2096:             }
 2097:             if ($domdefaults{'postsubmit'} eq 'on') {
 2098:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2099:                     $domdefaults{$type.'postsubtimeout'} = 
 2100:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2101:                 }
 2102:             }
 2103:         }
 2104:         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)=@_;
 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:                 } else {
 4308:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4309:                              $sincefilter.':'.&escape($descfilter).':'.
 4310:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4311:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4312:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4313:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4314:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4315:                              &escape($cc_clone).':'.$cloneonly.':'.
 4316:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4317:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4318:                              $tryserver);
 4319:                 }
 4320:                      
 4321:                 my @pairs=split(/\&/,$rep);
 4322:                 foreach my $item (@pairs) {
 4323:                     my ($key,$value)=split(/\=/,$item,2);
 4324:                     $key = &unescape($key);
 4325:                     next if ($key =~ /^error: 2 /);
 4326:                     my $result = &thaw_unescape($value);
 4327:                     if (ref($result) eq 'HASH') {
 4328:                         $returnhash{$key}=$result;
 4329:                     } else {
 4330:                         my @responses = split(/:/,$value);
 4331:                         my @items = ('description','inst_code','owner','type');
 4332:                         for (my $i=0; $i<@responses; $i++) {
 4333:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4334:                         }
 4335:                     }
 4336:                 }
 4337:             }
 4338:         }
 4339:     }
 4340:     return %returnhash;
 4341: }
 4342: 
 4343: sub courselastaccess {
 4344:     my ($cdom,$cnum,$hostidref) = @_;
 4345:     my %returnhash;
 4346:     if ($cdom && $cnum) {
 4347:         my $chome = &homeserver($cnum,$cdom);
 4348:         if ($chome ne 'no_host') {
 4349:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4350:             &extract_lastaccess(\%returnhash,$rep);
 4351:         }
 4352:     } else {
 4353:         if (!$cdom) { $cdom=''; }
 4354:         my %libserv = &all_library();
 4355:         foreach my $tryserver (keys(%libserv)) {
 4356:             if (ref($hostidref) eq 'ARRAY') {
 4357:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4358:             } 
 4359:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4360:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4361:                 &extract_lastaccess(\%returnhash,$rep);
 4362:             }
 4363:         }
 4364:     }
 4365:     return %returnhash;
 4366: }
 4367: 
 4368: sub extract_lastaccess {
 4369:     my ($returnhash,$rep) = @_;
 4370:     if (ref($returnhash) eq 'HASH') {
 4371:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4372:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4373:                  $rep eq '') {
 4374:             my @pairs=split(/\&/,$rep);
 4375:             foreach my $item (@pairs) {
 4376:                 my ($key,$value)=split(/\=/,$item,2);
 4377:                 $key = &unescape($key);
 4378:                 next if ($key =~ /^error: 2 /);
 4379:                 $returnhash->{$key} = &thaw_unescape($value);
 4380:             }
 4381:         }
 4382:     }
 4383:     return;
 4384: }
 4385: 
 4386: # ---------------------------------------------------------- DC e-mail
 4387: 
 4388: sub dcmailput {
 4389:     my ($domain,$msgid,$message,$server)=@_;
 4390:     my $status = &Apache::lonnet::critical(
 4391:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4392:        &escape($message),$server);
 4393:     return $status;
 4394: }
 4395: 
 4396: sub dcmaildump {
 4397:     my ($dom,$startdate,$enddate,$senders) = @_;
 4398:     my %returnhash=();
 4399: 
 4400:     if (defined(&domain($dom,'primary'))) {
 4401:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4402:                                                          &escape($enddate).':';
 4403: 	my @esc_senders=map { &escape($_)} @$senders;
 4404: 	$cmd.=&escape(join('&',@esc_senders));
 4405: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4406:             my ($key,$value) = split(/\=/,$line,2);
 4407:             if (($key) && ($value)) {
 4408:                 $returnhash{&unescape($key)} = &unescape($value);
 4409:             }
 4410:         }
 4411:     }
 4412:     return %returnhash;
 4413: }
 4414: # ---------------------------------------------------------- Domain roles
 4415: 
 4416: sub get_domain_roles {
 4417:     my ($dom,$roles,$startdate,$enddate)=@_;
 4418:     if ((!defined($startdate)) || ($startdate eq '')) {
 4419:         $startdate = '.';
 4420:     }
 4421:     if ((!defined($enddate)) || ($enddate eq '')) {
 4422:         $enddate = '.';
 4423:     }
 4424:     my $rolelist;
 4425:     if (ref($roles) eq 'ARRAY') {
 4426:         $rolelist = join('&',@{$roles});
 4427:     }
 4428:     my %personnel = ();
 4429: 
 4430:     my %servers = &get_servers($dom,'library');
 4431:     foreach my $tryserver (keys(%servers)) {
 4432: 	%{$personnel{$tryserver}}=();
 4433: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4434: 					    &escape($startdate).':'.
 4435: 					    &escape($enddate).':'.
 4436: 					    &escape($rolelist), $tryserver))) {
 4437: 	    my ($key,$value) = split(/\=/,$line,2);
 4438: 	    if (($key) && ($value)) {
 4439: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4440: 	    }
 4441: 	}
 4442:     }
 4443:     return %personnel;
 4444: }
 4445: 
 4446: # ----------------------------------------------------------- Interval timing 
 4447: 
 4448: {
 4449: # Caches needed for speedup of navmaps
 4450: # We don't want to cache this for very long at all (5 seconds at most)
 4451: # 
 4452: # The user for whom we cache
 4453: my $cachedkey='';
 4454: # The cached times for this user
 4455: my %cachedtimes=();
 4456: # When this was last done
 4457: my $cachedtime='';
 4458: 
 4459: sub load_all_first_access {
 4460:     my ($uname,$udom)=@_;
 4461:     if (($cachedkey eq $uname.':'.$udom) &&
 4462:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4463:         return;
 4464:     }
 4465:     $cachedtime=time;
 4466:     $cachedkey=$uname.':'.$udom;
 4467:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4468: }
 4469: 
 4470: sub get_first_access {
 4471:     my ($type,$argsymb,$argmap)=@_;
 4472:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4473:     if ($argsymb) { $symb=$argsymb; }
 4474:     my ($map,$id,$res)=&decode_symb($symb);
 4475:     if ($argmap) { $map = $argmap; }
 4476:     if ($type eq 'course') {
 4477: 	$res='course';
 4478:     } elsif ($type eq 'map') {
 4479: 	$res=&symbread($map);
 4480:     } else {
 4481: 	$res=$symb;
 4482:     }
 4483:     &load_all_first_access($uname,$udom);
 4484:     return $cachedtimes{"$courseid\0$res"};
 4485: }
 4486: 
 4487: sub set_first_access {
 4488:     my ($type,$interval)=@_;
 4489:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4490:     my ($map,$id,$res)=&decode_symb($symb);
 4491:     if ($type eq 'course') {
 4492: 	$res='course';
 4493:     } elsif ($type eq 'map') {
 4494: 	$res=&symbread($map);
 4495:     } else {
 4496: 	$res=$symb;
 4497:     }
 4498:     $cachedkey='';
 4499:     my $firstaccess=&get_first_access($type,$symb,$map);
 4500:     if (!$firstaccess) {
 4501:         my $start = time;
 4502: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4503:                           $udom,$uname);
 4504:         if ($putres eq 'ok') {
 4505:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4506:                  $udom,$uname); 
 4507:             &appenv(
 4508:                      {
 4509:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4510:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4511:                      }
 4512:                   );
 4513:         }
 4514:         return $putres;
 4515:     }
 4516:     return 'already_set';
 4517: }
 4518: }
 4519: 
 4520: # --------------------------------------------- Set Expire Date for Spreadsheet
 4521: 
 4522: sub expirespread {
 4523:     my ($uname,$udom,$stype,$usymb)=@_;
 4524:     my $cid=$env{'request.course.id'}; 
 4525:     if ($cid) {
 4526:        my $now=time;
 4527:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4528:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4529:                             $env{'course.'.$cid.'.num'}.
 4530: 	        	    ':nohist_expirationdates:'.
 4531:                             &escape($key).'='.$now,
 4532:                             $env{'course.'.$cid.'.home'})
 4533:     }
 4534:     return 'ok';
 4535: }
 4536: 
 4537: # ----------------------------------------------------- Devalidate Spreadsheets
 4538: 
 4539: sub devalidate {
 4540:     my ($symb,$uname,$udom)=@_;
 4541:     my $cid=$env{'request.course.id'}; 
 4542:     if ($cid) {
 4543:         # delete the stored spreadsheets for
 4544:         # - the student level sheet of this user in course's homespace
 4545:         # - the assessment level sheet for this resource 
 4546:         #   for this user in user's homespace
 4547: 	# - current conditional state info
 4548: 	my $key=$uname.':'.$udom.':';
 4549:         my $status=
 4550: 	    &del('nohist_calculatedsheets',
 4551: 		 [$key.'studentcalc:'],
 4552: 		 $env{'course.'.$cid.'.domain'},
 4553: 		 $env{'course.'.$cid.'.num'})
 4554: 		.' '.
 4555: 	    &del('nohist_calculatedsheets_'.$cid,
 4556: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4557:         unless ($status eq 'ok ok') {
 4558:            &logthis('Could not devalidate spreadsheet '.
 4559:                     $uname.' at '.$udom.' for '.
 4560: 		    $symb.': '.$status);
 4561:         }
 4562: 	&delenv('user.state.'.$cid);
 4563:     }
 4564: }
 4565: 
 4566: sub get_scalar {
 4567:     my ($string,$end) = @_;
 4568:     my $value;
 4569:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4570: 	$value = $1;
 4571:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4572: 	$value = $1;
 4573:     }
 4574:     return &unescape($value);
 4575: }
 4576: 
 4577: sub array2str {
 4578:   my (@array) = @_;
 4579:   my $result=&arrayref2str(\@array);
 4580:   $result=~s/^__ARRAY_REF__//;
 4581:   $result=~s/__END_ARRAY_REF__$//;
 4582:   return $result;
 4583: }
 4584: 
 4585: sub arrayref2str {
 4586:   my ($arrayref) = @_;
 4587:   my $result='__ARRAY_REF__';
 4588:   foreach my $elem (@$arrayref) {
 4589:     if(ref($elem) eq 'ARRAY') {
 4590:       $result.=&arrayref2str($elem).'&';
 4591:     } elsif(ref($elem) eq 'HASH') {
 4592:       $result.=&hashref2str($elem).'&';
 4593:     } elsif(ref($elem)) {
 4594:       #print("Got a ref of ".(ref($elem))." skipping.");
 4595:     } else {
 4596:       $result.=&escape($elem).'&';
 4597:     }
 4598:   }
 4599:   $result=~s/\&$//;
 4600:   $result .= '__END_ARRAY_REF__';
 4601:   return $result;
 4602: }
 4603: 
 4604: sub hash2str {
 4605:   my (%hash) = @_;
 4606:   my $result=&hashref2str(\%hash);
 4607:   $result=~s/^__HASH_REF__//;
 4608:   $result=~s/__END_HASH_REF__$//;
 4609:   return $result;
 4610: }
 4611: 
 4612: sub hashref2str {
 4613:   my ($hashref)=@_;
 4614:   my $result='__HASH_REF__';
 4615:   foreach my $key (sort(keys(%$hashref))) {
 4616:     if (ref($key) eq 'ARRAY') {
 4617:       $result.=&arrayref2str($key).'=';
 4618:     } elsif (ref($key) eq 'HASH') {
 4619:       $result.=&hashref2str($key).'=';
 4620:     } elsif (ref($key)) {
 4621:       $result.='=';
 4622:       #print("Got a ref of ".(ref($key))." skipping.");
 4623:     } else {
 4624: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4625:     }
 4626: 
 4627:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4628:       $result.=&arrayref2str($hashref->{$key}).'&';
 4629:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4630:       $result.=&hashref2str($hashref->{$key}).'&';
 4631:     } elsif(ref($hashref->{$key})) {
 4632:        $result.='&';
 4633:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4634:     } else {
 4635:       $result.=&escape($hashref->{$key}).'&';
 4636:     }
 4637:   }
 4638:   $result=~s/\&$//;
 4639:   $result .= '__END_HASH_REF__';
 4640:   return $result;
 4641: }
 4642: 
 4643: sub str2hash {
 4644:     my ($string)=@_;
 4645:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4646:     return %$hash;
 4647: }
 4648: 
 4649: sub str2hashref {
 4650:   my ($string) = @_;
 4651: 
 4652:   my %hash;
 4653: 
 4654:   if($string !~ /^__HASH_REF__/) {
 4655:       if (! ($string eq '' || !defined($string))) {
 4656: 	  $hash{'error'}='Not hash reference';
 4657:       }
 4658:       return (\%hash, $string);
 4659:   }
 4660: 
 4661:   $string =~ s/^__HASH_REF__//;
 4662: 
 4663:   while($string !~ /^__END_HASH_REF__/) {
 4664:       #key
 4665:       my $key='';
 4666:       if($string =~ /^__HASH_REF__/) {
 4667:           ($key, $string)=&str2hashref($string);
 4668:           if(defined($key->{'error'})) {
 4669:               $hash{'error'}='Bad data';
 4670:               return (\%hash, $string);
 4671:           }
 4672:       } elsif($string =~ /^__ARRAY_REF__/) {
 4673:           ($key, $string)=&str2arrayref($string);
 4674:           if($key->[0] eq 'Array reference error') {
 4675:               $hash{'error'}='Bad data';
 4676:               return (\%hash, $string);
 4677:           }
 4678:       } else {
 4679:           $string =~ s/^(.*?)=//;
 4680: 	  $key=&unescape($1);
 4681:       }
 4682:       $string =~ s/^=//;
 4683: 
 4684:       #value
 4685:       my $value='';
 4686:       if($string =~ /^__HASH_REF__/) {
 4687:           ($value, $string)=&str2hashref($string);
 4688:           if(defined($value->{'error'})) {
 4689:               $hash{'error'}='Bad data';
 4690:               return (\%hash, $string);
 4691:           }
 4692:       } elsif($string =~ /^__ARRAY_REF__/) {
 4693:           ($value, $string)=&str2arrayref($string);
 4694:           if($value->[0] eq 'Array reference error') {
 4695:               $hash{'error'}='Bad data';
 4696:               return (\%hash, $string);
 4697:           }
 4698:       } else {
 4699: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4700:       }
 4701:       $string =~ s/^&//;
 4702: 
 4703:       $hash{$key}=$value;
 4704:   }
 4705: 
 4706:   $string =~ s/^__END_HASH_REF__//;
 4707: 
 4708:   return (\%hash, $string);
 4709: }
 4710: 
 4711: sub str2array {
 4712:     my ($string)=@_;
 4713:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4714:     return @$array;
 4715: }
 4716: 
 4717: sub str2arrayref {
 4718:   my ($string) = @_;
 4719:   my @array;
 4720: 
 4721:   if($string !~ /^__ARRAY_REF__/) {
 4722:       if (! ($string eq '' || !defined($string))) {
 4723: 	  $array[0]='Array reference error';
 4724:       }
 4725:       return (\@array, $string);
 4726:   }
 4727: 
 4728:   $string =~ s/^__ARRAY_REF__//;
 4729: 
 4730:   while($string !~ /^__END_ARRAY_REF__/) {
 4731:       my $value='';
 4732:       if($string =~ /^__HASH_REF__/) {
 4733:           ($value, $string)=&str2hashref($string);
 4734:           if(defined($value->{'error'})) {
 4735:               $array[0] ='Array reference error';
 4736:               return (\@array, $string);
 4737:           }
 4738:       } elsif($string =~ /^__ARRAY_REF__/) {
 4739:           ($value, $string)=&str2arrayref($string);
 4740:           if($value->[0] eq 'Array reference error') {
 4741:               $array[0] ='Array reference error';
 4742:               return (\@array, $string);
 4743:           }
 4744:       } else {
 4745: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4746:       }
 4747:       $string =~ s/^&//;
 4748: 
 4749:       push(@array, $value);
 4750:   }
 4751: 
 4752:   $string =~ s/^__END_ARRAY_REF__//;
 4753: 
 4754:   return (\@array, $string);
 4755: }
 4756: 
 4757: # -------------------------------------------------------------------Temp Store
 4758: 
 4759: sub tmpreset {
 4760:   my ($symb,$namespace,$domain,$stuname) = @_;
 4761:   if (!$symb) {
 4762:     $symb=&symbread();
 4763:     if (!$symb) { $symb= $env{'request.url'}; }
 4764:   }
 4765:   $symb=escape($symb);
 4766: 
 4767:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4768:   $namespace=~s/\//\_/g;
 4769:   $namespace=~s/\W//g;
 4770: 
 4771:   if (!$domain) { $domain=$env{'user.domain'}; }
 4772:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4773:   if ($domain eq 'public' && $stuname eq 'public') {
 4774:       $stuname=$ENV{'REMOTE_ADDR'};
 4775:   }
 4776:   my $path=LONCAPA::tempdir();
 4777:   my %hash;
 4778:   if (tie(%hash,'GDBM_File',
 4779: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4780: 	  &GDBM_WRCREAT(),0640)) {
 4781:     foreach my $key (keys(%hash)) {
 4782:       if ($key=~ /:$symb/) {
 4783: 	delete($hash{$key});
 4784:       }
 4785:     }
 4786:   }
 4787: }
 4788: 
 4789: sub tmpstore {
 4790:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4791: 
 4792:   if (!$symb) {
 4793:     $symb=&symbread();
 4794:     if (!$symb) { $symb= $env{'request.url'}; }
 4795:   }
 4796:   $symb=escape($symb);
 4797: 
 4798:   if (!$namespace) {
 4799:     # I don't think we would ever want to store this for a course.
 4800:     # it seems this will only be used if we don't have a course.
 4801:     #$namespace=$env{'request.course.id'};
 4802:     #if (!$namespace) {
 4803:       $namespace=$env{'request.state'};
 4804:     #}
 4805:   }
 4806:   $namespace=~s/\//\_/g;
 4807:   $namespace=~s/\W//g;
 4808:   if (!$domain) { $domain=$env{'user.domain'}; }
 4809:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4810:   if ($domain eq 'public' && $stuname eq 'public') {
 4811:       $stuname=$ENV{'REMOTE_ADDR'};
 4812:   }
 4813:   my $now=time;
 4814:   my %hash;
 4815:   my $path=LONCAPA::tempdir();
 4816:   if (tie(%hash,'GDBM_File',
 4817: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4818: 	  &GDBM_WRCREAT(),0640)) {
 4819:     $hash{"version:$symb"}++;
 4820:     my $version=$hash{"version:$symb"};
 4821:     my $allkeys=''; 
 4822:     foreach my $key (keys(%$storehash)) {
 4823:       $allkeys.=$key.':';
 4824:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4825:     }
 4826:     $hash{"$version:$symb:timestamp"}=$now;
 4827:     $allkeys.='timestamp';
 4828:     $hash{"$version:keys:$symb"}=$allkeys;
 4829:     if (untie(%hash)) {
 4830:       return 'ok';
 4831:     } else {
 4832:       return "error:$!";
 4833:     }
 4834:   } else {
 4835:     return "error:$!";
 4836:   }
 4837: }
 4838: 
 4839: # -----------------------------------------------------------------Temp Restore
 4840: 
 4841: sub tmprestore {
 4842:   my ($symb,$namespace,$domain,$stuname) = @_;
 4843: 
 4844:   if (!$symb) {
 4845:     $symb=&symbread();
 4846:     if (!$symb) { $symb= $env{'request.url'}; }
 4847:   }
 4848:   $symb=escape($symb);
 4849: 
 4850:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4851: 
 4852:   if (!$domain) { $domain=$env{'user.domain'}; }
 4853:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4854:   if ($domain eq 'public' && $stuname eq 'public') {
 4855:       $stuname=$ENV{'REMOTE_ADDR'};
 4856:   }
 4857:   my %returnhash;
 4858:   $namespace=~s/\//\_/g;
 4859:   $namespace=~s/\W//g;
 4860:   my %hash;
 4861:   my $path=LONCAPA::tempdir();
 4862:   if (tie(%hash,'GDBM_File',
 4863: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4864: 	  &GDBM_READER(),0640)) {
 4865:     my $version=$hash{"version:$symb"};
 4866:     $returnhash{'version'}=$version;
 4867:     my $scope;
 4868:     for ($scope=1;$scope<=$version;$scope++) {
 4869:       my $vkeys=$hash{"$scope:keys:$symb"};
 4870:       my @keys=split(/:/,$vkeys);
 4871:       my $key;
 4872:       $returnhash{"$scope:keys"}=$vkeys;
 4873:       foreach $key (@keys) {
 4874: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4875: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4876:       }
 4877:     }
 4878:     if (!(untie(%hash))) {
 4879:       return "error:$!";
 4880:     }
 4881:   } else {
 4882:     return "error:$!";
 4883:   }
 4884:   return %returnhash;
 4885: }
 4886: 
 4887: # ----------------------------------------------------------------------- Store
 4888: 
 4889: sub store {
 4890:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4891:     my $home='';
 4892: 
 4893:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4894: 
 4895:     $symb=&symbclean($symb);
 4896:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4897: 
 4898:     if (!$domain) { $domain=$env{'user.domain'}; }
 4899:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4900: 
 4901:     &devalidate($symb,$stuname,$domain);
 4902: 
 4903:     $symb=escape($symb);
 4904:     if (!$namespace) { 
 4905:        unless ($namespace=$env{'request.course.id'}) { 
 4906:           return ''; 
 4907:        } 
 4908:     }
 4909:     if (!$home) { $home=$env{'user.home'}; }
 4910: 
 4911:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4912:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4913: 
 4914:     my $namevalue='';
 4915:     foreach my $key (keys(%$storehash)) {
 4916:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4917:     }
 4918:     $namevalue=~s/\&$//;
 4919:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4920:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4921: }
 4922: 
 4923: # -------------------------------------------------------------- Critical Store
 4924: 
 4925: sub cstore {
 4926:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4927:     my $home='';
 4928: 
 4929:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4930: 
 4931:     $symb=&symbclean($symb);
 4932:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4933: 
 4934:     if (!$domain) { $domain=$env{'user.domain'}; }
 4935:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4936: 
 4937:     &devalidate($symb,$stuname,$domain);
 4938: 
 4939:     $symb=escape($symb);
 4940:     if (!$namespace) { 
 4941:        unless ($namespace=$env{'request.course.id'}) { 
 4942:           return ''; 
 4943:        } 
 4944:     }
 4945:     if (!$home) { $home=$env{'user.home'}; }
 4946: 
 4947:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4948:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4949: 
 4950:     my $namevalue='';
 4951:     foreach my $key (keys(%$storehash)) {
 4952:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4953:     }
 4954:     $namevalue=~s/\&$//;
 4955:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4956:     return critical
 4957:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4958: }
 4959: 
 4960: # --------------------------------------------------------------------- Restore
 4961: 
 4962: sub restore {
 4963:     my ($symb,$namespace,$domain,$stuname) = @_;
 4964:     my $home='';
 4965: 
 4966:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4967: 
 4968:     if (!$symb) {
 4969:         return if ($namespace eq 'courserequests');
 4970:         unless ($symb=escape(&symbread())) { return ''; }
 4971:     } else {
 4972:         unless ($namespace eq 'courserequests') {
 4973:             $symb=&escape(&symbclean($symb));
 4974:         }
 4975:     }
 4976:     if (!$namespace) { 
 4977:        unless ($namespace=$env{'request.course.id'}) { 
 4978:           return ''; 
 4979:        } 
 4980:     }
 4981:     if (!$domain) { $domain=$env{'user.domain'}; }
 4982:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4983:     if (!$home) { $home=$env{'user.home'}; }
 4984:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4985: 
 4986:     my %returnhash=();
 4987:     foreach my $line (split(/\&/,$answer)) {
 4988: 	my ($name,$value)=split(/\=/,$line);
 4989:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4990:     }
 4991:     my $version;
 4992:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4993:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4994:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4995:        }
 4996:     }
 4997:     return %returnhash;
 4998: }
 4999: 
 5000: # ---------------------------------------------------------- Course Description
 5001: #
 5002: #  
 5003: 
 5004: sub coursedescription {
 5005:     my ($courseid,$args)=@_;
 5006:     $courseid=~s/^\///;
 5007:     $courseid=~s/\_/\//g;
 5008:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5009:     my $chome=&homeserver($cnum,$cdomain);
 5010:     my $normalid=$cdomain.'_'.$cnum;
 5011:     # need to always cache even if we get errors otherwise we keep 
 5012:     # trying and trying and trying to get the course description.
 5013:     my %envhash=();
 5014:     my %returnhash=();
 5015:     
 5016:     my $expiretime=600;
 5017:     if ($env{'request.course.id'} eq $normalid) {
 5018: 	$expiretime=120;
 5019:     }
 5020: 
 5021:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5022:     if (!$args->{'freshen_cache'}
 5023: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5024: 	foreach my $key (keys(%env)) {
 5025: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5026: 	    my ($setting) = $1;
 5027: 	    $returnhash{$setting} = $env{$key};
 5028: 	}
 5029: 	return %returnhash;
 5030:     }
 5031: 
 5032:     # get the data again
 5033: 
 5034:     if (!$args->{'one_time'}) {
 5035: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5036:     }
 5037: 
 5038:     if ($chome ne 'no_host') {
 5039:        %returnhash=&dump('environment',$cdomain,$cnum);
 5040:        if (!exists($returnhash{'con_lost'})) {
 5041: 	   my $username = $env{'user.name'}; # Defult username
 5042: 	   if(defined $args->{'user'}) {
 5043: 	       $username = $args->{'user'};
 5044: 	   }
 5045:            $returnhash{'home'}= $chome;
 5046: 	   $returnhash{'domain'} = $cdomain;
 5047: 	   $returnhash{'num'} = $cnum;
 5048:            if (!defined($returnhash{'type'})) {
 5049:                $returnhash{'type'} = 'Course';
 5050:            }
 5051:            while (my ($name,$value) = each %returnhash) {
 5052:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5053:            }
 5054:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5055:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5056: 	       $username.'_'.$cdomain.'_'.$cnum;
 5057:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5058:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5059:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5060:        }
 5061:     }
 5062:     if (!$args->{'one_time'}) {
 5063: 	&appenv(\%envhash);
 5064:     }
 5065:     return %returnhash;
 5066: }
 5067: 
 5068: sub update_released_required {
 5069:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5070:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5071:         $cid = $env{'request.course.id'};
 5072:         $cdom = $env{'course.'.$cid.'.domain'};
 5073:         $cnum = $env{'course.'.$cid.'.num'};
 5074:         $chome = $env{'course.'.$cid.'.home'};
 5075:     }
 5076:     if ($needsrelease) {
 5077:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5078:         my $needsupdate;
 5079:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5080:             $needsupdate = 1;
 5081:         } else {
 5082:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5083:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5084:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5085:                 $needsupdate = 1;
 5086:             }
 5087:         }
 5088:         if ($needsupdate) {
 5089:             my %needshash = (
 5090:                              'internal.releaserequired' => $needsrelease,
 5091:                             );
 5092:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5093:             if ($putresult eq 'ok') {
 5094:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5095:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5096:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5097:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5098:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5099:                 }
 5100:             }
 5101:         }
 5102:     }
 5103:     return;
 5104: }
 5105: 
 5106: # -------------------------------------------------See if a user is privileged
 5107: 
 5108: sub privileged {
 5109:     my ($username,$domain,$possdomains,$possroles)=@_;
 5110:     my $now = time;
 5111:     my $roles;
 5112:     if (ref($possroles) eq 'ARRAY') {
 5113:         $roles = $possroles; 
 5114:     } else {
 5115:         $roles = ['dc','su'];
 5116:     }
 5117:     if (ref($possdomains) eq 'ARRAY') {
 5118:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5119:         foreach my $dom (@{$possdomains}) {
 5120:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5121:                 (ref($privileged{$dom}) eq 'HASH')) {
 5122:                 foreach my $role (@{$roles}) {
 5123:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5124:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5125:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5126:                             return 1 unless (($end && $end < $now) ||
 5127:                                              ($start && $start > $now));
 5128:                         }
 5129:                     }
 5130:                 }
 5131:             }
 5132:         }
 5133:     } else {
 5134:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5135:         my $now = time;
 5136: 
 5137:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5138:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5139:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5140:                 return 1 unless ($tend && $tend < $now) 
 5141:                         or ($tstart && $tstart > $now);
 5142:             }
 5143:         }
 5144:     }
 5145:     return 0;
 5146: }
 5147: 
 5148: sub privileged_by_domain {
 5149:     my ($domains,$roles) = @_;
 5150:     my %privileged = ();
 5151:     my $cachetime = 60*60*24;
 5152:     my $now = time;
 5153:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5154:         return %privileged;
 5155:     }
 5156:     foreach my $dom (@{$domains}) {
 5157:         next if (ref($privileged{$dom}) eq 'HASH');
 5158:         my $needroles;
 5159:         foreach my $role (@{$roles}) {
 5160:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5161:             if (defined($cached)) {
 5162:                 if (ref($result) eq 'HASH') {
 5163:                     $privileged{$dom}{$role} = $result;
 5164:                 }
 5165:             } else {
 5166:                 $needroles = 1;
 5167:             }
 5168:         }
 5169:         if ($needroles) {
 5170:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5171:             $privileged{$dom} = {};
 5172:             foreach my $server (keys(%dompersonnel)) {
 5173:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5174:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5175:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5176:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5177:                         next if ($end && $end < $now);
 5178:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5179:                             $dompersonnel{$server}{$item};
 5180:                     }
 5181:                 }
 5182:             }
 5183:             if (ref($privileged{$dom}) eq 'HASH') {
 5184:                 foreach my $role (@{$roles}) {
 5185:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5186:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5187:                     } else {
 5188:                         my %hash = ();
 5189:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5190:                     }
 5191:                 }
 5192:             }
 5193:         }
 5194:     }
 5195:     return %privileged;
 5196: }
 5197: 
 5198: # -------------------------------------------------------- Get user privileges
 5199: 
 5200: sub rolesinit {
 5201:     my ($domain, $username) = @_;
 5202:     my %userroles = ('user.login.time' => time);
 5203:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5204: 
 5205:     # firstaccess and timerinterval are related to timed maps/resources. 
 5206:     # also, blocking can be triggered by an activating timer
 5207:     # it's saved in the user's %env.
 5208:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5209:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5210:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5211:         %timerintchk, %timerintenv);
 5212: 
 5213:     foreach my $key (keys(%firstaccess)) {
 5214:         my ($cid, $rest) = split(/\0/, $key);
 5215:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5216:     }
 5217: 
 5218:     foreach my $key (keys(%timerinterval)) {
 5219:         my ($cid,$rest) = split(/\0/,$key);
 5220:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5221:     }
 5222: 
 5223:     my %allroles=();
 5224:     my %allgroups=();
 5225: 
 5226:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5227:         my $role = $rolesdump{$area};
 5228:         $area =~ s/\_\w\w$//;
 5229: 
 5230:         my ($trole, $tend, $tstart, $group_privs);
 5231: 
 5232:         if ($role =~ /^cr/) {
 5233:         # Custom role, defined by a user 
 5234:         # e.g., user.role.cr/msu/smith/mynewrole
 5235:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5236:                 $trole = $1;
 5237:                 ($tend, $tstart) = split('_', $2);
 5238:             } else {
 5239:                 $trole = $role;
 5240:             }
 5241:         } elsif ($role =~ m|^gr/|) {
 5242:         # Role of member in a group, defined within a course/community
 5243:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5244:             ($trole, $tend, $tstart) = split(/_/, $role);
 5245:             next if $tstart eq '-1';
 5246:             ($trole, $group_privs) = split(/\//, $trole);
 5247:             $group_privs = &unescape($group_privs);
 5248:         } else {
 5249:         # Just a normal role, defined in roles.tab
 5250:             ($trole, $tend, $tstart) = split(/_/,$role);
 5251:         }
 5252: 
 5253:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5254:                  $username);
 5255:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5256: 
 5257:         # role expired or not available yet?
 5258:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5259:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5260: 
 5261:         next if $area eq '' or $trole eq '';
 5262: 
 5263:         my $spec = "$trole.$area";
 5264:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5265: 
 5266:         if ($trole =~ /^cr\//) {
 5267:         # Custom role, defined by a user
 5268:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5269:         } elsif ($trole eq 'gr') {
 5270:         # Role of a member in a group, defined within a course/community
 5271:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5272:             next;
 5273:         } else {
 5274:         # Normal role, defined in roles.tab
 5275:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5276:         }
 5277: 
 5278:         my $cid = $tdomain.'_'.$trest;
 5279:         unless ($firstaccchk{$cid}) {
 5280:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5281:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5282:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5283:                         $coursetimerstarts{$cid}{$item}; 
 5284:                 }
 5285:             }
 5286:             $firstaccchk{$cid} = 1;
 5287:         }
 5288:         unless ($timerintchk{$cid}) {
 5289:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5290:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5291:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5292:                        $coursetimerintervals{$cid}{$item};
 5293:                 }
 5294:             }
 5295:             $timerintchk{$cid} = 1;
 5296:         }
 5297:     }
 5298: 
 5299:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5300:         \%allroles, \%allgroups);
 5301:     $env{'user.adv'} = $userroles{'user.adv'};
 5302: 
 5303:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5304: }
 5305: 
 5306: sub set_arearole {
 5307:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5308:     unless ($nolog) {
 5309: # log the associated role with the area
 5310:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5311:     }
 5312:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5313: }
 5314: 
 5315: sub custom_roleprivs {
 5316:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5317:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5318:     my $homsvr = &homeserver($rauthor,$rdomain);
 5319:     if (&hostname($homsvr) ne '') {
 5320:         my ($rdummy,$roledef)=
 5321:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5322:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5323:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5324:             if (defined($syspriv)) {
 5325:                 if ($trest =~ /^$match_community$/) {
 5326:                     $syspriv =~ s/bre\&S//; 
 5327:                 }
 5328:                 $$allroles{'cm./'}.=':'.$syspriv;
 5329:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5330:             }
 5331:             if ($tdomain ne '') {
 5332:                 if (defined($dompriv)) {
 5333:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5334:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5335:                 }
 5336:                 if (($trest ne '') && (defined($coursepriv))) {
 5337:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5338:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5339:                 }
 5340:             }
 5341:         }
 5342:     }
 5343: }
 5344: 
 5345: sub group_roleprivs {
 5346:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5347:     my $access = 1;
 5348:     my $now = time;
 5349:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5350:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5351:     if ($access) {
 5352:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5353:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5354:     }
 5355: }
 5356: 
 5357: sub standard_roleprivs {
 5358:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5359:     if (defined($pr{$trole.':s'})) {
 5360:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5361:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5362:     }
 5363:     if ($tdomain ne '') {
 5364:         if (defined($pr{$trole.':d'})) {
 5365:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5366:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5367:         }
 5368:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5369:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5370:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5371:         }
 5372:     }
 5373: }
 5374: 
 5375: sub set_userprivs {
 5376:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5377:     my $author=0;
 5378:     my $adv=0;
 5379:     my %grouproles = ();
 5380:     if (keys(%{$allgroups}) > 0) {
 5381:         my @groupkeys; 
 5382:         foreach my $role (keys(%{$allroles})) {
 5383:             push(@groupkeys,$role);
 5384:         }
 5385:         if (ref($groups_roles) eq 'HASH') {
 5386:             foreach my $key (keys(%{$groups_roles})) {
 5387:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5388:                     push(@groupkeys,$key);
 5389:                 }
 5390:             }
 5391:         }
 5392:         if (@groupkeys > 0) {
 5393:             foreach my $role (@groupkeys) {
 5394:                 my ($trole,$area,$sec,$extendedarea);
 5395:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5396:                     $trole = $1;
 5397:                     $area = $2;
 5398:                     $sec = $3;
 5399:                     $extendedarea = $area.$sec;
 5400:                     if (exists($$allgroups{$area})) {
 5401:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5402:                             my $spec = $trole.'.'.$extendedarea;
 5403:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5404:                                                 $$allgroups{$area}{$group};
 5405:                         }
 5406:                     }
 5407:                 }
 5408:             }
 5409:         }
 5410:     }
 5411:     foreach my $group (keys(%grouproles)) {
 5412:         $$allroles{$group} = $grouproles{$group};
 5413:     }
 5414:     foreach my $role (keys(%{$allroles})) {
 5415:         my %thesepriv;
 5416:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5417:         foreach my $item (split(/:/,$$allroles{$role})) {
 5418:             if ($item ne '') {
 5419:                 my ($privilege,$restrictions)=split(/&/,$item);
 5420:                 if ($restrictions eq '') {
 5421:                     $thesepriv{$privilege}='F';
 5422:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5423:                     $thesepriv{$privilege}.=$restrictions;
 5424:                 }
 5425:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5426:             }
 5427:         }
 5428:         my $thesestr='';
 5429:         foreach my $priv (sort(keys(%thesepriv))) {
 5430: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5431: 	}
 5432:         $userroles->{'user.priv.'.$role} = $thesestr;
 5433:     }
 5434:     return ($author,$adv);
 5435: }
 5436: 
 5437: sub role_status {
 5438:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5439:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5440:         my ($one,$two) = split(m{\./},$rolekey,2);
 5441:         (undef,undef,$$role) = split(/\./,$one,3);
 5442:         unless (!defined($$role) || $$role eq '') {
 5443:             $$where = '/'.$two;
 5444:             $$trolecode=$$role.'.'.$$where;
 5445:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5446:             $$tstatus='is';
 5447:             if ($$tstart && $$tstart>$update) {
 5448:                 $$tstatus='future';
 5449:                 if ($$tstart<$now) {
 5450:                     if ($$tstart && $$tstart>$refresh) {
 5451:                         if (($$where ne '') && ($$role ne '')) {
 5452:                             my (%allroles,%allgroups,$group_privs,
 5453:                                 %groups_roles,@rolecodes);
 5454:                             my %userroles = (
 5455:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5456:                             );
 5457:                             @rolecodes = ('cm'); 
 5458:                             my $spec=$$role.'.'.$$where;
 5459:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5460:                             if ($$role =~ /^cr\//) {
 5461:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5462:                                 push(@rolecodes,'cr');
 5463:                             } elsif ($$role eq 'gr') {
 5464:                                 push(@rolecodes,$$role);
 5465:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5466:                                                     $env{'user.name'});
 5467:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5468:                                 (undef,my $group_privs) = split(/\//,$trole);
 5469:                                 $group_privs = &unescape($group_privs);
 5470:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5471:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5472:                                 &get_groups_roles($tdomain,$trest,
 5473:                                                   \%course_roles,\@rolecodes,
 5474:                                                   \%groups_roles);
 5475:                             } else {
 5476:                                 push(@rolecodes,$$role);
 5477:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5478:                             }
 5479:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5480:                             &appenv(\%userroles,\@rolecodes);
 5481:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5482:                         }
 5483:                     }
 5484:                     $$tstatus = 'is';
 5485:                 }
 5486:             }
 5487:             if ($$tend) {
 5488:                 if ($$tend<$update) {
 5489:                     $$tstatus='expired';
 5490:                 } elsif ($$tend<$now) {
 5491:                     $$tstatus='will_not';
 5492:                 }
 5493:             }
 5494:         }
 5495:     }
 5496: }
 5497: 
 5498: sub get_groups_roles {
 5499:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5500:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5501:                   (ref($rolecodes) eq 'ARRAY') && 
 5502:                   (ref($groups_roles) eq 'HASH')); 
 5503:     if (keys(%{$cdom_courseroles}) > 0) {
 5504:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5505:         if ($cdom ne '' && $cnum ne '') {
 5506:             foreach my $key (keys(%{$cdom_courseroles})) {
 5507:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5508:                     my $crsrole = $1;
 5509:                     my $crssec = $2;
 5510:                     if ($crsrole =~ /^cr/) {
 5511:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5512:                             push(@{$rolecodes},'cr');
 5513:                         }
 5514:                     } else {
 5515:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5516:                             push(@{$rolecodes},$crsrole);
 5517:                         }
 5518:                     }
 5519:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5520:                     if ($crssec ne '') {
 5521:                         $rolekey .= "/$crssec";
 5522:                     }
 5523:                     $rolekey .= './';
 5524:                     $groups_roles->{$rolekey} = $rolecodes;
 5525:                 }
 5526:             }
 5527:         }
 5528:     }
 5529:     return;
 5530: }
 5531: 
 5532: sub delete_env_groupprivs {
 5533:     my ($where,$courseroles,$possroles) = @_;
 5534:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5535:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5536:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5537:         %{$courseroles->{$udom}} =
 5538:             &get_my_roles('','','userroles',['active'],
 5539:                           $possroles,[$udom],1);
 5540:     }
 5541:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5542:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5543:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5544:             my $area = '/'.$cdom.'/'.$cnum;
 5545:             my $privkey = "user.priv.$crsrole.$area";
 5546:             if ($crssec ne '') {
 5547:                 $privkey .= '/'.$crssec;
 5548:             }
 5549:             $privkey .= ".$area/$group";
 5550:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5551:         }
 5552:     }
 5553:     return;
 5554: }
 5555: 
 5556: sub check_adhoc_privs {
 5557:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5558:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5559:     my $setprivs;
 5560:     if ($env{$cckey}) {
 5561:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5562:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5563:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5564:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5565:             $setprivs = 1;
 5566:         }
 5567:     } else {
 5568:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5569:         $setprivs = 1;
 5570:     }
 5571:     return $setprivs;
 5572: }
 5573: 
 5574: sub set_adhoc_privileges {
 5575: # role can be cc or ca
 5576:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5577:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5578:     my $spec = $role.'.'.$area;
 5579:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5580:                                   $env{'user.name'},1);
 5581:     my %ccrole = ();
 5582:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5583:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5584:     &appenv(\%userroles,[$role,'cm']);
 5585:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5586:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5587:         &appenv( {'request.role'        => $spec,
 5588:                   'request.role.domain' => $dcdom,
 5589:                   'request.course.sec'  => ''
 5590:                  }
 5591:                );
 5592:         my $tadv=0;
 5593:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5594:         &appenv({'request.role.adv'    => $tadv});
 5595:     }
 5596: }
 5597: 
 5598: # --------------------------------------------------------------- get interface
 5599: 
 5600: sub get {
 5601:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5602:    my $items='';
 5603:    foreach my $item (@$storearr) {
 5604:        $items.=&escape($item).'&';
 5605:    }
 5606:    $items=~s/\&$//;
 5607:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5608:    if (!$uname) { $uname=$env{'user.name'}; }
 5609:    my $uhome=&homeserver($uname,$udomain);
 5610: 
 5611:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5612:    my @pairs=split(/\&/,$rep);
 5613:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5614:      return @pairs;
 5615:    }
 5616:    my %returnhash=();
 5617:    my $i=0;
 5618:    foreach my $item (@$storearr) {
 5619:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5620:       $i++;
 5621:    }
 5622:    return %returnhash;
 5623: }
 5624: 
 5625: # --------------------------------------------------------------- del interface
 5626: 
 5627: sub del {
 5628:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5629:    my $items='';
 5630:    foreach my $item (@$storearr) {
 5631:        $items.=&escape($item).'&';
 5632:    }
 5633: 
 5634:    $items=~s/\&$//;
 5635:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5636:    if (!$uname) { $uname=$env{'user.name'}; }
 5637:    my $uhome=&homeserver($uname,$udomain);
 5638:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5639: }
 5640: 
 5641: # -------------------------------------------------------------- dump interface
 5642: 
 5643: sub unserialize {
 5644:     my ($rep, $escapedkeys) = @_;
 5645: 
 5646:     return {} if $rep =~ /^error/;
 5647: 
 5648:     my %returnhash=();
 5649: 	foreach my $item (split(/\&/,$rep)) {
 5650: 	    my ($key, $value) = split(/=/, $item, 2);
 5651: 	    $key = unescape($key) unless $escapedkeys;
 5652: 	    next if $key =~ /^error: 2 /;
 5653: 	    $returnhash{$key} = &thaw_unescape($value);
 5654: 	}
 5655:     #return %returnhash;
 5656:     return \%returnhash;
 5657: }        
 5658: 
 5659: # see Lond::dump_with_regexp
 5660: # if $escapedkeys hash keys won't get unescaped.
 5661: sub dump {
 5662:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5663:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5664:     if (!$uname) { $uname=$env{'user.name'}; }
 5665:     my $uhome=&homeserver($uname,$udomain);
 5666: 
 5667:     if ($regexp) {
 5668:         $regexp=&escape($regexp);
 5669:     } else {
 5670:         $regexp='.';
 5671:     }
 5672:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5673:         # user is hosted on this machine
 5674:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5675:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5676:         return %{unserialize($reply, $escapedkeys)};
 5677:     }
 5678:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5679:     my @pairs=split(/\&/,$rep);
 5680:     my %returnhash=();
 5681:     if (!($rep =~ /^error/ )) {
 5682: 	foreach my $item (@pairs) {
 5683: 	    my ($key,$value)=split(/=/,$item,2);
 5684:         $key = unescape($key) unless $escapedkeys;
 5685:         #$key = &unescape($key);
 5686: 	    next if ($key =~ /^error: 2 /);
 5687: 	    $returnhash{$key}=&thaw_unescape($value);
 5688: 	}
 5689:     }
 5690:     return %returnhash;
 5691: }
 5692: 
 5693: 
 5694: # --------------------------------------------------------- dumpstore interface
 5695: 
 5696: sub dumpstore {
 5697:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5698:    # same as dump but keys must be escaped. They may contain colon separated
 5699:    # lists of values that may themself contain colons (e.g. symbs).
 5700:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5701: }
 5702: 
 5703: # -------------------------------------------------------------- keys interface
 5704: 
 5705: sub getkeys {
 5706:    my ($namespace,$udomain,$uname)=@_;
 5707:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5708:    if (!$uname) { $uname=$env{'user.name'}; }
 5709:    my $uhome=&homeserver($uname,$udomain);
 5710:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5711:    my @keyarray=();
 5712:    foreach my $key (split(/\&/,$rep)) {
 5713:       next if ($key =~ /^error: 2 /);
 5714:       push(@keyarray,&unescape($key));
 5715:    }
 5716:    return @keyarray;
 5717: }
 5718: 
 5719: # --------------------------------------------------------------- currentdump
 5720: sub currentdump {
 5721:    my ($courseid,$sdom,$sname)=@_;
 5722:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5723:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5724:    $sname    = $env{'user.name'}         if (! defined($sname));
 5725:    my $uhome = &homeserver($sname,$sdom);
 5726:    my $rep;
 5727: 
 5728:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5729:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5730:                    $courseid)));
 5731:    } else {
 5732:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5733:    }
 5734: 
 5735:    return if ($rep =~ /^(error:|no_such_host)/);
 5736:    #
 5737:    my %returnhash=();
 5738:    #
 5739:    if ($rep eq "unknown_cmd") { 
 5740:        # an old lond will not know currentdump
 5741:        # Do a dump and make it look like a currentdump
 5742:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5743:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5744:        my %hash = @tmp;
 5745:        @tmp=();
 5746:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5747:    } else {
 5748:        my @pairs=split(/\&/,$rep);
 5749:        foreach my $pair (@pairs) {
 5750:            my ($key,$value)=split(/=/,$pair,2);
 5751:            my ($symb,$param) = split(/:/,$key);
 5752:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5753:                                                         &thaw_unescape($value);
 5754:        }
 5755:    }
 5756:    return %returnhash;
 5757: }
 5758: 
 5759: sub convert_dump_to_currentdump{
 5760:     my %hash = %{shift()};
 5761:     my %returnhash;
 5762:     # Code ripped from lond, essentially.  The only difference
 5763:     # here is the unescaping done by lonnet::dump().  Conceivably
 5764:     # we might run in to problems with parameter names =~ /^v\./
 5765:     while (my ($key,$value) = each(%hash)) {
 5766:         my ($v,$symb,$param) = split(/:/,$key);
 5767: 	$symb  = &unescape($symb);
 5768: 	$param = &unescape($param);
 5769:         next if ($v eq 'version' || $symb eq 'keys');
 5770:         next if (exists($returnhash{$symb}) &&
 5771:                  exists($returnhash{$symb}->{$param}) &&
 5772:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5773:         $returnhash{$symb}->{$param}=$value;
 5774:         $returnhash{$symb}->{'v.'.$param}=$v;
 5775:     }
 5776:     #
 5777:     # Remove all of the keys in the hashes which keep track of
 5778:     # the version of the parameter.
 5779:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5780:         # use a foreach because we are going to delete from the hash.
 5781:         foreach my $key (keys(%$param_hash)) {
 5782:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5783:         }
 5784:     }
 5785:     return \%returnhash;
 5786: }
 5787: 
 5788: # ------------------------------------------------------ critical inc interface
 5789: 
 5790: sub cinc {
 5791:     return &inc(@_,'critical');
 5792: }
 5793: 
 5794: # --------------------------------------------------------------- inc interface
 5795: 
 5796: sub inc {
 5797:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5798:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5799:     if (!$uname) { $uname=$env{'user.name'}; }
 5800:     my $uhome=&homeserver($uname,$udomain);
 5801:     my $items='';
 5802:     if (! ref($store)) {
 5803:         # got a single value, so use that instead
 5804:         $items = &escape($store).'=&';
 5805:     } elsif (ref($store) eq 'SCALAR') {
 5806:         $items = &escape($$store).'=&';        
 5807:     } elsif (ref($store) eq 'ARRAY') {
 5808:         $items = join('=&',map {&escape($_);} @{$store});
 5809:     } elsif (ref($store) eq 'HASH') {
 5810:         while (my($key,$value) = each(%{$store})) {
 5811:             $items.= &escape($key).'='.&escape($value).'&';
 5812:         }
 5813:     }
 5814:     $items=~s/\&$//;
 5815:     if ($critical) {
 5816: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5817:     } else {
 5818: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5819:     }
 5820: }
 5821: 
 5822: # --------------------------------------------------------------- put interface
 5823: 
 5824: sub put {
 5825:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5826:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5827:    if (!$uname) { $uname=$env{'user.name'}; }
 5828:    my $uhome=&homeserver($uname,$udomain);
 5829:    my $items='';
 5830:    foreach my $item (keys(%$storehash)) {
 5831:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5832:    }
 5833:    $items=~s/\&$//;
 5834:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5835: }
 5836: 
 5837: # ------------------------------------------------------------ newput interface
 5838: 
 5839: sub newput {
 5840:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5841:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5842:    if (!$uname) { $uname=$env{'user.name'}; }
 5843:    my $uhome=&homeserver($uname,$udomain);
 5844:    my $items='';
 5845:    foreach my $key (keys(%$storehash)) {
 5846:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5847:    }
 5848:    $items=~s/\&$//;
 5849:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5850: }
 5851: 
 5852: # ---------------------------------------------------------  putstore interface
 5853: 
 5854: sub putstore {
 5855:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 5856:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5857:    if (!$uname) { $uname=$env{'user.name'}; }
 5858:    my $uhome=&homeserver($uname,$udomain);
 5859:    my $items='';
 5860:    foreach my $key (keys(%$storehash)) {
 5861:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5862:    }
 5863:    $items=~s/\&$//;
 5864:    my $esc_symb=&escape($symb);
 5865:    my $esc_v=&escape($version);
 5866:    my $reply =
 5867:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5868: 	      $uhome);
 5869:    if (($tolog) && ($reply eq 'ok')) {
 5870:        my $namevalue='';
 5871:        foreach my $key (keys(%{$storehash})) {
 5872:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5873:        }
 5874:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5875:                      '&host='.&escape($perlvar{'lonHostID'}).
 5876:                      '&version='.$esc_v.
 5877:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5878:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5879:    }
 5880:    if ($reply eq 'unknown_cmd') {
 5881:        # gfall back to way things use to be done
 5882:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5883: 			    $uname);
 5884:    }
 5885:    return $reply;
 5886: }
 5887: 
 5888: sub old_putstore {
 5889:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5890:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5891:     if (!$uname) { $uname=$env{'user.name'}; }
 5892:     my $uhome=&homeserver($uname,$udomain);
 5893:     my %newstorehash;
 5894:     foreach my $item (keys(%$storehash)) {
 5895: 	my $key = $version.':'.&escape($symb).':'.$item;
 5896: 	$newstorehash{$key} = $storehash->{$item};
 5897:     }
 5898:     my $items='';
 5899:     my %allitems = ();
 5900:     foreach my $item (keys(%newstorehash)) {
 5901: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5902: 	    my $key = $1.':keys:'.$2;
 5903: 	    $allitems{$key} .= $3.':';
 5904: 	}
 5905: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5906:     }
 5907:     foreach my $item (keys(%allitems)) {
 5908: 	$allitems{$item} =~ s/\:$//;
 5909: 	$items.= $item.'='.$allitems{$item}.'&';
 5910:     }
 5911:     $items=~s/\&$//;
 5912:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5913: }
 5914: 
 5915: # ------------------------------------------------------ critical put interface
 5916: 
 5917: sub cput {
 5918:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5919:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5920:    if (!$uname) { $uname=$env{'user.name'}; }
 5921:    my $uhome=&homeserver($uname,$udomain);
 5922:    my $items='';
 5923:    foreach my $item (keys(%$storehash)) {
 5924:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5925:    }
 5926:    $items=~s/\&$//;
 5927:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5928: }
 5929: 
 5930: # -------------------------------------------------------------- eget interface
 5931: 
 5932: sub eget {
 5933:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5934:    my $items='';
 5935:    foreach my $item (@$storearr) {
 5936:        $items.=&escape($item).'&';
 5937:    }
 5938:    $items=~s/\&$//;
 5939:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5940:    if (!$uname) { $uname=$env{'user.name'}; }
 5941:    my $uhome=&homeserver($uname,$udomain);
 5942:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5943:    my @pairs=split(/\&/,$rep);
 5944:    my %returnhash=();
 5945:    my $i=0;
 5946:    foreach my $item (@$storearr) {
 5947:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5948:       $i++;
 5949:    }
 5950:    return %returnhash;
 5951: }
 5952: 
 5953: # ------------------------------------------------------------ tmpput interface
 5954: sub tmpput {
 5955:     my ($storehash,$server,$context)=@_;
 5956:     my $items='';
 5957:     foreach my $item (keys(%$storehash)) {
 5958: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5959:     }
 5960:     $items=~s/\&$//;
 5961:     if (defined($context)) {
 5962:         $items .= ':'.&escape($context);
 5963:     }
 5964:     return &reply("tmpput:$items",$server);
 5965: }
 5966: 
 5967: # ------------------------------------------------------------ tmpget interface
 5968: sub tmpget {
 5969:     my ($token,$server)=@_;
 5970:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5971:     my $rep=&reply("tmpget:$token",$server);
 5972:     my %returnhash;
 5973:     foreach my $item (split(/\&/,$rep)) {
 5974: 	my ($key,$value)=split(/=/,$item);
 5975:         next if ($key =~ /^error: 2 /);
 5976: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5977:     }
 5978:     return %returnhash;
 5979: }
 5980: 
 5981: # ------------------------------------------------------------ tmpdel interface
 5982: sub tmpdel {
 5983:     my ($token,$server)=@_;
 5984:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5985:     return &reply("tmpdel:$token",$server);
 5986: }
 5987: 
 5988: # ------------------------------------------------------------ get_timebased_id 
 5989: 
 5990: sub get_timebased_id {
 5991:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5992:         $maxtries) = @_;
 5993:     my ($newid,$error,$dellock);
 5994:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5995:         return ('','ok','invalid call to get suffix');
 5996:     }
 5997: 
 5998: # set defaults for any optional args for which values were not supplied
 5999:     if ($who eq '') {
 6000:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6001:     }
 6002:     if (!$locktries) {
 6003:         $locktries = 3;
 6004:     }
 6005:     if (!$maxtries) {
 6006:         $maxtries = 10;
 6007:     }
 6008:     
 6009:     if (($cdom eq '') || ($cnum eq '')) {
 6010:         if ($env{'request.course.id'}) {
 6011:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6012:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6013:         }
 6014:         if (($cdom eq '') || ($cnum eq '')) {
 6015:             return ('','ok','call to get suffix not in course context');
 6016:         }
 6017:     }
 6018: 
 6019: # construct locking item
 6020:     my $lockhash = {
 6021:                       $prefix."\0".'locked_'.$keyid => $who,
 6022:                    };
 6023:     my $tries = 0;
 6024: 
 6025: # attempt to get lock on nohist_$namespace file
 6026:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6027:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6028:         $tries ++;
 6029:         sleep 1;
 6030:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6031:     }
 6032: 
 6033: # attempt to get unique identifier, based on current timestamp
 6034:     if ($gotlock eq 'ok') {
 6035:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6036:         my $id = time;
 6037:         $newid = $id;
 6038:         if ($idtype eq 'addcode') {
 6039:             $newid .= &sixnum_code();
 6040:         }
 6041:         my $idtries = 0;
 6042:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6043:             if ($idtype eq 'concat') {
 6044:                 $newid = $id.$idtries;
 6045:             } elsif ($idtype eq 'addcode') {
 6046:                 $newid = $newid.&sixnum_code();
 6047:             } else {
 6048:                 $newid ++;
 6049:             }
 6050:             $idtries ++;
 6051:         }
 6052:         if (!exists($inuse{$prefix."\0".$newid})) {
 6053:             my %new_item =  (
 6054:                               $prefix."\0".$newid => $who,
 6055:                             );
 6056:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6057:                                                  $cdom,$cnum);
 6058:             if ($putresult ne 'ok') {
 6059:                 undef($newid);
 6060:                 $error = 'error saving new item: '.$putresult;
 6061:             }
 6062:         } else {
 6063:              undef($newid);
 6064:              $error = ('error: no unique suffix available for the new item ');
 6065:         }
 6066: #  remove lock
 6067:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6068:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6069:     } else {
 6070:         $error = "error: could not obtain lockfile\n";
 6071:         $dellock = 'ok';
 6072:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6073:             $dellock = 'nolock';
 6074:         }
 6075:     }
 6076:     return ($newid,$dellock,$error);
 6077: }
 6078: 
 6079: sub sixnum_code {
 6080:     my $code;
 6081:     for (0..6) {
 6082:         $code .= int( rand(9) );
 6083:     }
 6084:     return $code;
 6085: }
 6086: 
 6087: # -------------------------------------------------- portfolio access checking
 6088: 
 6089: sub portfolio_access {
 6090:     my ($requrl,$clientip) = @_;
 6091:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6092:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6093:     if ($result) {
 6094:         my %setters;
 6095:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6096:             my ($startblock,$endblock) =
 6097:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6098:             if ($startblock && $endblock) {
 6099:                 return 'B';
 6100:             }
 6101:         } else {
 6102:             my ($startblock,$endblock) =
 6103:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6104:             if ($startblock && $endblock) {
 6105:                 return 'B';
 6106:             }
 6107:         }
 6108:     }
 6109:     if ($result eq 'ok') {
 6110:        return 'F';
 6111:     } elsif ($result =~ /^[^:]+:guest_/) {
 6112:        return 'A';
 6113:     }
 6114:     return '';
 6115: }
 6116: 
 6117: sub get_portfolio_access {
 6118:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6119: 
 6120:     if (!ref($access_hash)) {
 6121: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6122: 	my %access_controls = &get_access_controls($current_perms,$group,
 6123: 						   $file_name);
 6124: 	$access_hash = $access_controls{$file_name};
 6125:     }
 6126: 
 6127:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6128:     my $now = time;
 6129:     if (ref($access_hash) eq 'HASH') {
 6130:         foreach my $key (keys(%{$access_hash})) {
 6131:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6132:             if ($start > $now) {
 6133:                 next;
 6134:             }
 6135:             if ($end && $end<$now) {
 6136:                 next;
 6137:             }
 6138:             if ($scope eq 'public') {
 6139:                 $public = $key;
 6140:                 last;
 6141:             } elsif ($scope eq 'guest') {
 6142:                 $guest = $key;
 6143:             } elsif ($scope eq 'domains') {
 6144:                 push(@domains,$key);
 6145:             } elsif ($scope eq 'users') {
 6146:                 push(@users,$key);
 6147:             } elsif ($scope eq 'course') {
 6148:                 push(@courses,$key);
 6149:             } elsif ($scope eq 'group') {
 6150:                 push(@groups,$key);
 6151:             } elsif ($scope eq 'ip') {
 6152:                 push(@ips,$key);
 6153:             }
 6154:         }
 6155:         if ($public) {
 6156:             return 'ok';
 6157:         } elsif (@ips > 0) {
 6158:             my $allowed;
 6159:             foreach my $ipkey (@ips) {
 6160:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6161:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6162:                         $allowed = 1;
 6163:                         last; 
 6164:                     }
 6165:                 }
 6166:             }
 6167:             if ($allowed) {
 6168:                 return 'ok';
 6169:             }
 6170:         }
 6171:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6172:             if ($guest) {
 6173:                 return $guest;
 6174:             }
 6175:         } else {
 6176:             if (@domains > 0) {
 6177:                 foreach my $domkey (@domains) {
 6178:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6179:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6180:                             return 'ok';
 6181:                         }
 6182:                     }
 6183:                 }
 6184:             }
 6185:             if (@users > 0) {
 6186:                 foreach my $userkey (@users) {
 6187:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6188:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6189:                             if (ref($item) eq 'HASH') {
 6190:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6191:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6192:                                     return 'ok';
 6193:                                 }
 6194:                             }
 6195:                         }
 6196:                     } 
 6197:                 }
 6198:             }
 6199:             my %roleshash;
 6200:             my @courses_and_groups = @courses;
 6201:             push(@courses_and_groups,@groups); 
 6202:             if (@courses_and_groups > 0) {
 6203:                 my (%allgroups,%allroles); 
 6204:                 my ($start,$end,$role,$sec,$group);
 6205:                 foreach my $envkey (%env) {
 6206:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6207:                         my $cid = $2.'_'.$3; 
 6208:                         if ($1 eq 'gr') {
 6209:                             $group = $4;
 6210:                             $allgroups{$cid}{$group} = $env{$envkey};
 6211:                         } else {
 6212:                             if ($4 eq '') {
 6213:                                 $sec = 'none';
 6214:                             } else {
 6215:                                 $sec = $4;
 6216:                             }
 6217:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6218:                         }
 6219:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6220:                         my $cid = $2.'_'.$3;
 6221:                         if ($4 eq '') {
 6222:                             $sec = 'none';
 6223:                         } else {
 6224:                             $sec = $4;
 6225:                         }
 6226:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6227:                     }
 6228:                 }
 6229:                 if (keys(%allroles) == 0) {
 6230:                     return;
 6231:                 }
 6232:                 foreach my $key (@courses_and_groups) {
 6233:                     my %content = %{$$access_hash{$key}};
 6234:                     my $cnum = $content{'number'};
 6235:                     my $cdom = $content{'domain'};
 6236:                     my $cid = $cdom.'_'.$cnum;
 6237:                     if (!exists($allroles{$cid})) {
 6238:                         next;
 6239:                     }    
 6240:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6241:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6242:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6243:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6244:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6245:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6246:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6247:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6248:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6249:                                         if (grep/^all$/,@sections) {
 6250:                                             return 'ok';
 6251:                                         } else {
 6252:                                             if (grep/^$sec$/,@sections) {
 6253:                                                 return 'ok';
 6254:                                             }
 6255:                                         }
 6256:                                     }
 6257:                                 }
 6258:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6259:                                     if (grep/^none$/,@groups) {
 6260:                                         return 'ok';
 6261:                                     }
 6262:                                 } else {
 6263:                                     if (grep/^all$/,@groups) {
 6264:                                         return 'ok';
 6265:                                     } 
 6266:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6267:                                         if (grep/^$group$/,@groups) {
 6268:                                             return 'ok';
 6269:                                         }
 6270:                                     }
 6271:                                 } 
 6272:                             }
 6273:                         }
 6274:                     }
 6275:                 }
 6276:             }
 6277:             if ($guest) {
 6278:                 return $guest;
 6279:             }
 6280:         }
 6281:     }
 6282:     return;
 6283: }
 6284: 
 6285: sub course_group_datechecker {
 6286:     my ($dates,$now,$status) = @_;
 6287:     my ($start,$end) = split(/\./,$dates);
 6288:     if (!$start && !$end) {
 6289:         return 'ok';
 6290:     }
 6291:     if (grep/^active$/,@{$status}) {
 6292:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6293:             return 'ok';
 6294:         }
 6295:     }
 6296:     if (grep/^previous$/,@{$status}) {
 6297:         if ($end > $now ) {
 6298:             return 'ok';
 6299:         }
 6300:     }
 6301:     if (grep/^future$/,@{$status}) {
 6302:         if ($start > $now) {
 6303:             return 'ok';
 6304:         }
 6305:     }
 6306:     return; 
 6307: }
 6308: 
 6309: sub parse_portfolio_url {
 6310:     my ($url) = @_;
 6311: 
 6312:     my ($type,$udom,$unum,$group,$file_name);
 6313:     
 6314:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6315: 	$type = 1;
 6316:         $udom = $1;
 6317:         $unum = $2;
 6318:         $file_name = $3;
 6319:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6320: 	$type = 2;
 6321:         $udom = $1;
 6322:         $unum = $2;
 6323:         $group = $3;
 6324:         $file_name = $3.'/'.$4;
 6325:     }
 6326:     if (wantarray) {
 6327: 	return ($type,$udom,$unum,$file_name,$group);
 6328:     }
 6329:     return $type;
 6330: }
 6331: 
 6332: sub is_portfolio_url {
 6333:     my ($url) = @_;
 6334:     return scalar(&parse_portfolio_url($url));
 6335: }
 6336: 
 6337: sub is_portfolio_file {
 6338:     my ($file) = @_;
 6339:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6340:         return 1;
 6341:     }
 6342:     return;
 6343: }
 6344: 
 6345: sub usertools_access {
 6346:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6347:     my ($access,%tools);
 6348:     if ($context eq '') {
 6349:         $context = 'tools';
 6350:     }
 6351:     if ($context eq 'requestcourses') {
 6352:         %tools = (
 6353:                       official   => 1,
 6354:                       unofficial => 1,
 6355:                       community  => 1,
 6356:                       textbook   => 1,
 6357:                  );
 6358:     } elsif ($context eq 'requestauthor') {
 6359:         %tools = (
 6360:                       requestauthor => 1,
 6361:                  );
 6362:     } else {
 6363:         %tools = (
 6364:                       aboutme   => 1,
 6365:                       blog      => 1,
 6366:                       webdav    => 1,
 6367:                       portfolio => 1,
 6368:                  );
 6369:     }
 6370:     return if (!defined($tools{$tool}));
 6371: 
 6372:     if (($udom eq '') || ($uname eq '')) {
 6373:         $udom = $env{'user.domain'};
 6374:         $uname = $env{'user.name'};
 6375:     }
 6376: 
 6377:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6378:         if ($action ne 'reload') {
 6379:             if ($context eq 'requestcourses') {
 6380:                 return $env{'environment.canrequest.'.$tool};
 6381:             } elsif ($context eq 'requestauthor') {
 6382:                 return $env{'environment.canrequest.author'};
 6383:             } else {
 6384:                 return $env{'environment.availabletools.'.$tool};
 6385:             }
 6386:         }
 6387:     }
 6388: 
 6389:     my ($toolstatus,$inststatus,$envkey);
 6390:     if ($context eq 'requestauthor') {
 6391:         $envkey = $context; 
 6392:     } else {
 6393:         $envkey = $context.'.'.$tool;
 6394:     }
 6395: 
 6396:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6397:          ($action ne 'reload')) {
 6398:         $toolstatus = $env{'environment.'.$envkey};
 6399:         $inststatus = $env{'environment.inststatus'};
 6400:     } else {
 6401:         if (ref($userenvref) eq 'HASH') {
 6402:             $toolstatus = $userenvref->{$envkey};
 6403:             $inststatus = $userenvref->{'inststatus'};
 6404:         } else {
 6405:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6406:             $toolstatus = $userenv{$envkey};
 6407:             $inststatus = $userenv{'inststatus'};
 6408:         }
 6409:     }
 6410: 
 6411:     if ($toolstatus ne '') {
 6412:         if ($toolstatus) {
 6413:             $access = 1;
 6414:         } else {
 6415:             $access = 0;
 6416:         }
 6417:         return $access;
 6418:     }
 6419: 
 6420:     my ($is_adv,%domdef);
 6421:     if (ref($is_advref) eq 'HASH') {
 6422:         $is_adv = $is_advref->{'is_adv'};
 6423:     } else {
 6424:         $is_adv = &is_advanced_user($udom,$uname);
 6425:     }
 6426:     if (ref($domdefref) eq 'HASH') {
 6427:         %domdef = %{$domdefref};
 6428:     } else {
 6429:         %domdef = &get_domain_defaults($udom);
 6430:     }
 6431:     if (ref($domdef{$tool}) eq 'HASH') {
 6432:         if ($is_adv) {
 6433:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6434:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6435:                     $access = 1;
 6436:                 } else {
 6437:                     $access = 0;
 6438:                 }
 6439:                 return $access;
 6440:             }
 6441:         }
 6442:         if ($inststatus ne '') {
 6443:             my ($hasaccess,$hasnoaccess);
 6444:             foreach my $affiliation (split(/:/,$inststatus)) {
 6445:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6446:                     if ($domdef{$tool}{$affiliation}) {
 6447:                         $hasaccess = 1;
 6448:                     } else {
 6449:                         $hasnoaccess = 1;
 6450:                     }
 6451:                 }
 6452:             }
 6453:             if ($hasaccess || $hasnoaccess) {
 6454:                 if ($hasaccess) {
 6455:                     $access = 1;
 6456:                 } elsif ($hasnoaccess) {
 6457:                     $access = 0; 
 6458:                 }
 6459:                 return $access;
 6460:             }
 6461:         } else {
 6462:             if ($domdef{$tool}{'default'} ne '') {
 6463:                 if ($domdef{$tool}{'default'}) {
 6464:                     $access = 1;
 6465:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6466:                     $access = 0;
 6467:                 }
 6468:                 return $access;
 6469:             }
 6470:         }
 6471:     } else {
 6472:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6473:             $access = 1;
 6474:         } else {
 6475:             $access = 0;
 6476:         }
 6477:         return $access;
 6478:     }
 6479: }
 6480: 
 6481: sub is_course_owner {
 6482:     my ($cdom,$cnum,$udom,$uname) = @_;
 6483:     if (($udom eq '') || ($uname eq '')) {
 6484:         $udom = $env{'user.domain'};
 6485:         $uname = $env{'user.name'};
 6486:     }
 6487:     unless (($udom eq '') || ($uname eq '')) {
 6488:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6489:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6490:                 return 1;
 6491:             } else {
 6492:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6493:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6494:                     return 1;
 6495:                 }
 6496:             }
 6497:         }
 6498:     }
 6499:     return;
 6500: }
 6501: 
 6502: sub is_advanced_user {
 6503:     my ($udom,$uname) = @_;
 6504:     if ($udom ne '' && $uname ne '') {
 6505:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6506:             if (wantarray) {
 6507:                 return ($env{'user.adv'},$env{'user.author'});
 6508:             } else {
 6509:                 return $env{'user.adv'};
 6510:             }
 6511:         }
 6512:     }
 6513:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6514:     my %allroles;
 6515:     my ($is_adv,$is_author);
 6516:     foreach my $role (keys(%roleshash)) {
 6517:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6518:         my $area = '/'.$tdomain.'/'.$trest;
 6519:         if ($sec ne '') {
 6520:             $area .= '/'.$sec;
 6521:         }
 6522:         if (($area ne '') && ($trole ne '')) {
 6523:             my $spec=$trole.'.'.$area;
 6524:             if ($trole =~ /^cr\//) {
 6525:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6526:             } elsif ($trole ne 'gr') {
 6527:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6528:             }
 6529:             if ($trole eq 'au') {
 6530:                 $is_author = 1;
 6531:             }
 6532:         }
 6533:     }
 6534:     foreach my $role (keys(%allroles)) {
 6535:         last if ($is_adv);
 6536:         foreach my $item (split(/:/,$allroles{$role})) {
 6537:             if ($item ne '') {
 6538:                 my ($privilege,$restrictions)=split(/&/,$item);
 6539:                 if ($privilege eq 'adv') {
 6540:                     $is_adv = 1;
 6541:                     last;
 6542:                 }
 6543:             }
 6544:         }
 6545:     }
 6546:     if (wantarray) {
 6547:         return ($is_adv,$is_author);
 6548:     }
 6549:     return $is_adv;
 6550: }
 6551: 
 6552: sub check_can_request {
 6553:     my ($dom,$can_request,$request_domains) = @_;
 6554:     my $canreq = 0;
 6555:     my ($types,$typename) = &Apache::loncommon::course_types();
 6556:     my @options = ('approval','validate','autolimit');
 6557:     my $optregex = join('|',@options);
 6558:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6559:         foreach my $type (@{$types}) {
 6560:             if (&usertools_access($env{'user.name'},
 6561:                                   $env{'user.domain'},
 6562:                                   $type,undef,'requestcourses')) {
 6563:                 $canreq ++;
 6564:                 if (ref($request_domains) eq 'HASH') {
 6565:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6566:                 }
 6567:                 if ($dom eq $env{'user.domain'}) {
 6568:                     $can_request->{$type} = 1;
 6569:                 }
 6570:             }
 6571:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6572:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6573:                 if (@curr > 0) {
 6574:                     foreach my $item (@curr) {
 6575:                         if (ref($request_domains) eq 'HASH') {
 6576:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6577:                             if ($otherdom ne '') {
 6578:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6579:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6580:                                         push(@{$request_domains->{$type}},$otherdom);
 6581:                                     }
 6582:                                 } else {
 6583:                                     push(@{$request_domains->{$type}},$otherdom);
 6584:                                 }
 6585:                             }
 6586:                         }
 6587:                     }
 6588:                     unless($dom eq $env{'user.domain'}) {
 6589:                         $canreq ++;
 6590:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6591:                             $can_request->{$type} = 1;
 6592:                         }
 6593:                     }
 6594:                 }
 6595:             }
 6596:         }
 6597:     }
 6598:     return $canreq;
 6599: }
 6600: 
 6601: # ---------------------------------------------- Custom access rule evaluation
 6602: 
 6603: sub customaccess {
 6604:     my ($priv,$uri)=@_;
 6605:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6606:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6607:     $udom = &LONCAPA::clean_domain($udom);
 6608:     $ucrs = &LONCAPA::clean_username($ucrs);
 6609:     my $access=0;
 6610:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6611: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6612: 	if ($type eq 'user') {
 6613: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6614: 		my ($tdom,$tuname)=split(m{/},$scope);
 6615: 		if ($tdom) {
 6616: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6617: 		}
 6618: 		if ($tuname) {
 6619: 		    if ($tuname ne $env{'user.name'}) { next; }
 6620: 		}
 6621: 		$access=($effect eq 'allow');
 6622: 		last;
 6623: 	    }
 6624: 	} else {
 6625: 	    if ($role) {
 6626: 		if ($role ne $urole) { next; }
 6627: 	    }
 6628: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6629: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6630: 		if ($tdom) {
 6631: 		    if ($tdom ne $udom) { next; }
 6632: 		}
 6633: 		if ($tcrs) {
 6634: 		    if ($tcrs ne $ucrs) { next; }
 6635: 		}
 6636: 		if ($tsec) {
 6637: 		    if ($tsec ne $usec) { next; }
 6638: 		}
 6639: 		$access=($effect eq 'allow');
 6640: 		last;
 6641: 	    }
 6642: 	    if ($realm eq '' && $role eq '') {
 6643: 		$access=($effect eq 'allow');
 6644: 	    }
 6645: 	}
 6646:     }
 6647:     return $access;
 6648: }
 6649: 
 6650: # ------------------------------------------------- Check for a user privilege
 6651: 
 6652: sub allowed {
 6653:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 6654:     my $ver_orguri=$uri;
 6655:     $uri=&deversion($uri);
 6656:     my $orguri=$uri;
 6657:     $uri=&declutter($uri);
 6658: 
 6659:     if ($priv eq 'evb') {
 6660: # Evade communication block restrictions for specified role in a course
 6661:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6662:             return $1;
 6663:         } else {
 6664:             return;
 6665:         }
 6666:     }
 6667: 
 6668:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6669: # Free bre access to adm and meta resources
 6670:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6671: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6672: 	&& ($priv eq 'bre')) {
 6673: 	return 'F';
 6674:     }
 6675: 
 6676: # Free bre access to user's own portfolio contents
 6677:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6678:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6679: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6680:         my %setters;
 6681:         my ($startblock,$endblock) = 
 6682:             &Apache::loncommon::blockcheck(\%setters,'port');
 6683:         if ($startblock && $endblock) {
 6684:             return 'B';
 6685:         } else {
 6686:             return 'F';
 6687:         }
 6688:     }
 6689: 
 6690: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6691:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6692:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6693:         if (exists($env{'request.course.id'})) {
 6694:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6695:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6696:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6697:                 my $courseprivid=$env{'request.course.id'};
 6698:                 $courseprivid=~s/\_/\//;
 6699:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6700:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6701:                     return $1; 
 6702:                 } else {
 6703:                     if ($env{'request.course.sec'}) {
 6704:                         $courseprivid.='/'.$env{'request.course.sec'};
 6705:                     }
 6706:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6707:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6708:                         return $2;
 6709:                     }
 6710:                 }
 6711:             }
 6712:         }
 6713:     }
 6714: 
 6715: # Free bre to public access
 6716: 
 6717:     if ($priv eq 'bre') {
 6718:         my $copyright=&metadata($uri,'copyright');
 6719: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6720:            return 'F'; 
 6721:         }
 6722:         if ($copyright eq 'priv') {
 6723:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6724: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6725: 		return '';
 6726:             }
 6727:         }
 6728:         if ($copyright eq 'domain') {
 6729:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6730: 	    unless (($env{'user.domain'} eq $1) ||
 6731:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6732: 		return '';
 6733:             }
 6734:         }
 6735:         if ($env{'request.role'}=~ /li\.\//) {
 6736:             # Library role, so allow browsing of resources in this domain.
 6737:             return 'F';
 6738:         }
 6739:         if ($copyright eq 'custom') {
 6740: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6741:         }
 6742:     }
 6743:     # Domain coordinator is trying to create a course
 6744:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6745:         # uri is the requested domain in this case.
 6746:         # comparison to 'request.role.domain' shows if the user has selected
 6747:         # a role of dc for the domain in question.
 6748:         return 'F' if ($uri eq $env{'request.role.domain'});
 6749:     }
 6750: 
 6751:     my $thisallowed='';
 6752:     my $statecond=0;
 6753:     my $courseprivid='';
 6754: 
 6755:     my $ownaccess;
 6756:     # Community Coordinator or Assistant Co-author browsing resource space.
 6757:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6758:         if ($uri eq '') {
 6759:             $ownaccess = 1;
 6760:         } else {
 6761:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6762:                 my $udom = $env{'user.domain'};
 6763:                 my $uname = $env{'user.name'};
 6764:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6765:                     $ownaccess = 1;
 6766:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6767:                     unless ($uri =~ m{\.\./}) {
 6768:                         $ownaccess = 1;
 6769:                     }
 6770:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6771:                     my $now = time;
 6772:                     if ($uri =~ m{^([^/]+)/?$}) {
 6773:                         my $adom = $1;
 6774:                         foreach my $key (keys(%env)) {
 6775:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6776:                                 my ($start,$end) = split('.',$env{$key});
 6777:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6778:                                     $ownaccess = 1;
 6779:                                     last;
 6780:                                 }
 6781:                             }
 6782:                         }
 6783:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6784:                         my $adom = $1;
 6785:                         my $aname = $2;
 6786:                         foreach my $role ('ca','aa') { 
 6787:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6788:                                 my ($start,$end) =
 6789:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6790:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6791:                                     $ownaccess = 1;
 6792:                                     last;
 6793:                                 }
 6794:                             }
 6795:                         }
 6796:                     }
 6797:                 }
 6798:             }
 6799:         }
 6800:     }
 6801: 
 6802: # Course
 6803: 
 6804:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6805:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6806:             $thisallowed.=$1;
 6807:         }
 6808:     }
 6809: 
 6810: # Domain
 6811: 
 6812:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6813:        =~/\Q$priv\E\&([^\:]*)/) {
 6814:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6815:             $thisallowed.=$1;
 6816:         }
 6817:     }
 6818: 
 6819: # User who is not author or co-author might still be able to edit
 6820: # resource of an author in the domain (e.g., if Domain Coordinator).
 6821:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6822:         (&allowed('mdc',$env{'request.course.id'}))) {
 6823:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6824:             $thisallowed.=$1;
 6825:         }
 6826:     }
 6827: 
 6828: # Course: uri itself is a course
 6829:     my $courseuri=$uri;
 6830:     $courseuri=~s/\_(\d)/\/$1/;
 6831:     $courseuri=~s/^([^\/])/\/$1/;
 6832: 
 6833:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6834:        =~/\Q$priv\E\&([^\:]*)/) {
 6835:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6836:             $thisallowed.=$1;
 6837:         }
 6838:     }
 6839: 
 6840: # URI is an uploaded document for this course, default permissions don't matter
 6841: # not allowing 'edit' access (editupload) to uploaded course docs
 6842:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6843: 	$thisallowed='';
 6844:         my ($match)=&is_on_map($uri);
 6845:         if ($match) {
 6846:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6847:                   =~/\Q$priv\E\&([^\:]*)/) {
 6848:                 my $value = $1;
 6849:                 if ($noblockcheck) {
 6850:                     $thisallowed.=$value;
 6851:                 } else {
 6852:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6853:                     if (@blockers > 0) {
 6854:                         $thisallowed = 'B';
 6855:                     } else {
 6856:                         $thisallowed.=$value;
 6857:                     }
 6858:                 }
 6859:             }
 6860:         } else {
 6861:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6862:             if ($refuri) {
 6863:                 if ($refuri =~ m|^/adm/|) {
 6864:                     $thisallowed='F';
 6865:                 } else {
 6866:                     $refuri=&declutter($refuri);
 6867:                     my ($match) = &is_on_map($refuri);
 6868:                     if ($match) {
 6869:                         if ($noblockcheck) {
 6870:                             $thisallowed='F';
 6871:                         } else {
 6872:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6873:                             if (@blockers > 0) {
 6874:                                 $thisallowed = 'B';
 6875:                             } else {
 6876:                                 $thisallowed='F';
 6877:                             }
 6878:                         }
 6879:                     }
 6880:                 }
 6881:             }
 6882:         }
 6883:     }
 6884: 
 6885:     if ($priv eq 'bre'
 6886: 	&& $thisallowed ne 'F' 
 6887: 	&& $thisallowed ne '2'
 6888: 	&& &is_portfolio_url($uri)) {
 6889: 	$thisallowed = &portfolio_access($uri,$clientip);
 6890:     }
 6891: 
 6892: # Full access at system, domain or course-wide level? Exit.
 6893:     if ($thisallowed=~/F/) {
 6894: 	return 'F';
 6895:     }
 6896: 
 6897: # If this is generating or modifying users, exit with special codes
 6898: 
 6899:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6900: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6901: 	    my ($audom,$auname)=split('/',$uri);
 6902: # no author name given, so this just checks on the general right to make a co-author in this domain
 6903: 	    unless ($auname) { return $thisallowed; }
 6904: # an author name is given, so we are about to actually make a co-author for a certain account
 6905: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6906: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6907: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6908: 	}
 6909: 	return $thisallowed;
 6910:     }
 6911: #
 6912: # Gathered so far: system, domain and course wide privileges
 6913: #
 6914: # Course: See if uri or referer is an individual resource that is part of 
 6915: # the course
 6916: 
 6917:     if ($env{'request.course.id'}) {
 6918: 
 6919:        $courseprivid=$env{'request.course.id'};
 6920:        if ($env{'request.course.sec'}) {
 6921:           $courseprivid.='/'.$env{'request.course.sec'};
 6922:        }
 6923:        $courseprivid=~s/\_/\//;
 6924:        my $checkreferer=1;
 6925:        my ($match,$cond)=&is_on_map($uri);
 6926:        if ($match) {
 6927:            $statecond=$cond;
 6928:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6929:                =~/\Q$priv\E\&([^\:]*)/) {
 6930:                my $value = $1;
 6931:                if ($priv eq 'bre') {
 6932:                    if ($noblockcheck) {
 6933:                        $thisallowed.=$value;
 6934:                    } else {
 6935:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6936:                        if (@blockers > 0) {
 6937:                            $thisallowed = 'B';
 6938:                        } else {
 6939:                            $thisallowed.=$value;
 6940:                        }
 6941:                    }
 6942:                } else {
 6943:                    $thisallowed.=$value;
 6944:                }
 6945:                $checkreferer=0;
 6946:            }
 6947:        }
 6948:        
 6949:        if ($checkreferer) {
 6950: 	  my $refuri=$env{'httpref.'.$orguri};
 6951:             unless ($refuri) {
 6952:                 foreach my $key (keys(%env)) {
 6953: 		    if ($key=~/^httpref\..*\*/) {
 6954: 			my $pattern=$key;
 6955:                         $pattern=~s/^httpref\.\/res\///;
 6956:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6957:                         $pattern=~s/\//\\\//g;
 6958:                         if ($orguri=~/$pattern/) {
 6959: 			    $refuri=$env{$key};
 6960:                         }
 6961:                     }
 6962:                 }
 6963:             }
 6964: 
 6965:          if ($refuri) { 
 6966: 	  $refuri=&declutter($refuri);
 6967:           my ($match,$cond)=&is_on_map($refuri);
 6968:             if ($match) {
 6969:               my $refstatecond=$cond;
 6970:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6971:                   =~/\Q$priv\E\&([^\:]*)/) {
 6972:                   my $value = $1;
 6973:                   if ($priv eq 'bre') {
 6974:                       if ($noblockcheck) {
 6975:                           $thisallowed.=$value;
 6976:                       } else {
 6977:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6978:                           if (@blockers > 0) {
 6979:                               $thisallowed = 'B';
 6980:                           } else {
 6981:                               $thisallowed.=$value;
 6982:                           }
 6983:                       }
 6984:                   } else {
 6985:                       $thisallowed.=$value;
 6986:                   }
 6987:                   $uri=$refuri;
 6988:                   $statecond=$refstatecond;
 6989:               }
 6990:           }
 6991:         }
 6992:        }
 6993:    }
 6994: 
 6995: #
 6996: # Gathered now: all privileges that could apply, and condition number
 6997: # 
 6998: #
 6999: # Full or no access?
 7000: #
 7001: 
 7002:     if ($thisallowed=~/F/) {
 7003: 	return 'F';
 7004:     }
 7005: 
 7006:     unless ($thisallowed) {
 7007:         return '';
 7008:     }
 7009: 
 7010: # Restrictions exist, deal with them
 7011: #
 7012: #   C:according to course preferences
 7013: #   R:according to resource settings
 7014: #   L:unless locked
 7015: #   X:according to user session state
 7016: #
 7017: 
 7018: # Possibly locked functionality, check all courses
 7019: # Locks might take effect only after 10 minutes cache expiration for other
 7020: # courses, and 2 minutes for current course
 7021: 
 7022:     my $envkey;
 7023:     if ($thisallowed=~/L/) {
 7024:         foreach $envkey (keys(%env)) {
 7025:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7026:                my $courseid=$2;
 7027:                my $roleid=$1.'.'.$2;
 7028:                $courseid=~s/^\///;
 7029:                my $expiretime=600;
 7030:                if ($env{'request.role'} eq $roleid) {
 7031: 		  $expiretime=120;
 7032:                }
 7033: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7034:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7035:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7036: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7037:                }
 7038:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7039:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7040: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7041:                        &log($env{'user.domain'},$env{'user.name'},
 7042:                             $env{'user.home'},
 7043:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7044:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7045:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7046: 		       return '';
 7047:                    }
 7048:                }
 7049:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7050:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7051: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7052:                        &log($env{'user.domain'},$env{'user.name'},
 7053:                             $env{'user.home'},
 7054:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7055:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7056:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7057: 		       return '';
 7058:                    }
 7059:                }
 7060: 	   }
 7061:        }
 7062:     }
 7063:    
 7064: #
 7065: # Rest of the restrictions depend on selected course
 7066: #
 7067: 
 7068:     unless ($env{'request.course.id'}) {
 7069: 	if ($thisallowed eq 'A') {
 7070: 	    return 'A';
 7071:         } elsif ($thisallowed eq 'B') {
 7072:             return 'B';
 7073: 	} else {
 7074: 	    return '1';
 7075: 	}
 7076:     }
 7077: 
 7078: #
 7079: # Now user is definitely in a course
 7080: #
 7081: 
 7082: 
 7083: # Course preferences
 7084: 
 7085:    if ($thisallowed=~/C/) {
 7086:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7087:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7088:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7089: 	   =~/\Q$rolecode\E/) {
 7090: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7091: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7092: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7093: 			$env{'request.course.id'});
 7094: 	   }
 7095:            return '';
 7096:        }
 7097: 
 7098:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7099: 	   =~/\Q$unamedom\E/) {
 7100: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7101: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7102: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7103: 			$env{'request.course.id'});
 7104: 	   }
 7105:            return '';
 7106:        }
 7107:    }
 7108: 
 7109: # Resource preferences
 7110: 
 7111:    if ($thisallowed=~/R/) {
 7112:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7113:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7114: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7115: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7116: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7117: 	   }
 7118: 	   return '';
 7119:        }
 7120:    }
 7121: 
 7122: # Restricted by state or randomout?
 7123: 
 7124:    if ($thisallowed=~/X/) {
 7125:       if ($env{'acc.randomout'}) {
 7126: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7127:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7128:             return ''; 
 7129:          }
 7130:       }
 7131:       if (&condval($statecond)) {
 7132: 	 return '2';
 7133:       } else {
 7134:          return '';
 7135:       }
 7136:    }
 7137: 
 7138:     if ($thisallowed eq 'A') {
 7139: 	return 'A';
 7140:     } elsif ($thisallowed eq 'B') {
 7141:         return 'B';
 7142:     }
 7143:    return 'F';
 7144: }
 7145: 
 7146: # ------------------------------------------- Check construction space access
 7147: 
 7148: sub constructaccess {
 7149:     my ($url,$setpriv)=@_;
 7150: 
 7151: # We do not allow editing of previous versions of files
 7152:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7153: 
 7154: # Get username and domain from URL
 7155:     my ($ownername,$ownerdomain,$ownerhome);
 7156: 
 7157:     ($ownerdomain,$ownername) =
 7158:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7159: 
 7160: # The URL does not really point to any authorspace, forget it
 7161:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7162: 
 7163: # Now we need to see if the user has access to the authorspace of
 7164: # $ownername at $ownerdomain
 7165: 
 7166:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7167: # Real author for this?
 7168:        $ownerhome = $env{'user.home'};
 7169:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7170:           return ($ownername,$ownerdomain,$ownerhome);
 7171:        }
 7172:     } else {
 7173: # Co-author for this?
 7174:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7175:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7176:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7177:             return ($ownername,$ownerdomain,$ownerhome);
 7178:         }
 7179:     }
 7180: 
 7181: # We don't have any access right now. If we are not possibly going to do anything about this,
 7182: # we might as well leave
 7183:    unless ($setpriv) { return ''; }
 7184: 
 7185: # Backdoor access?
 7186:     my $allowed=&allowed('eco',$ownerdomain);
 7187: # Nope
 7188:     unless ($allowed) { return ''; }
 7189: # Looks like we may have access, but could be locked by the owner of the construction space
 7190:     if ($allowed eq 'U') {
 7191:         my %blocked=&get('environment',['domcoord.author'],
 7192:                          $ownerdomain,$ownername);
 7193: # Is blocked by owner
 7194:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7195:     }
 7196:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7197: # Grant temporary access
 7198:         my $then=$env{'user.login.time'};
 7199:         my $update=$env{'user.update.time'};
 7200:         if (!$update) { $update = $then; }
 7201:         my $refresh=$env{'user.refresh.time'};
 7202:         if (!$refresh) { $refresh = $update; }
 7203:         my $now = time;
 7204:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7205:                            $now,'ca','constructaccess');
 7206:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7207:         return($ownername,$ownerdomain,$ownerhome);
 7208:     }
 7209: # No business here
 7210:     return '';
 7211: }
 7212: 
 7213: # ----------------------------------------------------------- Content Blocking
 7214: 
 7215: {
 7216: # Caches for faster Course Contents display where content blocking
 7217: # is in operation (i.e., interval param set) for timed quiz.
 7218: #
 7219: # User for whom data are being temporarily cached.
 7220: my $cacheduser='';
 7221: # Cached blockers for this user (a hash of blocking items). 
 7222: my %cachedblockers=();
 7223: # When the data were last cached.
 7224: my $cachedlast='';
 7225: 
 7226: sub load_all_blockers {
 7227:     my ($uname,$udom,$blocks)=@_;
 7228:     if (($uname ne '') && ($udom ne '')) { 
 7229:         if (($cacheduser eq $uname.':'.$udom) &&
 7230:             (abs($cachedlast-time)<5)) {
 7231:             return;
 7232:         }
 7233:     }
 7234:     $cachedlast=time;
 7235:     $cacheduser=$uname.':'.$udom;
 7236:     %cachedblockers = &get_commblock_resources($blocks);
 7237: }
 7238: 
 7239: sub get_comm_blocks {
 7240:     my ($cdom,$cnum) = @_;
 7241:     if ($cdom eq '' || $cnum eq '') {
 7242:         return unless ($env{'request.course.id'});
 7243:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7244:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7245:     }
 7246:     my %commblocks;
 7247:     my $hashid=$cdom.'_'.$cnum;
 7248:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7249:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7250:         %commblocks = %{$blocksref};
 7251:     } else {
 7252:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7253:         my $cachetime = 600;
 7254:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7255:     }
 7256:     return %commblocks;
 7257: }
 7258: 
 7259: sub get_commblock_resources {
 7260:     my ($blocks) = @_;
 7261:     my %blockers = ();
 7262:     return %blockers unless ($env{'request.course.id'});
 7263:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7264:     my %commblocks;
 7265:     if (ref($blocks) eq 'HASH') {
 7266:         %commblocks = %{$blocks};
 7267:     } else {
 7268:         %commblocks = &get_comm_blocks();
 7269:     }
 7270:     return %blockers unless (keys(%commblocks) > 0); 
 7271:     my $navmap = Apache::lonnavmaps::navmap->new();
 7272:     return %blockers unless (ref($navmap));
 7273:     my $now = time;
 7274:     foreach my $block (keys(%commblocks)) {
 7275:         if ($block =~ /^(\d+)____(\d+)$/) {
 7276:             my ($start,$end) = ($1,$2);
 7277:             if ($start <= $now && $end >= $now) {
 7278:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7279:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7280:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7281:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7282:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 7283:                             }
 7284:                         }
 7285:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7286:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7287:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7288:                             }
 7289:                         }
 7290:                     }
 7291:                 }
 7292:             }
 7293:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7294:             my $item = $1;
 7295:             my @to_test;
 7296:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7297:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7298:                     my @interval;
 7299:                     my $type = 'map';
 7300:                     if ($item eq 'course') {
 7301:                         $type = 'course';
 7302:                         @interval=&EXT("resource.0.interval");
 7303:                     } else {
 7304:                         if ($item =~ /___\d+___/) {
 7305:                             $type = 'resource';
 7306:                             @interval=&EXT("resource.0.interval",$item);
 7307:                             if (ref($navmap)) {                        
 7308:                                 my $res = $navmap->getBySymb($item); 
 7309:                                 push(@to_test,$res);
 7310:                             }
 7311:                         } else {
 7312:                             my $mapsymb = &symbread($item,1);
 7313:                             if ($mapsymb) {
 7314:                                 if (ref($navmap)) {
 7315:                                     my $mapres = $navmap->getBySymb($mapsymb);
 7316:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 7317:                                     foreach my $res (@to_test) {
 7318:                                         my $symb = $res->symb();
 7319:                                         next if ($symb eq $mapsymb);
 7320:                                         if ($symb ne '') {
 7321:                                             @interval=&EXT("resource.0.interval",$symb);
 7322:                                             if ($interval[1] eq 'map') {
 7323:                                                 last;
 7324:                                             }
 7325:                                         }
 7326:                                     }
 7327:                                 }
 7328:                             }
 7329:                         }
 7330:                     }
 7331:                     if ($interval[0] =~ /^\d+$/) {
 7332:                         my $first_access;
 7333:                         if ($type eq 'resource') {
 7334:                             $first_access=&get_first_access($interval[1],$item);
 7335:                         } elsif ($type eq 'map') {
 7336:                             $first_access=&get_first_access($interval[1],undef,$item);
 7337:                         } else {
 7338:                             $first_access=&get_first_access($interval[1]);
 7339:                         }
 7340:                         if ($first_access) {
 7341:                             my $timesup = $first_access+$interval[0];
 7342:                             if ($timesup > $now) {
 7343:                                 my $activeblock;
 7344:                                 foreach my $res (@to_test) {
 7345:                                     if ($res->answerable()) {
 7346:                                         $activeblock = 1;
 7347:                                         last;
 7348:                                     }
 7349:                                 }
 7350:                                 if ($activeblock) {
 7351:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7352:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7353:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 7354:                                          }
 7355:                                     }
 7356:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7357:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7358:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7359:                                         }
 7360:                                     }
 7361:                                 }
 7362:                             }
 7363:                         }
 7364:                     }
 7365:                 }
 7366:             }
 7367:         }
 7368:     }
 7369:     return %blockers;
 7370: }
 7371: 
 7372: sub has_comm_blocking {
 7373:     my ($priv,$symb,$uri,$blocks) = @_;
 7374:     my @blockers;
 7375:     return unless ($env{'request.course.id'});
 7376:     return unless ($priv eq 'bre');
 7377:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7378:     return if ($env{'request.state'} eq 'construct');
 7379:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 7380:     return unless (keys(%cachedblockers) > 0);
 7381:     my (%possibles,@symbs);
 7382:     if (!$symb) {
 7383:         $symb = &symbread($uri,1,1,1,\%possibles);
 7384:     }
 7385:     if ($symb) {
 7386:         @symbs = ($symb);
 7387:     } elsif (keys(%possibles)) { 
 7388:         @symbs = keys(%possibles);
 7389:     }
 7390:     my $noblock;
 7391:     foreach my $symb (@symbs) {
 7392:         last if ($noblock);
 7393:         my ($map,$resid,$resurl)=&decode_symb($symb);
 7394:         foreach my $block (keys(%cachedblockers)) {
 7395:             if ($block =~ /^firstaccess____(.+)$/) {
 7396:                 my $item = $1;
 7397:                 if (($item eq $map) || ($item eq $symb)) {
 7398:                     $noblock = 1;
 7399:                     last;
 7400:                 }
 7401:             }
 7402:             if (ref($cachedblockers{$block}) eq 'HASH') {
 7403:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 7404:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 7405:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 7406:                             push(@blockers,$block);
 7407:                         }
 7408:                     }
 7409:                 }
 7410:             }
 7411:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 7412:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 7413:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 7414:                         push(@blockers,$block);
 7415:                     }
 7416:                 }
 7417:             }
 7418:         }
 7419:     }
 7420:     return if ($noblock);
 7421:     return @blockers;
 7422: }
 7423: }
 7424: 
 7425: # -------------------------------- Deversion and split uri into path an filename   
 7426: 
 7427: #
 7428: #   Removes the version from a URI and
 7429: #   splits it in to its filename and path to the filename.
 7430: #   Seems like File::Basename could have done this more clearly.
 7431: #   Parameters:
 7432: #      $uri   - input URI
 7433: #   Returns:
 7434: #     Two element list consisting of 
 7435: #     $pathname  - the URI up to and excluding the trailing /
 7436: #     $filename  - The part of the URI following the last /
 7437: #  NOTE:
 7438: #    Another realization of this is simply:
 7439: #    use File::Basename;
 7440: #    ...
 7441: #    $uri = shift;
 7442: #    $filename = basename($uri);
 7443: #    $path     = dirname($uri);
 7444: #    return ($filename, $path);
 7445: #
 7446: #     The implementation below is probably faster however.
 7447: #
 7448: sub split_uri_for_cond {
 7449:     my $uri=&deversion(&declutter(shift));
 7450:     my @uriparts=split(/\//,$uri);
 7451:     my $filename=pop(@uriparts);
 7452:     my $pathname=join('/',@uriparts);
 7453:     return ($pathname,$filename);
 7454: }
 7455: # --------------------------------------------------- Is a resource on the map?
 7456: 
 7457: sub is_on_map {
 7458:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7459:     #Trying to find the conditional for the file
 7460:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7461: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7462:     if ($match) {
 7463: 	return (1,$1);
 7464:     } else {
 7465: 	return (0,0);
 7466:     }
 7467: }
 7468: 
 7469: # --------------------------------------------------------- Get symb from alias
 7470: 
 7471: sub get_symb_from_alias {
 7472:     my $symb=shift;
 7473:     my ($map,$resid,$url)=&decode_symb($symb);
 7474: # Already is a symb
 7475:     if ($url) { return $symb; }
 7476: # Must be an alias
 7477:     my $aliassymb='';
 7478:     my %bighash;
 7479:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7480:                             &GDBM_READER(),0640)) {
 7481:         my $rid=$bighash{'mapalias_'.$symb};
 7482: 	if ($rid) {
 7483: 	    my ($mapid,$resid)=split(/\./,$rid);
 7484: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7485: 				    $resid,$bighash{'src_'.$rid});
 7486: 	}
 7487:         untie %bighash;
 7488:     }
 7489:     return $aliassymb;
 7490: }
 7491: 
 7492: # ----------------------------------------------------------------- Define Role
 7493: 
 7494: sub definerole {
 7495:   if (allowed('mcr','/')) {
 7496:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7497:     foreach my $role (split(':',$sysrole)) {
 7498: 	my ($crole,$cqual)=split(/\&/,$role);
 7499:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7500:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7501: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7502:                return "refused:s:$crole&$cqual"; 
 7503:             }
 7504:         }
 7505:     }
 7506:     foreach my $role (split(':',$domrole)) {
 7507: 	my ($crole,$cqual)=split(/\&/,$role);
 7508:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7509:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7510: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7511:                return "refused:d:$crole&$cqual"; 
 7512:             }
 7513:         }
 7514:     }
 7515:     foreach my $role (split(':',$courole)) {
 7516: 	my ($crole,$cqual)=split(/\&/,$role);
 7517:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7518:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7519: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7520:                return "refused:c:$crole&$cqual"; 
 7521:             }
 7522:         }
 7523:     }
 7524:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7525:                 "$env{'user.domain'}:$env{'user.name'}:".
 7526: 	        "rolesdef_$rolename=".
 7527:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7528:     return reply($command,$env{'user.home'});
 7529:   } else {
 7530:     return 'refused';
 7531:   }
 7532: }
 7533: 
 7534: # ---------------- Make a metadata query against the network of library servers
 7535: 
 7536: sub metadata_query {
 7537:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7538:     my %rhash;
 7539:     my %libserv = &all_library();
 7540:     my @server_list = (defined($server_array) ? @$server_array
 7541:                                               : keys(%libserv) );
 7542:     for my $server (@server_list) {
 7543:         my $domains = ''; 
 7544:         if (ref($domains_hash) eq 'HASH') {
 7545:             $domains = $domains_hash->{$server}; 
 7546:         }
 7547: 	unless ($custom or $customshow) {
 7548: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7549: 	    $rhash{$server}=$reply;
 7550: 	}
 7551: 	else {
 7552: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7553: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7554: 			     $server);
 7555: 	    $rhash{$server}=$reply;
 7556: 	}
 7557:     }
 7558:     return \%rhash;
 7559: }
 7560: 
 7561: # ----------------------------------------- Send log queries and wait for reply
 7562: 
 7563: sub log_query {
 7564:     my ($uname,$udom,$query,%filters)=@_;
 7565:     my $uhome=&homeserver($uname,$udom);
 7566:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7567:     my $uhost=&hostname($uhome);
 7568:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7569:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7570:                        $uhome);
 7571:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7572:     return get_query_reply($queryid);
 7573: }
 7574: 
 7575: # -------------------------- Update MySQL table for portfolio file
 7576: 
 7577: sub update_portfolio_table {
 7578:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7579:     if ($group ne '') {
 7580:         $file_name =~s /^\Q$group\E//;
 7581:     }
 7582:     my $homeserver = &homeserver($uname,$udom);
 7583:     my $queryid=
 7584:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7585:                ':'.&escape($file_name).':'.$action,$homeserver);
 7586:     my $reply = &get_query_reply($queryid);
 7587:     return $reply;
 7588: }
 7589: 
 7590: # -------------------------- Update MySQL allusers table
 7591: 
 7592: sub update_allusers_table {
 7593:     my ($uname,$udom,$names) = @_;
 7594:     my $homeserver = &homeserver($uname,$udom);
 7595:     my $queryid=
 7596:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7597:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7598:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7599:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7600:                'generation='.&escape($names->{'generation'}).'%%'.
 7601:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7602:                'id='.&escape($names->{'id'}),$homeserver);
 7603:     return;
 7604: }
 7605: 
 7606: # ------- Request retrieval of institutional classlists for course(s)
 7607: 
 7608: sub fetch_enrollment_query {
 7609:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7610:     my $homeserver;
 7611:     my $maxtries = 1;
 7612:     if ($context eq 'automated') {
 7613:         $homeserver = $perlvar{'lonHostID'};
 7614:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7615:     } else {
 7616:         $homeserver = &homeserver($cnum,$dom);
 7617:     }
 7618:     my $host=&hostname($homeserver);
 7619:     my $cmd = '';
 7620:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7621:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7622:     }
 7623:     $cmd =~ s/%%$//;
 7624:     $cmd = &escape($cmd);
 7625:     my $query = 'fetchenrollment';
 7626:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7627:     unless ($queryid=~/^\Q$host\E\_/) { 
 7628:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7629:         return 'error: '.$queryid;
 7630:     }
 7631:     my $reply = &get_query_reply($queryid);
 7632:     my $tries = 1;
 7633:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7634:         $reply = &get_query_reply($queryid);
 7635:         $tries ++;
 7636:     }
 7637:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7638:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7639:     } else {
 7640:         my @responses = split(/:/,$reply);
 7641:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7642:             foreach my $line (@responses) {
 7643:                 my ($key,$value) = split(/=/,$line,2);
 7644:                 $$replyref{$key} = $value;
 7645:             }
 7646:         } else {
 7647:             my $pathname = LONCAPA::tempdir();
 7648:             foreach my $line (@responses) {
 7649:                 my ($key,$value) = split(/=/,$line);
 7650:                 $$replyref{$key} = $value;
 7651:                 if ($value > 0) {
 7652:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7653:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7654:                         my $destname = $pathname.'/'.$filename;
 7655:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7656:                         if ($xml_classlist =~ /^error/) {
 7657:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7658:                         } else {
 7659:                             if ( open(FILE,">$destname") ) {
 7660:                                 print FILE &unescape($xml_classlist);
 7661:                                 close(FILE);
 7662:                             } else {
 7663:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7664:                             }
 7665:                         }
 7666:                     }
 7667:                 }
 7668:             }
 7669:         }
 7670:         return 'ok';
 7671:     }
 7672:     return 'error';
 7673: }
 7674: 
 7675: sub get_query_reply {
 7676:     my $queryid=shift;
 7677:     my $replyfile=LONCAPA::tempdir().$queryid;
 7678:     my $reply='';
 7679:     for (1..100) {
 7680: 	sleep 2;
 7681:         if (-e $replyfile.'.end') {
 7682: 	    if (open(my $fh,$replyfile)) {
 7683: 		$reply = join('',<$fh>);
 7684: 		close($fh);
 7685: 	   } else { return 'error: reply_file_error'; }
 7686:            return &unescape($reply);
 7687: 	}
 7688:     }
 7689:     return 'timeout:'.$queryid;
 7690: }
 7691: 
 7692: sub courselog_query {
 7693: #
 7694: # possible filters:
 7695: # url: url or symb
 7696: # username
 7697: # domain
 7698: # action: view, submit, grade
 7699: # start: timestamp
 7700: # end: timestamp
 7701: #
 7702:     my (%filters)=@_;
 7703:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7704:     if ($filters{'url'}) {
 7705: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7706:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7707:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7708:     }
 7709:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7710:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7711:     return &log_query($cname,$cdom,'courselog',%filters);
 7712: }
 7713: 
 7714: sub userlog_query {
 7715: #
 7716: # possible filters:
 7717: # action: log check role
 7718: # start: timestamp
 7719: # end: timestamp
 7720: #
 7721:     my ($uname,$udom,%filters)=@_;
 7722:     return &log_query($uname,$udom,'userlog',%filters);
 7723: }
 7724: 
 7725: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7726: 
 7727: sub auto_run {
 7728:     my ($cnum,$cdom) = @_;
 7729:     my $response = 0;
 7730:     my $settings;
 7731:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7732:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7733:         $settings = $domconfig{'autoenroll'};
 7734:         if ($settings->{'run'} eq '1') {
 7735:             $response = 1;
 7736:         }
 7737:     } else {
 7738:         my $homeserver;
 7739:         if (&is_course($cdom,$cnum)) {
 7740:             $homeserver = &homeserver($cnum,$cdom);
 7741:         } else {
 7742:             $homeserver = &domain($cdom,'primary');
 7743:         }
 7744:         if ($homeserver ne 'no_host') {
 7745:             $response = &reply('autorun:'.$cdom,$homeserver);
 7746:         }
 7747:     }
 7748:     return $response;
 7749: }
 7750: 
 7751: sub auto_get_sections {
 7752:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7753:     my $homeserver;
 7754:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7755:         $homeserver = &homeserver($cnum,$cdom);
 7756:     }
 7757:     if (!defined($homeserver)) { 
 7758:         if ($cdom =~ /^$match_domain$/) {
 7759:             $homeserver = &domain($cdom,'primary');
 7760:         }
 7761:     }
 7762:     my @secs;
 7763:     if (defined($homeserver)) {
 7764:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7765:         unless ($response eq 'refused') {
 7766:             @secs = split(/:/,$response);
 7767:         }
 7768:     }
 7769:     return @secs;
 7770: }
 7771: 
 7772: sub auto_new_course {
 7773:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7774:     my $homeserver = &homeserver($cnum,$cdom);
 7775:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7776:     return $response;
 7777: }
 7778: 
 7779: sub auto_validate_courseID {
 7780:     my ($cnum,$cdom,$inst_course_id) = @_;
 7781:     my $homeserver = &homeserver($cnum,$cdom);
 7782:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7783:     return $response;
 7784: }
 7785: 
 7786: sub auto_validate_instcode {
 7787:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7788:     my ($homeserver,$response);
 7789:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7790:         $homeserver = &homeserver($cnum,$cdom);
 7791:     }
 7792:     if (!defined($homeserver)) {
 7793:         if ($cdom =~ /^$match_domain$/) {
 7794:             $homeserver = &domain($cdom,'primary');
 7795:         }
 7796:     }
 7797:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7798:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7799:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7800:     return ($outcome,$description,$defaultcredits);
 7801: }
 7802: 
 7803: sub auto_create_password {
 7804:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7805:     my ($homeserver,$response);
 7806:     my $create_passwd = 0;
 7807:     my $authchk = '';
 7808:     if ($udom =~ /^$match_domain$/) {
 7809:         $homeserver = &domain($udom,'primary');
 7810:     }
 7811:     if ($homeserver eq '') {
 7812:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7813:             $homeserver = &homeserver($cnum,$cdom);
 7814:         }
 7815:     }
 7816:     if ($homeserver eq '') {
 7817:         $authchk = 'nodomain';
 7818:     } else {
 7819:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7820:         if ($response eq 'refused') {
 7821:             $authchk = 'refused';
 7822:         } else {
 7823:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7824:         }
 7825:     }
 7826:     return ($authparam,$create_passwd,$authchk);
 7827: }
 7828: 
 7829: sub auto_photo_permission {
 7830:     my ($cnum,$cdom,$students) = @_;
 7831:     my $homeserver = &homeserver($cnum,$cdom);
 7832:     my ($outcome,$perm_reqd,$conditions) = 
 7833: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7834:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7835: 	return (undef,undef);
 7836:     }
 7837:     return ($outcome,$perm_reqd,$conditions);
 7838: }
 7839: 
 7840: sub auto_checkphotos {
 7841:     my ($uname,$udom,$pid) = @_;
 7842:     my $homeserver = &homeserver($uname,$udom);
 7843:     my ($result,$resulttype);
 7844:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7845: 				   &escape($uname).':'.&escape($pid),
 7846: 				   $homeserver));
 7847:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7848: 	return (undef,undef);
 7849:     }
 7850:     if ($outcome) {
 7851:         ($result,$resulttype) = split(/:/,$outcome);
 7852:     } 
 7853:     return ($result,$resulttype);
 7854: }
 7855: 
 7856: sub auto_photochoice {
 7857:     my ($cnum,$cdom) = @_;
 7858:     my $homeserver = &homeserver($cnum,$cdom);
 7859:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7860: 						       &escape($cdom),
 7861: 						       $homeserver)));
 7862:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7863: 	return (undef,undef);
 7864:     }
 7865:     return ($update,$comment);
 7866: }
 7867: 
 7868: sub auto_photoupdate {
 7869:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7870:     my $homeserver = &homeserver($cnum,$dom);
 7871:     my $host=&hostname($homeserver);
 7872:     my $cmd = '';
 7873:     my $maxtries = 1;
 7874:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7875:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7876:     }
 7877:     $cmd =~ s/%%$//;
 7878:     $cmd = &escape($cmd);
 7879:     my $query = 'institutionalphotos';
 7880:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7881:     unless ($queryid=~/^\Q$host\E\_/) {
 7882:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7883:         return 'error: '.$queryid;
 7884:     }
 7885:     my $reply = &get_query_reply($queryid);
 7886:     my $tries = 1;
 7887:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7888:         $reply = &get_query_reply($queryid);
 7889:         $tries ++;
 7890:     }
 7891:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7892:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7893:     } else {
 7894:         my @responses = split(/:/,$reply);
 7895:         my $outcome = shift(@responses); 
 7896:         foreach my $item (@responses) {
 7897:             my ($key,$value) = split(/=/,$item);
 7898:             $$photo{$key} = $value;
 7899:         }
 7900:         return $outcome;
 7901:     }
 7902:     return 'error';
 7903: }
 7904: 
 7905: sub auto_instcode_format {
 7906:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7907: 	$cat_order) = @_;
 7908:     my $courses = '';
 7909:     my @homeservers;
 7910:     if ($caller eq 'global') {
 7911: 	my %servers = &get_servers($codedom,'library');
 7912: 	foreach my $tryserver (keys(%servers)) {
 7913: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7914: 		push(@homeservers,$tryserver);
 7915: 	    }
 7916:         }
 7917:     } elsif ($caller eq 'requests') {
 7918:         if ($codedom =~ /^$match_domain$/) {
 7919:             my $chome = &domain($codedom,'primary');
 7920:             unless ($chome eq 'no_host') {
 7921:                 push(@homeservers,$chome);
 7922:             }
 7923:         }
 7924:     } else {
 7925:         push(@homeservers,&homeserver($caller,$codedom));
 7926:     }
 7927:     foreach my $code (keys(%{$instcodes})) {
 7928:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7929:     }
 7930:     chop($courses);
 7931:     my $ok_response = 0;
 7932:     my $response;
 7933:     while (@homeservers > 0 && $ok_response == 0) {
 7934:         my $server = shift(@homeservers); 
 7935:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7936:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7937:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7938: 		split(/:/,$response);
 7939:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7940:             push(@{$codetitles},&str2array($codetitles_str));
 7941:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7942:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7943:             $ok_response = 1;
 7944:         }
 7945:     }
 7946:     if ($ok_response) {
 7947:         return 'ok';
 7948:     } else {
 7949:         return $response;
 7950:     }
 7951: }
 7952: 
 7953: sub auto_instcode_defaults {
 7954:     my ($domain,$returnhash,$code_order) = @_;
 7955:     my @homeservers;
 7956: 
 7957:     my %servers = &get_servers($domain,'library');
 7958:     foreach my $tryserver (keys(%servers)) {
 7959: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7960: 	    push(@homeservers,$tryserver);
 7961: 	}
 7962:     }
 7963: 
 7964:     my $response;
 7965:     foreach my $server (@homeservers) {
 7966:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7967:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7968: 	
 7969: 	foreach my $pair (split(/\&/,$response)) {
 7970: 	    my ($name,$value)=split(/\=/,$pair);
 7971: 	    if ($name eq 'code_order') {
 7972: 		@{$code_order} = split(/\&/,&unescape($value));
 7973: 	    } else {
 7974: 		$returnhash->{&unescape($name)}=&unescape($value);
 7975: 	    }
 7976: 	}
 7977: 	return 'ok';
 7978:     }
 7979: 
 7980:     return $response;
 7981: }
 7982: 
 7983: sub auto_possible_instcodes {
 7984:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7985:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7986:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7987:         return;
 7988:     }
 7989:     my (@homeservers,$uhome);
 7990:     if (defined(&domain($domain,'primary'))) {
 7991:         $uhome=&domain($domain,'primary');
 7992:         push(@homeservers,&domain($domain,'primary'));
 7993:     } else {
 7994:         my %servers = &get_servers($domain,'library');
 7995:         foreach my $tryserver (keys(%servers)) {
 7996:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7997:                 push(@homeservers,$tryserver);
 7998:             }
 7999:         }
 8000:     }
 8001:     my $response;
 8002:     foreach my $server (@homeservers) {
 8003:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8004:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8005:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8006:             split(':',$response);
 8007:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8008:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8009:         foreach my $item (split('&',$cat_title)) {   
 8010:             my ($name,$value)=split('=',$item);
 8011:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8012:         }
 8013:         foreach my $item (split('&',$cat_order)) {
 8014:             my ($name,$value)=split('=',$item);
 8015:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8016:         }
 8017:         return 'ok';
 8018:     }
 8019:     return $response;
 8020: }
 8021: 
 8022: sub auto_courserequest_checks {
 8023:     my ($dom) = @_;
 8024:     my ($homeserver,%validations);
 8025:     if ($dom =~ /^$match_domain$/) {
 8026:         $homeserver = &domain($dom,'primary');
 8027:     }
 8028:     unless ($homeserver eq 'no_host') {
 8029:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8030:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8031:             my @items = split(/&/,$response);
 8032:             foreach my $item (@items) {
 8033:                 my ($key,$value) = split('=',$item);
 8034:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8035:             }
 8036:         }
 8037:     }
 8038:     return %validations; 
 8039: }
 8040: 
 8041: sub auto_courserequest_validation {
 8042:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8043:     my ($homeserver,$response);
 8044:     if ($dom =~ /^$match_domain$/) {
 8045:         $homeserver = &domain($dom,'primary');
 8046:     }
 8047:     unless ($homeserver eq 'no_host') {
 8048:         my $customdata;
 8049:         if (ref($custominfo) eq 'HASH') {
 8050:             $customdata = &freeze_escape($custominfo);
 8051:         }
 8052:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8053:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8054:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8055:                                     $customdata,$homeserver));
 8056:     }
 8057:     return $response;
 8058: }
 8059: 
 8060: sub auto_validate_class_sec {
 8061:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8062:     my $homeserver = &homeserver($cnum,$cdom);
 8063:     my $ownerlist;
 8064:     if (ref($owners) eq 'ARRAY') {
 8065:         $ownerlist = join(',',@{$owners});
 8066:     } else {
 8067:         $ownerlist = $owners;
 8068:     }
 8069:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8070:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8071:     return $response;
 8072: }
 8073: 
 8074: sub auto_crsreq_update {
 8075:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8076:         $code,$accessstart,$accessend,$inbound) = @_;
 8077:     my ($homeserver,%crsreqresponse);
 8078:     if ($cdom =~ /^$match_domain$/) {
 8079:         $homeserver = &domain($cdom,'primary');
 8080:     }
 8081:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8082:         my $info;
 8083:         if (ref($inbound) eq 'HASH') {
 8084:             $info = &freeze_escape($inbound);
 8085:         }
 8086:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8087:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8088:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8089:                             &escape($title).':'.&escape($code).':'.
 8090:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8091:                             $homeserver);
 8092:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8093:             my @items = split(/&/,$response);
 8094:             foreach my $item (@items) {
 8095:                 my ($key,$value) = split('=',$item);
 8096:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8097:             }
 8098:         }
 8099:     }
 8100:     return \%crsreqresponse;
 8101: }
 8102: 
 8103: # ------------------------------------------------------- Course Group routines
 8104: 
 8105: sub get_coursegroups {
 8106:     my ($cdom,$cnum,$group,$namespace) = @_;
 8107:     return(&dump($namespace,$cdom,$cnum,$group));
 8108: }
 8109: 
 8110: sub modify_coursegroup {
 8111:     my ($cdom,$cnum,$groupsettings) = @_;
 8112:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8113: }
 8114: 
 8115: sub toggle_coursegroup_status {
 8116:     my ($cdom,$cnum,$group,$action) = @_;
 8117:     my ($from_namespace,$to_namespace);
 8118:     if ($action eq 'delete') {
 8119:         $from_namespace = 'coursegroups';
 8120:         $to_namespace = 'deleted_groups';
 8121:     } else {
 8122:         $from_namespace = 'deleted_groups';
 8123:         $to_namespace = 'coursegroups';
 8124:     }
 8125:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8126:     if (my $tmp = &error(%curr_group)) {
 8127:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8128:         return ('read error',$tmp);
 8129:     } else {
 8130:         my %savedsettings = %curr_group; 
 8131:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8132:         my $deloutcome;
 8133:         if ($result eq 'ok') {
 8134:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8135:         } else {
 8136:             return ('write error',$result);
 8137:         }
 8138:         if ($deloutcome eq 'ok') {
 8139:             return 'ok';
 8140:         } else {
 8141:             return ('delete error',$deloutcome);
 8142:         }
 8143:     }
 8144: }
 8145: 
 8146: sub modify_group_roles {
 8147:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8148:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8149:     my $role = 'gr/'.&escape($userprivs);
 8150:     my ($uname,$udom) = split(/:/,$user);
 8151:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8152:     if ($result eq 'ok') {
 8153:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8154:     }
 8155:     return $result;
 8156: }
 8157: 
 8158: sub modify_coursegroup_membership {
 8159:     my ($cdom,$cnum,$membership) = @_;
 8160:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8161:     return $result;
 8162: }
 8163: 
 8164: sub get_active_groups {
 8165:     my ($udom,$uname,$cdom,$cnum) = @_;
 8166:     my $now = time;
 8167:     my %groups = ();
 8168:     foreach my $key (keys(%env)) {
 8169:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8170:             my ($start,$end) = split(/\./,$env{$key});
 8171:             if (($end!=0) && ($end<$now)) { next; }
 8172:             if (($start!=0) && ($start>$now)) { next; }
 8173:             if ($1 eq $cdom && $2 eq $cnum) {
 8174:                 $groups{$3} = $env{$key} ;
 8175:             }
 8176:         }
 8177:     }
 8178:     return %groups;
 8179: }
 8180: 
 8181: sub get_group_membership {
 8182:     my ($cdom,$cnum,$group) = @_;
 8183:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8184: }
 8185: 
 8186: sub get_users_groups {
 8187:     my ($udom,$uname,$courseid) = @_;
 8188:     my @usersgroups;
 8189:     my $cachetime=1800;
 8190: 
 8191:     my $hashid="$udom:$uname:$courseid";
 8192:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8193:     if (defined($cached)) {
 8194:         @usersgroups = split(/:/,$grouplist);
 8195:     } else {  
 8196:         $grouplist = '';
 8197:         my $courseurl = &courseid_to_courseurl($courseid);
 8198:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8199:         my $access_end = $env{'course.'.$courseid.
 8200:                               '.default_enrollment_end_date'};
 8201:         my $now = time;
 8202:         foreach my $key (keys(%roleshash)) {
 8203:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8204:                 my $group = $1;
 8205:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8206:                     my $start = $2;
 8207:                     my $end = $1;
 8208:                     if ($start == -1) { next; } # deleted from group
 8209:                     if (($start!=0) && ($start>$now)) { next; }
 8210:                     if (($end!=0) && ($end<$now)) {
 8211:                         if ($access_end && $access_end < $now) {
 8212:                             if ($access_end - $end < 86400) {
 8213:                                 push(@usersgroups,$group);
 8214:                             }
 8215:                         }
 8216:                         next;
 8217:                     }
 8218:                     push(@usersgroups,$group);
 8219:                 }
 8220:             }
 8221:         }
 8222:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8223:         $grouplist = join(':',@usersgroups);
 8224:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8225:     }
 8226:     return @usersgroups;
 8227: }
 8228: 
 8229: sub devalidate_getgroups_cache {
 8230:     my ($udom,$uname,$cdom,$cnum)=@_;
 8231:     my $courseid = $cdom.'_'.$cnum;
 8232: 
 8233:     my $hashid="$udom:$uname:$courseid";
 8234:     &devalidate_cache_new('getgroups',$hashid);
 8235: }
 8236: 
 8237: # ------------------------------------------------------------------ Plain Text
 8238: 
 8239: sub plaintext {
 8240:     my ($short,$type,$cid,$forcedefault) = @_;
 8241:     if ($short =~ m{^cr/}) {
 8242: 	return (split('/',$short))[-1];
 8243:     }
 8244:     if (!defined($cid)) {
 8245:         $cid = $env{'request.course.id'};
 8246:     }
 8247:     my %rolenames = (
 8248:                       Course    => 'std',
 8249:                       Community => 'alt1',
 8250:                     );
 8251:     if ($cid ne '') {
 8252:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8253:             unless ($forcedefault) {
 8254:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8255:                 &Apache::lonlocal::mt_escape(\$roletext);
 8256:                 return &Apache::lonlocal::mt($roletext);
 8257:             }
 8258:         }
 8259:     }
 8260:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8261:         (defined($rolenames{$type})) && 
 8262:         (defined($prp{$short}{$rolenames{$type}}))) {
 8263:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8264:     } elsif ($cid ne '') {
 8265:         my $crstype = $env{'course.'.$cid.'.type'};
 8266:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8267:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8268:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8269:         }
 8270:     }
 8271:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8272: }
 8273: 
 8274: # ----------------------------------------------------------------- Assign Role
 8275: 
 8276: sub assignrole {
 8277:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8278:         $context)=@_;
 8279:     my $mrole;
 8280:     if ($role =~ /^cr\//) {
 8281:         my $cwosec=$url;
 8282:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8283: 	unless (&allowed('ccr',$cwosec)) {
 8284:            my $refused = 1;
 8285:            if ($context eq 'requestcourses') {
 8286:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8287:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8288:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8289:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8290:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8291:                            if ($crsenv{'internal.courseowner'} eq
 8292:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8293:                                $refused = '';
 8294:                            }
 8295:                        }
 8296:                    }
 8297:                }
 8298:            }
 8299:            if ($refused) {
 8300:                &logthis('Refused custom assignrole: '.
 8301:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8302:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8303:                return 'refused';
 8304:            }
 8305:         }
 8306:         $mrole='cr';
 8307:     } elsif ($role =~ /^gr\//) {
 8308:         my $cwogrp=$url;
 8309:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8310:         unless (&allowed('mdg',$cwogrp)) {
 8311:             &logthis('Refused group assignrole: '.
 8312:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8313:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8314:             return 'refused';
 8315:         }
 8316:         $mrole='gr';
 8317:     } else {
 8318:         my $cwosec=$url;
 8319:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8320:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8321:             my $refused;
 8322:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8323:                 if (!(&allowed('c'.$role,$url))) {
 8324:                     $refused = 1;
 8325:                 }
 8326:             } else {
 8327:                 $refused = 1;
 8328:             }
 8329:             if ($refused) {
 8330:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8331:                 if (!$selfenroll && $context eq 'course') {
 8332:                     my %crsenv;
 8333:                     if ($role eq 'cc' || $role eq 'co') {
 8334:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8335:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8336:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8337:                                 if ($crsenv{'internal.courseowner'} eq 
 8338:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8339:                                     $refused = '';
 8340:                                 }
 8341:                             }
 8342:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8343:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8344:                                 if ($crsenv{'internal.courseowner'} eq 
 8345:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8346:                                     $refused = '';
 8347:                                 }
 8348:                             }
 8349:                         }
 8350:                     }
 8351:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8352:                     $refused = '';
 8353:                 } elsif ($context eq 'requestcourses') {
 8354:                     my @possroles = ('st','ta','ep','in','cc','co');
 8355:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8356:                         my $wrongcc;
 8357:                         if ($cnum =~ /^$match_community$/) {
 8358:                             $wrongcc = 1 if ($role eq 'cc');
 8359:                         } else {
 8360:                             $wrongcc = 1 if ($role eq 'co');
 8361:                         }
 8362:                         unless ($wrongcc) {
 8363:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8364:                             if ($crsenv{'internal.courseowner'} eq 
 8365:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8366:                                 $refused = '';
 8367:                             }
 8368:                         }
 8369:                     }
 8370:                 } elsif ($context eq 'requestauthor') {
 8371:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8372:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8373:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8374:                             $refused = '';
 8375:                         } else {
 8376:                             my %domdefaults = &get_domain_defaults($udom);
 8377:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8378:                                 my $checkbystatus;
 8379:                                 if ($env{'user.adv'}) { 
 8380:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8381:                                     if ($disposition eq 'automatic') {
 8382:                                         $refused = '';
 8383:                                     } elsif ($disposition eq '') {
 8384:                                         $checkbystatus = 1;
 8385:                                     } 
 8386:                                 } else {
 8387:                                     $checkbystatus = 1;
 8388:                                 }
 8389:                                 if ($checkbystatus) {
 8390:                                     if ($env{'environment.inststatus'}) {
 8391:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8392:                                         foreach my $type (@inststatuses) {
 8393:                                             if (($type ne '') &&
 8394:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8395:                                                 $refused = '';
 8396:                                             }
 8397:                                         }
 8398:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8399:                                         $refused = '';
 8400:                                     }
 8401:                                 }
 8402:                             }
 8403:                         }
 8404:                     }
 8405:                 }
 8406:                 if ($refused) {
 8407:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8408:                              ' '.$role.' '.$end.' '.$start.' by '.
 8409: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8410:                     return 'refused';
 8411:                 }
 8412:             }
 8413:         } elsif ($role eq 'au') {
 8414:             if ($url ne '/'.$udom.'/') {
 8415:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8416:                          ' to assign author role for '.$uname.':'.$udom.
 8417:                          ' in domain: '.$url.' refused (wrong domain).');
 8418:                 return 'refused';
 8419:             }
 8420:         }
 8421:         $mrole=$role;
 8422:     }
 8423:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8424:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8425:     if ($end) { $command.='_'.$end; }
 8426:     if ($start) {
 8427: 	if ($end) { 
 8428:            $command.='_'.$start; 
 8429:         } else {
 8430:            $command.='_0_'.$start;
 8431:         }
 8432:     }
 8433:     my $origstart = $start;
 8434:     my $origend = $end;
 8435:     my $delflag;
 8436: # actually delete
 8437:     if ($deleteflag) {
 8438: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8439: # modify command to delete the role
 8440:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8441:                 "$udom:$uname:$url".'_'."$mrole";
 8442: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8443: # set start and finish to negative values for userrolelog
 8444:            $start=-1;
 8445:            $end=-1;
 8446:            $delflag = 1;
 8447:         }
 8448:     }
 8449: # send command
 8450:     my $answer=&reply($command,&homeserver($uname,$udom));
 8451: # log new user role if status is ok
 8452:     if ($answer eq 'ok') {
 8453: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8454:         if (($role eq 'cc') || ($role eq 'in') ||
 8455:             ($role eq 'ep') || ($role eq 'ad') ||
 8456:             ($role eq 'ta') || ($role eq 'st') ||
 8457:             ($role=~/^cr/) || ($role eq 'gr') ||
 8458:             ($role eq 'co')) {
 8459: # for course roles, perform group memberships changes triggered by role change.
 8460:             unless ($role =~ /^gr/) {
 8461:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8462:                                                  $origstart,$selfenroll,$context);
 8463:             }
 8464:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8465:                            $selfenroll,$context);
 8466:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8467:                  ($role eq 'au') || ($role eq 'dc')) {
 8468:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8469:                            $context);
 8470:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8471:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8472:                              $context); 
 8473:         }
 8474:         if ($role eq 'cc') {
 8475:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8476:         }
 8477:     }
 8478:     return $answer;
 8479: }
 8480: 
 8481: sub autoupdate_coowners {
 8482:     my ($url,$end,$start,$uname,$udom) = @_;
 8483:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8484:     if (($cdom ne '') && ($cnum ne '')) {
 8485:         my $now = time;
 8486:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8487:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8488:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8489:             my $instcode = $coursehash{'internal.coursecode'};
 8490:             if ($instcode ne '') {
 8491:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8492:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8493:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8494:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8495:                         if ($result eq 'valid') {
 8496:                             if ($coursehash{'internal.co-owners'}) {
 8497:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8498:                                     push(@newcoowners,$coowner);
 8499:                                 }
 8500:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8501:                                     push(@newcoowners,$uname.':'.$udom);
 8502:                                 }
 8503:                                 @newcoowners = sort(@newcoowners);
 8504:                             } else {
 8505:                                 push(@newcoowners,$uname.':'.$udom);
 8506:                             }
 8507:                         } else {
 8508:                             if ($coursehash{'internal.co-owners'}) {
 8509:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8510:                                     unless ($coowner eq $uname.':'.$udom) {
 8511:                                         push(@newcoowners,$coowner);
 8512:                                     }
 8513:                                 }
 8514:                                 unless (@newcoowners > 0) {
 8515:                                     $delcoowners = 1;
 8516:                                     $coowners = '';
 8517:                                 }
 8518:                             }
 8519:                         }
 8520:                         if (@newcoowners || $delcoowners) {
 8521:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8522:                                             $delcoowners,@newcoowners);
 8523:                         }
 8524:                     }
 8525:                 }
 8526:             }
 8527:         }
 8528:     }
 8529: }
 8530: 
 8531: sub store_coowners {
 8532:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8533:     my $cid = $cdom.'_'.$cnum;
 8534:     my ($coowners,$delresult,$putresult);
 8535:     if (@newcoowners) {
 8536:         $coowners = join(',',@newcoowners);
 8537:         my %coownershash = (
 8538:                             'internal.co-owners' => $coowners,
 8539:                            );
 8540:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8541:         if ($putresult eq 'ok') {
 8542:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8543:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8544:             }
 8545:         }
 8546:     }
 8547:     if ($delcoowners) {
 8548:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8549:         if ($delresult eq 'ok') {
 8550:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8551:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8552:             }
 8553:         }
 8554:     }
 8555:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8556:         my %crsinfo =
 8557:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8558:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8559:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8560:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8561:         }
 8562:     }
 8563: }
 8564: 
 8565: # -------------------------------------------------- Modify user authentication
 8566: # Overrides without validation
 8567: 
 8568: sub modifyuserauth {
 8569:     my ($udom,$uname,$umode,$upass)=@_;
 8570:     my $uhome=&homeserver($uname,$udom);
 8571:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8572:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8573:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8574:              ' in domain '.$env{'request.role.domain'});  
 8575:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8576: 		     &escape($upass),$uhome);
 8577:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8578:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8579:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8580:     &log($udom,,$uname,$uhome,
 8581:         'Authentication changed by '.$env{'user.domain'}.', '.
 8582:                                      $env{'user.name'}.', '.$umode.
 8583:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8584:     unless ($reply eq 'ok') {
 8585:         &logthis('Authentication mode error: '.$reply);
 8586: 	return 'error: '.$reply;
 8587:     }   
 8588:     return 'ok';
 8589: }
 8590: 
 8591: # --------------------------------------------------------------- Modify a user
 8592: 
 8593: sub modifyuser {
 8594:     my ($udom,    $uname, $uid,
 8595:         $umode,   $upass, $first,
 8596:         $middle,  $last,  $gene,
 8597:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8598:     $udom= &LONCAPA::clean_domain($udom);
 8599:     $uname=&LONCAPA::clean_username($uname);
 8600:     my $showcandelete = 'none';
 8601:     if (ref($candelete) eq 'ARRAY') {
 8602:         if (@{$candelete} > 0) {
 8603:             $showcandelete = join(', ',@{$candelete});
 8604:         }
 8605:     }
 8606:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8607:              $umode.', '.$first.', '.$middle.', '.
 8608: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8609:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8610:                                      ' desiredhome not specified'). 
 8611:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8612:              ' in domain '.$env{'request.role.domain'});
 8613:     my $uhome=&homeserver($uname,$udom,'true');
 8614:     my $newuser;
 8615:     if ($uhome eq 'no_host') {
 8616:         $newuser = 1;
 8617:     }
 8618: # ----------------------------------------------------------------- Create User
 8619:     if (($uhome eq 'no_host') && 
 8620: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8621:         my $unhome='';
 8622:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8623:             $unhome = $desiredhome;
 8624: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8625: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8626:         } else { # load balancing routine for determining $unhome
 8627:             my $loadm=10000000;
 8628: 	    my %servers = &get_servers($udom,'library');
 8629: 	    foreach my $tryserver (keys(%servers)) {
 8630: 		my $answer=reply('load',$tryserver);
 8631: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8632: 		    $loadm=$answer;
 8633: 		    $unhome=$tryserver;
 8634: 		}
 8635: 	    }
 8636:         }
 8637:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8638: 	    return 'error: unable to find a home server for '.$uname.
 8639:                    ' in domain '.$udom;
 8640:         }
 8641:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8642:                          &escape($upass),$unhome);
 8643: 	unless ($reply eq 'ok') {
 8644:             return 'error: '.$reply;
 8645:         }   
 8646:         $uhome=&homeserver($uname,$udom,'true');
 8647:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8648: 	    return 'error: unable verify users home machine.';
 8649:         }
 8650:     }   # End of creation of new user
 8651: # ---------------------------------------------------------------------- Add ID
 8652:     if ($uid) {
 8653:        $uid=~tr/A-Z/a-z/;
 8654:        my %uidhash=&idrget($udom,$uname);
 8655:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8656:          && (!$forceid)) {
 8657: 	  unless ($uid eq $uidhash{$uname}) {
 8658: 	      return 'error: user id "'.$uid.'" does not match '.
 8659:                   'current user id "'.$uidhash{$uname}.'".';
 8660:           }
 8661:        } else {
 8662: 	  &idput($udom,($uname => $uid));
 8663:        }
 8664:     }
 8665: # -------------------------------------------------------------- Add names, etc
 8666:     my @tmp=&get('environment',
 8667: 		   ['firstname','middlename','lastname','generation','id',
 8668:                     'permanentemail','inststatus'],
 8669: 		   $udom,$uname);
 8670:     my (%names,%oldnames);
 8671:     if ($tmp[0] =~ m/^error:.*/) { 
 8672:         %names=(); 
 8673:     } else {
 8674:         %names = @tmp;
 8675:         %oldnames = %names;
 8676:     }
 8677: #
 8678: # If name, email and/or uid are blank (e.g., because an uploaded file
 8679: # of users did not contain them), do not overwrite existing values
 8680: # unless field is in $candelete array ref.  
 8681: #
 8682: 
 8683:     my @fields = ('firstname','middlename','lastname','generation',
 8684:                   'permanentemail','id');
 8685:     my %newvalues;
 8686:     if (ref($candelete) eq 'ARRAY') {
 8687:         foreach my $field (@fields) {
 8688:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8689:                 if ($field eq 'firstname') {
 8690:                     $names{$field} = $first;
 8691:                 } elsif ($field eq 'middlename') {
 8692:                     $names{$field} = $middle;
 8693:                 } elsif ($field eq 'lastname') {
 8694:                     $names{$field} = $last;
 8695:                 } elsif ($field eq 'generation') { 
 8696:                     $names{$field} = $gene;
 8697:                 } elsif ($field eq 'permanentemail') {
 8698:                     $names{$field} = $email;
 8699:                 } elsif ($field eq 'id') {
 8700:                     $names{$field}  = $uid;
 8701:                 }
 8702:             }
 8703:         }
 8704:     }
 8705:     if ($first)  { $names{'firstname'}  = $first; }
 8706:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8707:     if ($last)   { $names{'lastname'}   = $last; }
 8708:     if (defined($gene))   { $names{'generation'} = $gene; }
 8709:     if ($email) {
 8710:        $email=~s/[^\w\@\.\-\,]//gs;
 8711:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8712:     }
 8713:     if ($uid) { $names{'id'}  = $uid; }
 8714:     if (defined($inststatus)) {
 8715:         $names{'inststatus'} = '';
 8716:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8717:         if (ref($usertypes) eq 'HASH') {
 8718:             my @okstatuses; 
 8719:             foreach my $item (split(/:/,$inststatus)) {
 8720:                 if (defined($usertypes->{$item})) {
 8721:                     push(@okstatuses,$item);  
 8722:                 }
 8723:             }
 8724:             if (@okstatuses) {
 8725:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8726:             }
 8727:         }
 8728:     }
 8729:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8730:                  $umode.', '.$first.', '.$middle.', '.
 8731:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8732:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8733:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8734:     } else {
 8735:         $logmsg .= ' during self creation';
 8736:     }
 8737:     my $changed;
 8738:     if ($newuser) {
 8739:         $changed = 1;
 8740:     } else {
 8741:         foreach my $field (@fields) {
 8742:             if ($names{$field} ne $oldnames{$field}) {
 8743:                 $changed = 1;
 8744:                 last;
 8745:             }
 8746:         }
 8747:     }
 8748:     unless ($changed) {
 8749:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8750:         &logthis($logmsg);
 8751:         return 'ok';
 8752:     }
 8753:     my $reply = &put('environment', \%names, $udom,$uname);
 8754:     if ($reply ne 'ok') { 
 8755:         return 'error: '.$reply;
 8756:     }
 8757:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8758:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8759:     }
 8760:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8761:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8762:     $logmsg = 'Success modifying user '.$logmsg;
 8763:     &logthis($logmsg);
 8764:     return 'ok';
 8765: }
 8766: 
 8767: # -------------------------------------------------------------- Modify student
 8768: 
 8769: sub modifystudent {
 8770:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8771:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8772:         $selfenroll,$context,$inststatus,$credits)=@_;
 8773:     if (!$cid) {
 8774: 	unless ($cid=$env{'request.course.id'}) {
 8775: 	    return 'not_in_class';
 8776: 	}
 8777:     }
 8778: # --------------------------------------------------------------- Make the user
 8779:     my $reply=&modifyuser
 8780: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8781:          $desiredhome,$email,$inststatus);
 8782:     unless ($reply eq 'ok') { return $reply; }
 8783:     # This will cause &modify_student_enrollment to get the uid from the
 8784:     # student's environment
 8785:     $uid = undef if (!$forceid);
 8786:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8787:                                         $gene,$usec,$end,$start,$type,$locktype,
 8788:                                         $cid,$selfenroll,$context,$credits);
 8789:     return $reply;
 8790: }
 8791: 
 8792: sub modify_student_enrollment {
 8793:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8794:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8795:     my ($cdom,$cnum,$chome);
 8796:     if (!$cid) {
 8797: 	unless ($cid=$env{'request.course.id'}) {
 8798: 	    return 'not_in_class';
 8799: 	}
 8800: 	$cdom=$env{'course.'.$cid.'.domain'};
 8801: 	$cnum=$env{'course.'.$cid.'.num'};
 8802:     } else {
 8803: 	($cdom,$cnum)=split(/_/,$cid);
 8804:     }
 8805:     $chome=$env{'course.'.$cid.'.home'};
 8806:     if (!$chome) {
 8807: 	$chome=&homeserver($cnum,$cdom);
 8808:     }
 8809:     if (!$chome) { return 'unknown_course'; }
 8810:     # Make sure the user exists
 8811:     my $uhome=&homeserver($uname,$udom);
 8812:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8813: 	return 'error: no such user';
 8814:     }
 8815:     # Get student data if we were not given enough information
 8816:     if (!defined($first)  || $first  eq '' || 
 8817:         !defined($last)   || $last   eq '' || 
 8818:         !defined($uid)    || $uid    eq '' || 
 8819:         !defined($middle) || $middle eq '' || 
 8820:         !defined($gene)   || $gene   eq '') {
 8821:         # They did not supply us with enough data to enroll the student, so
 8822:         # we need to pick up more information.
 8823:         my %tmp = &get('environment',
 8824:                        ['firstname','middlename','lastname', 'generation','id']
 8825:                        ,$udom,$uname);
 8826: 
 8827:         #foreach my $key (keys(%tmp)) {
 8828:         #    &logthis("key $key = ".$tmp{$key});
 8829:         #}
 8830:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8831:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8832:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8833:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8834:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8835:     }
 8836:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8837:     my $user = "$uname:$udom";
 8838:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8839:     my $reply=cput('classlist',
 8840: 		   {$user => 
 8841: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8842: 		   $cdom,$cnum);
 8843:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8844:         &devalidate_getsection_cache($udom,$uname,$cid);
 8845:     } else { 
 8846: 	return 'error: '.$reply;
 8847:     }
 8848:     # Add student role to user
 8849:     my $uurl='/'.$cid;
 8850:     $uurl=~s/\_/\//g;
 8851:     if ($usec) {
 8852: 	$uurl.='/'.$usec;
 8853:     }
 8854:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8855:                              $selfenroll,$context);
 8856:     if ($result ne 'ok') {
 8857:         if ($old_entry{$user} ne '') {
 8858:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8859:         } else {
 8860:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8861:         }
 8862:     }
 8863:     return $result; 
 8864: }
 8865: 
 8866: sub format_name {
 8867:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8868:     my $name;
 8869:     if ($first ne 'lastname') {
 8870: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8871:     } else {
 8872: 	if ($lastname=~/\S/) {
 8873: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8874: 	    $name=~s/\s+,/,/;
 8875: 	} else {
 8876: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8877: 	}
 8878:     }
 8879:     $name=~s/^\s+//;
 8880:     $name=~s/\s+$//;
 8881:     $name=~s/\s+/ /g;
 8882:     return $name;
 8883: }
 8884: 
 8885: # ------------------------------------------------- Write to course preferences
 8886: 
 8887: sub writecoursepref {
 8888:     my ($courseid,%prefs)=@_;
 8889:     $courseid=~s/^\///;
 8890:     $courseid=~s/\_/\//g;
 8891:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8892:     my $chome=homeserver($cnum,$cdomain);
 8893:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8894: 	return 'error: no such course';
 8895:     }
 8896:     my $cstring='';
 8897:     foreach my $pref (keys(%prefs)) {
 8898: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8899:     }
 8900:     $cstring=~s/\&$//;
 8901:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8902: }
 8903: 
 8904: # ---------------------------------------------------------- Make/modify course
 8905: 
 8906: sub createcourse {
 8907:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8908:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8909:     $url=&declutter($url);
 8910:     my $cid='';
 8911:     if ($context eq 'requestcourses') {
 8912:         my $can_create = 0;
 8913:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8914:         if ($udom eq $ownerdom) {
 8915:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8916:                                   $context)) {
 8917:                 $can_create = 1;
 8918:             }
 8919:         } else {
 8920:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8921:                                            $category);
 8922:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8923:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8924:                 if (@curr > 0) {
 8925:                     my @options = qw(approval validate autolimit);
 8926:                     my $optregex = join('|',@options);
 8927:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8928:                         $can_create = 1;
 8929:                     }
 8930:                 }
 8931:             }
 8932:         }
 8933:         if ($can_create) {
 8934:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8935:                 unless (&allowed('ccc',$udom)) {
 8936:                     return 'refused'; 
 8937:                 }
 8938:             }
 8939:         } else {
 8940:             return 'refused';
 8941:         }
 8942:     } elsif (!&allowed('ccc',$udom)) {
 8943:         return 'refused';
 8944:     }
 8945: # --------------------------------------------------------------- Get Unique ID
 8946:     my $uname;
 8947:     if ($cnum =~ /^$match_courseid$/) {
 8948:         my $chome=&homeserver($cnum,$udom,'true');
 8949:         if (($chome eq '') || ($chome eq 'no_host')) {
 8950:             $uname = $cnum;
 8951:         } else {
 8952:             $uname = &generate_coursenum($udom,$crstype);
 8953:         }
 8954:     } else {
 8955:         $uname = &generate_coursenum($udom,$crstype);
 8956:     }
 8957:     return $uname if ($uname =~ /^error/);
 8958: # -------------------------------------------------- Check supplied server name
 8959:     if (!defined($course_server)) {
 8960:         if (defined(&domain($udom,'primary'))) {
 8961:             $course_server = &domain($udom,'primary');
 8962:         } else {
 8963:             $course_server = $env{'user.home'}; 
 8964:         }
 8965:     }
 8966:     my %host_servers =
 8967:         &Apache::lonnet::get_servers($udom,'library');
 8968:     unless ($host_servers{$course_server}) {
 8969:         return 'error: invalid home server for course: '.$course_server;
 8970:     }
 8971: # ------------------------------------------------------------- Make the course
 8972:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8973:                       $course_server);
 8974:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8975:     my $uhome=&homeserver($uname,$udom,'true');
 8976:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8977: 	return 'error: no such course';
 8978:     }
 8979: # ----------------------------------------------------------------- Course made
 8980: # log existence
 8981:     my $now = time;
 8982:     my $newcourse = {
 8983:                     $udom.'_'.$uname => {
 8984:                                      description => $description,
 8985:                                      inst_code   => $inst_code,
 8986:                                      owner       => $course_owner,
 8987:                                      type        => $crstype,
 8988:                                      creator     => $env{'user.name'}.':'.
 8989:                                                     $env{'user.domain'},
 8990:                                      created     => $now,
 8991:                                      context     => $context,
 8992:                                                 },
 8993:                     };
 8994:     &courseidput($udom,$newcourse,$uhome,'notime');
 8995: # set toplevel url
 8996:     my $topurl=$url;
 8997:     unless ($nonstandard) {
 8998: # ------------------------------------------ For standard courses, make top url
 8999:         my $mapurl=&clutter($url);
 9000:         if ($mapurl eq '/res/') { $mapurl=''; }
 9001:         $env{'form.initmap'}=(<<ENDINITMAP);
 9002: <map>
 9003: <resource id="1" type="start"></resource>
 9004: <resource id="2" src="$mapurl"></resource>
 9005: <resource id="3" type="finish"></resource>
 9006: <link index="1" from="1" to="2"></link>
 9007: <link index="2" from="2" to="3"></link>
 9008: </map>
 9009: ENDINITMAP
 9010:         $topurl=&declutter(
 9011:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9012:                           );
 9013:     }
 9014: # ----------------------------------------------------------- Write preferences
 9015:     &writecoursepref($udom.'_'.$uname,
 9016:                      ('description'              => $description,
 9017:                       'url'                      => $topurl,
 9018:                       'internal.creator'         => $env{'user.name'}.':'.
 9019:                                                     $env{'user.domain'},
 9020:                       'internal.created'         => $now,
 9021:                       'internal.creationcontext' => $context)
 9022:                     );
 9023:     return '/'.$udom.'/'.$uname;
 9024: }
 9025: 
 9026: # ------------------------------------------------------------------- Create ID
 9027: sub generate_coursenum {
 9028:     my ($udom,$crstype) = @_;
 9029:     my $domdesc = &domain($udom);
 9030:     return 'error: invalid domain' if ($domdesc eq '');
 9031:     my $first;
 9032:     if ($crstype eq 'Community') {
 9033:         $first = '0';
 9034:     } else {
 9035:         $first = int(1+rand(9)); 
 9036:     } 
 9037:     my $uname=$first.
 9038:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9039:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9040:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9041: # ----------------------------------------------- Make sure that does not exist
 9042:     my $uhome=&homeserver($uname,$udom,'true');
 9043:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9044:         if ($crstype eq 'Community') {
 9045:             $first = '0';
 9046:         } else {
 9047:             $first = int(1+rand(9));
 9048:         }
 9049:         $uname=$first.
 9050:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9051:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9052:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9053:         $uhome=&homeserver($uname,$udom,'true');
 9054:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9055:             return 'error: unable to generate unique course-ID';
 9056:         }
 9057:     }
 9058:     return $uname;
 9059: }
 9060: 
 9061: sub is_course {
 9062:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9063:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9064: 
 9065:     return unless $cdom and $cnum;
 9066: 
 9067:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9068:         '.');
 9069: 
 9070:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9071:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9072: }
 9073: 
 9074: sub store_userdata {
 9075:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9076:     my $result;
 9077:     if ($datakey ne '') {
 9078:         if (ref($storehash) eq 'HASH') {
 9079:             if ($udom eq '' || $uname eq '') {
 9080:                 $udom = $env{'user.domain'};
 9081:                 $uname = $env{'user.name'};
 9082:             }
 9083:             my $uhome=&homeserver($uname,$udom);
 9084:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9085:                 $result = 'error: no_host';
 9086:             } else {
 9087:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9088:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9089: 
 9090:                 my $namevalue='';
 9091:                 foreach my $key (keys(%{$storehash})) {
 9092:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9093:                 }
 9094:                 $namevalue=~s/\&$//;
 9095:                 unless ($namespace eq 'courserequests') {
 9096:                     $datakey = &escape($datakey);
 9097:                 }
 9098:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9099:                                   $namevalue,$uhome);
 9100:             }
 9101:         } else {
 9102:             $result = 'error: data to store was not a hash reference'; 
 9103:         }
 9104:     } else {
 9105:         $result= 'error: invalid requestkey'; 
 9106:     }
 9107:     return $result;
 9108: }
 9109: 
 9110: # ---------------------------------------------------------- Assign Custom Role
 9111: 
 9112: sub assigncustomrole {
 9113:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9114:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9115:                        $end,$start,$deleteflag,$selfenroll,$context);
 9116: }
 9117: 
 9118: # ----------------------------------------------------------------- Revoke Role
 9119: 
 9120: sub revokerole {
 9121:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9122:     my $now=time;
 9123:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9124: }
 9125: 
 9126: # ---------------------------------------------------------- Revoke Custom Role
 9127: 
 9128: sub revokecustomrole {
 9129:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9130:     my $now=time;
 9131:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9132:            $deleteflag,$selfenroll,$context);
 9133: }
 9134: 
 9135: # ------------------------------------------------------------ Disk usage
 9136: sub diskusage {
 9137:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9138:     $directorypath =~ s/\/$//;
 9139:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9140:                        .&escape($getpropath).':'.&escape($uname).':'
 9141:                        .&escape($udom),homeserver($uname,$udom));
 9142:     if ($listing eq 'unknown_cmd') {
 9143:         if ($getpropath) {
 9144:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9145:         }
 9146:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9147:     }
 9148:     return $listing;
 9149: }
 9150: 
 9151: sub is_locked {
 9152:     my ($file_name, $domain, $user, $which) = @_;
 9153:     my @check;
 9154:     my $is_locked;
 9155:     push (@check,$file_name);
 9156:     my %locked = &get('file_permissions',\@check,
 9157: 		      $env{'user.domain'},$env{'user.name'});
 9158:     my ($tmp)=keys(%locked);
 9159:     if ($tmp=~/^error:/) { undef(%locked); }
 9160:     
 9161:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9162:         $is_locked = 'false';
 9163:         foreach my $entry (@{$locked{$file_name}}) {
 9164:            if (ref($entry) eq 'ARRAY') {
 9165:                $is_locked = 'true';
 9166:                if (ref($which) eq 'ARRAY') {
 9167:                    push(@{$which},$entry);
 9168:                } else {
 9169:                    last;
 9170:                }
 9171:            }
 9172:        }
 9173:     } else {
 9174:         $is_locked = 'false';
 9175:     }
 9176:     return $is_locked;
 9177: }
 9178: 
 9179: sub declutter_portfile {
 9180:     my ($file) = @_;
 9181:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9182:     return $file;
 9183: }
 9184: 
 9185: # ------------------------------------------------------------- Mark as Read Only
 9186: 
 9187: sub mark_as_readonly {
 9188:     my ($domain,$user,$files,$what) = @_;
 9189:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9190:     my ($tmp)=keys(%current_permissions);
 9191:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9192:     foreach my $file (@{$files}) {
 9193: 	$file = &declutter_portfile($file);
 9194:         push(@{$current_permissions{$file}},$what);
 9195:     }
 9196:     &put('file_permissions',\%current_permissions,$domain,$user);
 9197:     return;
 9198: }
 9199: 
 9200: # ------------------------------------------------------------Save Selected Files
 9201: 
 9202: sub save_selected_files {
 9203:     my ($user, $path, @files) = @_;
 9204:     my $filename = $user."savedfiles";
 9205:     my @other_files = &files_not_in_path($user, $path);
 9206:     open (OUT, '>'.$tmpdir.$filename);
 9207:     foreach my $file (@files) {
 9208:         print (OUT $env{'form.currentpath'}.$file."\n");
 9209:     }
 9210:     foreach my $file (@other_files) {
 9211:         print (OUT $file."\n");
 9212:     }
 9213:     close (OUT);
 9214:     return 'ok';
 9215: }
 9216: 
 9217: sub clear_selected_files {
 9218:     my ($user) = @_;
 9219:     my $filename = $user."savedfiles";
 9220:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9221:     print (OUT undef);
 9222:     close (OUT);
 9223:     return ("ok");    
 9224: }
 9225: 
 9226: sub files_in_path {
 9227:     my ($user, $path) = @_;
 9228:     my $filename = $user."savedfiles";
 9229:     my %return_files;
 9230:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9231:     while (my $line_in = <IN>) {
 9232:         chomp ($line_in);
 9233:         my @paths_and_file = split (m!/!, $line_in);
 9234:         my $file_part = pop (@paths_and_file);
 9235:         my $path_part = join ('/', @paths_and_file);
 9236:         $path_part.='/';
 9237:         my $path_and_file = $path_part.$file_part;
 9238:         if ($path_part eq $path) {
 9239:             $return_files{$file_part}= 'selected';
 9240:         }
 9241:     }
 9242:     close (IN);
 9243:     return (\%return_files);
 9244: }
 9245: 
 9246: # called in portfolio select mode, to show files selected NOT in current directory
 9247: sub files_not_in_path {
 9248:     my ($user, $path) = @_;
 9249:     my $filename = $user."savedfiles";
 9250:     my @return_files;
 9251:     my $path_part;
 9252:     open(IN, '<'.LONCAPA::.$filename);
 9253:     while (my $line = <IN>) {
 9254:         #ok, I know it's clunky, but I want it to work
 9255:         my @paths_and_file = split(m|/|, $line);
 9256:         my $file_part = pop(@paths_and_file);
 9257:         chomp($file_part);
 9258:         my $path_part = join('/', @paths_and_file);
 9259:         $path_part .= '/';
 9260:         my $path_and_file = $path_part.$file_part;
 9261:         if ($path_part ne $path) {
 9262:             push(@return_files, ($path_and_file));
 9263:         }
 9264:     }
 9265:     close(OUT);
 9266:     return (@return_files);
 9267: }
 9268: 
 9269: #------------------------------Submitted/Handedback Portfolio Files Versioning
 9270:  
 9271: sub portfiles_versioning {
 9272:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
 9273:     my $portfolio_root = '/userfiles/portfolio';
 9274:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
 9275:     foreach my $file (@{$portfiles}) {
 9276:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 9277:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 9278:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
 9279:         my $getpropath = 1;
 9280:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
 9281:                                              $stu_name,$getpropath);
 9282:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 9283:         my $new_answer = 
 9284:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
 9285:         if ($new_answer ne 'problem getting file') {
 9286:             push(@{$versioned_portfiles}, $directory.$new_answer);
 9287:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
 9288:                               [$symb,$env{'request.course.id'},'graded']);
 9289:         }
 9290:     }
 9291: }
 9292: 
 9293: sub get_next_version {
 9294:     my ($answer_name, $answer_ext, $dir_list) = @_;
 9295:     my $version;
 9296:     if (ref($dir_list) eq 'ARRAY') {
 9297:         foreach my $row (@{$dir_list}) {
 9298:             my ($file) = split(/\&/,$row,2);
 9299:             my ($file_name,$file_version,$file_ext) =
 9300:                 &file_name_version_ext($file);
 9301:             if (($file_name eq $answer_name) &&
 9302:                 ($file_ext eq $answer_ext)) {
 9303:                      # gets here if filename and extension match,
 9304:                      # regardless of version
 9305:                 if ($file_version ne '') {
 9306:                     # a versioned file is found  so save it for later
 9307:                     if ($file_version > $version) {
 9308:                         $version = $file_version;
 9309:                     }
 9310:                 }
 9311:             }
 9312:         }
 9313:     }
 9314:     $version ++;
 9315:     return($version);
 9316: }
 9317: 
 9318: sub version_selected_portfile {
 9319:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 9320:     my ($answer_name,$answer_ver,$answer_ext) =
 9321:         &file_name_version_ext($file_name);
 9322:     my $new_answer;
 9323:     $env{'form.copy'} =
 9324:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 9325:     if($env{'form.copy'} eq '-1') {
 9326:         $new_answer = 'problem getting file';
 9327:     } else {
 9328:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 9329:         my $copy_result = 
 9330:             &finishuserfileupload($stu_name,$domain,'copy',
 9331:                                   '/portfolio'.$directory.$new_answer);
 9332:     }
 9333:     undef($env{'form.copy'});
 9334:     return ($new_answer);
 9335: }
 9336: 
 9337: sub file_name_version_ext {
 9338:     my ($file)=@_;
 9339:     my @file_parts = split(/\./, $file);
 9340:     my ($name,$version,$ext);
 9341:     if (@file_parts > 1) {
 9342:         $ext=pop(@file_parts);
 9343:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 9344:             $version=pop(@file_parts);
 9345:         }
 9346:         $name=join('.',@file_parts);
 9347:     } else {
 9348:         $name=join('.',@file_parts);
 9349:     }
 9350:     return($name,$version,$ext);
 9351: }
 9352: 
 9353: #----------------------------------------------Get portfolio file permissions
 9354: 
 9355: sub get_portfile_permissions {
 9356:     my ($domain,$user) = @_;
 9357:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9358:     my ($tmp)=keys(%current_permissions);
 9359:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9360:     return \%current_permissions;
 9361: }
 9362: 
 9363: #---------------------------------------------Get portfolio file access controls
 9364: 
 9365: sub get_access_controls {
 9366:     my ($current_permissions,$group,$file) = @_;
 9367:     my %access;
 9368:     my $real_file = $file;
 9369:     $file =~ s/\.meta$//;
 9370:     if (defined($file)) {
 9371:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9372:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9373:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9374:             }
 9375:         }
 9376:     } else {
 9377:         foreach my $key (keys(%{$current_permissions})) {
 9378:             if ($key =~ /\0accesscontrol$/) {
 9379:                 if (defined($group)) {
 9380:                     if ($key !~ m-^\Q$group\E/-) {
 9381:                         next;
 9382:                     }
 9383:                 }
 9384:                 my ($fullpath) = split(/\0/,$key);
 9385:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9386:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9387:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9388:                     }
 9389:                 }
 9390:             }
 9391:         }
 9392:     }
 9393:     return %access;
 9394: }
 9395: 
 9396: sub modify_access_controls {
 9397:     my ($file_name,$changes,$domain,$user)=@_;
 9398:     my ($outcome,$deloutcome);
 9399:     my %store_permissions;
 9400:     my %new_values;
 9401:     my %new_control;
 9402:     my %translation;
 9403:     my @deletions = ();
 9404:     my $now = time;
 9405:     if (exists($$changes{'activate'})) {
 9406:         if (ref($$changes{'activate'}) eq 'HASH') {
 9407:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9408:             my $numnew = scalar(@newitems);
 9409:             for (my $i=0; $i<$numnew; $i++) {
 9410:                 my $newkey = $newitems[$i];
 9411:                 my $newid = &Apache::loncommon::get_cgi_id();
 9412:                 if ($newkey =~ /^\d+:/) { 
 9413:                     $newkey =~ s/^(\d+)/$newid/;
 9414:                     $translation{$1} = $newid;
 9415:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9416:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9417:                     $translation{$1} = $newid;
 9418:                 }
 9419:                 $new_values{$file_name."\0".$newkey} = 
 9420:                                           $$changes{'activate'}{$newitems[$i]};
 9421:                 $new_control{$newkey} = $now;
 9422:             }
 9423:         }
 9424:     }
 9425:     my %todelete;
 9426:     my %changed_items;
 9427:     foreach my $action ('delete','update') {
 9428:         if (exists($$changes{$action})) {
 9429:             if (ref($$changes{$action}) eq 'HASH') {
 9430:                 foreach my $key (keys(%{$$changes{$action}})) {
 9431:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9432:                     if ($action eq 'delete') { 
 9433:                         $todelete{$itemnum} = 1;
 9434:                     } else {
 9435:                         $changed_items{$itemnum} = $key;
 9436:                     }
 9437:                 }
 9438:             }
 9439:         }
 9440:     }
 9441:     # get lock on access controls for file.
 9442:     my $lockhash = {
 9443:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9444:                                                        ':'.$env{'user.domain'},
 9445:                    }; 
 9446:     my $tries = 0;
 9447:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9448:    
 9449:     while (($gotlock ne 'ok') && $tries <3) {
 9450:         $tries ++;
 9451:         sleep 1;
 9452:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9453:     }
 9454:     if ($gotlock eq 'ok') {
 9455:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9456:         my ($tmp)=keys(%curr_permissions);
 9457:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9458:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9459:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9460:             if (ref($curr_controls) eq 'HASH') {
 9461:                 foreach my $control_item (keys(%{$curr_controls})) {
 9462:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9463:                     if (defined($todelete{$itemnum})) {
 9464:                         push(@deletions,$file_name."\0".$control_item);
 9465:                     } else {
 9466:                         if (defined($changed_items{$itemnum})) {
 9467:                             $new_control{$changed_items{$itemnum}} = $now;
 9468:                             push(@deletions,$file_name."\0".$control_item);
 9469:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9470:                         } else {
 9471:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9472:                         }
 9473:                     }
 9474:                 }
 9475:             }
 9476:         }
 9477:         my ($group);
 9478:         if (&is_course($domain,$user)) {
 9479:             ($group,my $file) = split(/\//,$file_name,2);
 9480:         }
 9481:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9482:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9483:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9484:         #  remove lock
 9485:         my @del_lock = ($file_name."\0".'locked_access_records');
 9486:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9487:         my $sqlresult =
 9488:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9489:                                     $group);
 9490:     } else {
 9491:         $outcome = "error: could not obtain lockfile\n";  
 9492:     }
 9493:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9494: }
 9495: 
 9496: sub make_public_indefinitely {
 9497:     my (@requrl) = @_;
 9498:     return &automated_portfile_access('public',\@requrl);
 9499: }
 9500: 
 9501: sub automated_portfile_access {
 9502:     my ($accesstype,$addsref,$delsref,$info) = @_;
 9503:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
 9504:         return 'invalid';
 9505:     }
 9506:     my %urls;
 9507:     if (ref($addsref) eq 'ARRAY') {
 9508:         foreach my $requrl (@{$addsref}) {
 9509:             if (&is_portfolio_url($requrl)) {
 9510:                 unless (exists($urls{$requrl})) {
 9511:                     $urls{$requrl} = 'add';
 9512:                 }
 9513:             }
 9514:         }
 9515:     }
 9516:     if (ref($delsref) eq 'ARRAY') {
 9517:         foreach my $requrl (@{$delsref}) { 
 9518:             if (&is_portfolio_url($requrl)) {
 9519:                 unless (exists($urls{$requrl})) {
 9520:                     $urls{$requrl} = 'delete'; 
 9521:                 }
 9522:             }
 9523:         }
 9524:     }
 9525:     unless (keys(%urls)) {
 9526:         return 'invalid';
 9527:     }
 9528:     my $ip;
 9529:     if ($accesstype eq 'ip') {
 9530:         if (ref($info) eq 'HASH') {
 9531:             if ($info->{'ip'} ne '') {
 9532:                 $ip = $info->{'ip'};
 9533:             }
 9534:         }
 9535:         if ($ip eq '') {
 9536:             return 'invalid';
 9537:         }
 9538:     }
 9539:     my $errors;
 9540:     my $now = time;
 9541:     my %current_perms;
 9542:     foreach my $requrl (sort(keys(%urls))) {
 9543:         my $action;
 9544:         if ($urls{$requrl} eq 'add') {
 9545:             $action = 'activate';
 9546:         } else {
 9547:             $action = 'none';
 9548:         }
 9549:         my $aclnum = 0;
 9550:         my (undef,$udom,$unum,$file_name,$group) =
 9551:             &parse_portfolio_url($requrl);
 9552:         unless (exists($current_perms{$unum.':'.$udom})) {
 9553:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
 9554:         }
 9555:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
 9556:                                                    $group,$file_name);
 9557:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9558:             my ($num,$scope,$end,$start) = 
 9559:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9560:             if ($scope eq $accesstype) {
 9561:                 if (($start <= $now) && ($end == 0)) {
 9562:                     if ($accesstype eq 'ip') {
 9563:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
 9564:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
 9565:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
 9566:                                     if ($urls{$requrl} eq 'add') {
 9567:                                         $action = 'none';
 9568:                                         last;
 9569:                                     } else {
 9570:                                         $action = 'delete';
 9571:                                         $aclnum = $num;
 9572:                                         last;
 9573:                                     }
 9574:                                 }
 9575:                             }
 9576:                         }
 9577:                     } elsif ($accesstype eq 'public') {
 9578:                         if ($urls{$requrl} eq 'add') {
 9579:                             $action = 'none';
 9580:                             last;
 9581:                         } else {
 9582:                             $action = 'delete';
 9583:                             $aclnum = $num;
 9584:                             last;
 9585:                         }
 9586:                     }
 9587:                 } elsif ($accesstype eq 'public') {
 9588:                     $action = 'update';
 9589:                     $aclnum = $num;
 9590:                     last;
 9591:                 }
 9592:             }
 9593:         }
 9594:         if ($action eq 'none') {
 9595:             next;
 9596:         } else {
 9597:             my %changes;
 9598:             my $newend = 0;
 9599:             my $newstart = $now;
 9600:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
 9601:             $changes{$action}{$newkey} = {
 9602:                 type => $accesstype,
 9603:                 time => {
 9604:                     start => $newstart,
 9605:                     end   => $newend,
 9606:                 },
 9607:             };
 9608:             if ($accesstype eq 'ip') {
 9609:                 $changes{$action}{$newkey}{'ip'} = [$ip];
 9610:             }
 9611:             my ($outcome,$deloutcome,$new_values,$translation) =
 9612:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9613:             unless ($outcome eq 'ok') {
 9614:                 $errors .= $outcome.' ';
 9615:             }
 9616:         }
 9617:     }
 9618:     if ($errors) {
 9619:         $errors =~ s/\s$//;
 9620:         return $errors;
 9621:     } else {
 9622:         return 'ok';
 9623:     }
 9624: }
 9625: 
 9626: #------------------------------------------------------Get Marked as Read Only
 9627: 
 9628: sub get_marked_as_readonly {
 9629:     my ($domain,$user,$what,$group) = @_;
 9630:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9631:     my @readonly_files;
 9632:     my $cmp1=$what;
 9633:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9634:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9635:         if (defined($group)) {
 9636:             if ($file_name !~ m-^\Q$group\E/-) {
 9637:                 next;
 9638:             }
 9639:         }
 9640:         if (ref($value) eq "ARRAY"){
 9641:             foreach my $stored_what (@{$value}) {
 9642:                 my $cmp2=$stored_what;
 9643:                 if (ref($stored_what) eq 'ARRAY') {
 9644:                     $cmp2=join('',@{$stored_what});
 9645:                 }
 9646:                 if ($cmp1 eq $cmp2) {
 9647:                     push(@readonly_files, $file_name);
 9648:                     last;
 9649:                 } elsif (!defined($what)) {
 9650:                     push(@readonly_files, $file_name);
 9651:                     last;
 9652:                 }
 9653:             }
 9654:         }
 9655:     }
 9656:     return @readonly_files;
 9657: }
 9658: #-----------------------------------------------------------Get Marked as Read Only Hash
 9659: 
 9660: sub get_marked_as_readonly_hash {
 9661:     my ($current_permissions,$group,$what) = @_;
 9662:     my %readonly_files;
 9663:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9664:         if (defined($group)) {
 9665:             if ($file_name !~ m-^\Q$group\E/-) {
 9666:                 next;
 9667:             }
 9668:         }
 9669:         if (ref($value) eq "ARRAY"){
 9670:             foreach my $stored_what (@{$value}) {
 9671:                 if (ref($stored_what) eq 'ARRAY') {
 9672:                     foreach my $lock_descriptor(@{$stored_what}) {
 9673:                         if ($lock_descriptor eq 'graded') {
 9674:                             $readonly_files{$file_name} = 'graded';
 9675:                         } elsif ($lock_descriptor eq 'handback') {
 9676:                             $readonly_files{$file_name} = 'handback';
 9677:                         } else {
 9678:                             if (!exists($readonly_files{$file_name})) {
 9679:                                 $readonly_files{$file_name} = 'locked';
 9680:                             }
 9681:                         }
 9682:                     }
 9683:                 } 
 9684:             }
 9685:         } 
 9686:     }
 9687:     return %readonly_files;
 9688: }
 9689: # ------------------------------------------------------------ Unmark as Read Only
 9690: 
 9691: sub unmark_as_readonly {
 9692:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9693:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9694:     my ($domain,$user,$what,$file_name,$group) = @_;
 9695:     $file_name = &declutter_portfile($file_name);
 9696:     my $symb_crs = $what;
 9697:     if (ref($what)) { $symb_crs=join('',@$what); }
 9698:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9699:     my ($tmp)=keys(%current_permissions);
 9700:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9701:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9702:     foreach my $file (@readonly_files) {
 9703: 	my $clean_file = &declutter_portfile($file);
 9704: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9705: 	my $current_locks = $current_permissions{$file};
 9706:         my @new_locks;
 9707:         my @del_keys;
 9708:         if (ref($current_locks) eq "ARRAY"){
 9709:             foreach my $locker (@{$current_locks}) {
 9710:                 my $compare=$locker;
 9711:                 if (ref($locker) eq 'ARRAY') {
 9712:                     $compare=join('',@{$locker});
 9713:                     if ($compare ne $symb_crs) {
 9714:                         push(@new_locks, $locker);
 9715:                     }
 9716:                 }
 9717:             }
 9718:             if (scalar(@new_locks) > 0) {
 9719:                 $current_permissions{$file} = \@new_locks;
 9720:             } else {
 9721:                 push(@del_keys, $file);
 9722:                 &del('file_permissions',\@del_keys, $domain, $user);
 9723:                 delete($current_permissions{$file});
 9724:             }
 9725:         }
 9726:     }
 9727:     &put('file_permissions',\%current_permissions,$domain,$user);
 9728:     return;
 9729: }
 9730: 
 9731: # ------------------------------------------------------------ Directory lister
 9732: 
 9733: sub dirlist {
 9734:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9735:     $uri=~s/^\///;
 9736:     $uri=~s/\/$//;
 9737:     my ($udom, $uname);
 9738:     if ($getuserdir) {
 9739:         $udom = $userdomain;
 9740:         $uname = $username;
 9741:     } else {
 9742:         (undef,$udom,$uname)=split(/\//,$uri);
 9743:         if(defined($userdomain)) {
 9744:             $udom = $userdomain;
 9745:         }
 9746:         if(defined($username)) {
 9747:             $uname = $username;
 9748:         }
 9749:     }
 9750:     my ($dirRoot,$listing,@listing_results);
 9751: 
 9752:     $dirRoot = $perlvar{'lonDocRoot'};
 9753:     if (defined($getpropath)) {
 9754:         $dirRoot = &propath($udom,$uname);
 9755:         $dirRoot =~ s/\/$//;
 9756:     } elsif (defined($getuserdir)) {
 9757:         my $subdir=$uname.'__';
 9758:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9759:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9760:                    ."/$udom/$subdir/$uname";
 9761:     } elsif (defined($alternateRoot)) {
 9762:         $dirRoot = $alternateRoot;
 9763:     }
 9764: 
 9765:     if($udom) {
 9766:         if($uname) {
 9767:             my $uhome = &homeserver($uname,$udom);
 9768:             if ($uhome eq 'no_host') {
 9769:                 return ([],'no_host');
 9770:             }
 9771:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9772:                               .$getuserdir.':'.&escape($dirRoot)
 9773:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9774:             if ($listing eq 'unknown_cmd') {
 9775:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9776:             } else {
 9777:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9778:             }
 9779:             if ($listing eq 'unknown_cmd') {
 9780:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9781:                 @listing_results = split(/:/,$listing);
 9782:             } else {
 9783:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9784:             }
 9785:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9786:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9787:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9788:                 return ([],$listing);
 9789:             } else {
 9790:                 return (\@listing_results);
 9791:             }
 9792:         } elsif(!$alternateRoot) {
 9793:             my (%allusers,%listerror);
 9794: 	    my %servers = &get_servers($udom,'library');
 9795:  	    foreach my $tryserver (keys(%servers)) {
 9796:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9797:                                   &escape($udom),$tryserver);
 9798:                 if ($listing eq 'unknown_cmd') {
 9799: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9800: 				      $udom, $tryserver);
 9801:                 } else {
 9802:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9803:                 }
 9804: 		if ($listing eq 'unknown_cmd') {
 9805: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9806: 				      $udom, $tryserver);
 9807: 		    @listing_results = split(/:/,$listing);
 9808: 		} else {
 9809: 		    @listing_results =
 9810: 			map { &unescape($_); } split(/:/,$listing);
 9811: 		}
 9812:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9813:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9814:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9815:                     $listerror{$tryserver} = $listing;
 9816:                 } else {
 9817: 		    foreach my $line (@listing_results) {
 9818: 			my ($entry) = split(/&/,$line,2);
 9819: 			$allusers{$entry} = 1;
 9820: 		    }
 9821: 		}
 9822:             }
 9823:             my @alluserslist=();
 9824:             foreach my $user (sort(keys(%allusers))) {
 9825:                 push(@alluserslist,$user.'&user');
 9826:             }
 9827:             return (\@alluserslist);
 9828:         } else {
 9829:             return ([],'missing username');
 9830:         }
 9831:     } elsif(!defined($getpropath)) {
 9832:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9833:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9834:         return (\@all_domains);
 9835:     } else {
 9836:         return ([],'missing domain');
 9837:     }
 9838: }
 9839: 
 9840: # --------------------------------------------- GetFileTimestamp
 9841: # This function utilizes dirlist and returns the date stamp for
 9842: # when it was last modified.  It will also return an error of -1
 9843: # if an error occurs
 9844: 
 9845: sub GetFileTimestamp {
 9846:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9847:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9848:     $studentName   = &LONCAPA::clean_username($studentName);
 9849:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9850:                                     undef,$getuserdir);
 9851:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9852:         return -1;
 9853:     }
 9854:     if (ref($fileref) eq 'ARRAY') {
 9855:         my @stats = split('&',$fileref->[0]);
 9856:         # @stats contains first the filename, then the stat output
 9857:         return $stats[10]; # so this is 10 instead of 9.
 9858:     } else {
 9859:         return -1;
 9860:     }
 9861: }
 9862: 
 9863: sub stat_file {
 9864:     my ($uri) = @_;
 9865:     $uri = &clutter_with_no_wrapper($uri);
 9866: 
 9867:     my ($udom,$uname,$file);
 9868:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9869: 	($udom,$uname,$file) =
 9870: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9871: 	$file = 'userfiles/'.$file;
 9872:     }
 9873:     if ($uri =~ m-^/res/-) {
 9874: 	($udom,$uname) = 
 9875: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9876: 	$file = $uri;
 9877:     }
 9878: 
 9879:     if (!$udom || !$uname || !$file) {
 9880: 	# unable to handle the uri
 9881: 	return ();
 9882:     }
 9883:     my $getpropath;
 9884:     if ($file =~ /^userfiles\//) {
 9885:         $getpropath = 1;
 9886:     }
 9887:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9888:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9889:         return ();
 9890:     } else {
 9891:         if (ref($listref) eq 'ARRAY') {
 9892:             my @stats = split('&',$listref->[0]);
 9893: 	    shift(@stats); #filename is first
 9894: 	    return @stats;
 9895:         }
 9896:     }
 9897:     return ();
 9898: }
 9899: 
 9900: # -------------------------------------------------------- Value of a Condition
 9901: 
 9902: # gets the value of a specific preevaluated condition
 9903: #    stored in the string  $env{user.state.<cid>}
 9904: # or looks up a condition reference in the bighash and if if hasn't
 9905: # already been evaluated recurses into docondval to get the value of
 9906: # the condition, then memoizing it to 
 9907: #   $env{user.state.<cid>.<condition>}
 9908: sub directcondval {
 9909:     my $number=shift;
 9910:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9911: 	&Apache::lonuserstate::evalstate();
 9912:     }
 9913:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9914: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9915:     } elsif ($number =~ /^_/) {
 9916: 	my $sub_condition;
 9917: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9918: 		&GDBM_READER(),0640)) {
 9919: 	    $sub_condition=$bighash{'conditions'.$number};
 9920: 	    untie(%bighash);
 9921: 	}
 9922: 	my $value = &docondval($sub_condition);
 9923: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9924: 	return $value;
 9925:     }
 9926:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9927:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9928:     } else {
 9929:        return 2;
 9930:     }
 9931: }
 9932: 
 9933: # get the collection of conditions for this resource
 9934: sub condval {
 9935:     my $condidx=shift;
 9936:     my $allpathcond='';
 9937:     foreach my $cond (split(/\|/,$condidx)) {
 9938: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9939: 	    $allpathcond.=
 9940: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9941: 	}
 9942:     }
 9943:     $allpathcond=~s/\|$//;
 9944:     return &docondval($allpathcond);
 9945: }
 9946: 
 9947: #evaluates an expression of conditions
 9948: sub docondval {
 9949:     my ($allpathcond) = @_;
 9950:     my $result=0;
 9951:     if ($env{'request.course.id'}
 9952: 	&& defined($allpathcond)) {
 9953: 	my $operand='|';
 9954: 	my @stack;
 9955: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9956: 	    if ($chunk eq '(') {
 9957: 		push @stack,($operand,$result);
 9958: 	    } elsif ($chunk eq ')') {
 9959: 		my $before=pop @stack;
 9960: 		if (pop @stack eq '&') {
 9961: 		    $result=$result>$before?$before:$result;
 9962: 		} else {
 9963: 		    $result=$result>$before?$result:$before;
 9964: 		}
 9965: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9966: 		$operand=$chunk;
 9967: 	    } else {
 9968: 		my $new=directcondval($chunk);
 9969: 		if ($operand eq '&') {
 9970: 		    $result=$result>$new?$new:$result;
 9971: 		} else {
 9972: 		    $result=$result>$new?$result:$new;
 9973: 		}
 9974: 	    }
 9975: 	}
 9976:     }
 9977:     return $result;
 9978: }
 9979: 
 9980: # ---------------------------------------------------- Devalidate courseresdata
 9981: 
 9982: sub devalidatecourseresdata {
 9983:     my ($coursenum,$coursedomain)=@_;
 9984:     my $hashid=$coursenum.':'.$coursedomain;
 9985:     &devalidate_cache_new('courseres',$hashid);
 9986: }
 9987: 
 9988: 
 9989: # --------------------------------------------------- Course Resourcedata Query
 9990: #
 9991: #  Parameters:
 9992: #      $coursenum    - Number of the course.
 9993: #      $coursedomain - Domain at which the course was created.
 9994: #  Returns:
 9995: #     A hash of the course parameters along (I think) with timestamps
 9996: #     and version info.
 9997: 
 9998: sub get_courseresdata {
 9999:     my ($coursenum,$coursedomain)=@_;
10000:     my $coursehom=&homeserver($coursenum,$coursedomain);
10001:     my $hashid=$coursenum.':'.$coursedomain;
10002:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
10003:     my %dumpreply;
10004:     unless (defined($cached)) {
10005: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
10006: 	$result=\%dumpreply;
10007: 	my ($tmp) = keys(%dumpreply);
10008: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10009: 	    &do_cache_new('courseres',$hashid,$result,600);
10010: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10011: 	    return $tmp;
10012: 	} elsif ($tmp =~ /^(error)/) {
10013: 	    $result=undef;
10014: 	    &do_cache_new('courseres',$hashid,$result,600);
10015: 	}
10016:     }
10017:     return $result;
10018: }
10019: 
10020: sub devalidateuserresdata {
10021:     my ($uname,$udom)=@_;
10022:     my $hashid="$udom:$uname";
10023:     &devalidate_cache_new('userres',$hashid);
10024: }
10025: 
10026: sub get_userresdata {
10027:     my ($uname,$udom)=@_;
10028:     #most student don\'t have any data set, check if there is some data
10029:     if (&EXT_cache_status($udom,$uname)) { return undef; }
10030: 
10031:     my $hashid="$udom:$uname";
10032:     my ($result,$cached)=&is_cached_new('userres',$hashid);
10033:     if (!defined($cached)) {
10034: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
10035: 	$result=\%resourcedata;
10036: 	&do_cache_new('userres',$hashid,$result,600);
10037:     }
10038:     my ($tmp)=keys(%$result);
10039:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10040: 	return $result;
10041:     }
10042:     #error 2 occurs when the .db doesn't exist
10043:     if ($tmp!~/error: 2 /) {
10044: 	&logthis("<font color=\"blue\">WARNING:".
10045: 		 " Trying to get resource data for ".
10046: 		 $uname." at ".$udom.": ".
10047: 		 $tmp."</font>");
10048:     } elsif ($tmp=~/error: 2 /) {
10049: 	#&EXT_cache_set($udom,$uname);
10050: 	&do_cache_new('userres',$hashid,undef,600);
10051: 	undef($tmp); # not really an error so don't send it back
10052:     }
10053:     return $tmp;
10054: }
10055: #----------------------------------------------- resdata - return resource data
10056: #  Purpose:
10057: #    Return resource data for either users or for a course.
10058: #  Parameters:
10059: #     $name      - Course/user name.
10060: #     $domain    - Name of the domain the user/course is registered on.
10061: #     $type      - Type of thing $name is (must be 'course' or 'user'
10062: #     @which     - Array of names of resources desired.
10063: #  Returns:
10064: #     The value of the first reasource in @which that is found in the
10065: #     resource hash.
10066: #  Exceptional Conditions:
10067: #     If the $type passed in is not valid (not the string 'course' or 
10068: #     'user', an undefined  reference is returned.
10069: #     If none of the resources are found, an undef is returned
10070: sub resdata {
10071:     my ($name,$domain,$type,@which)=@_;
10072:     my $result;
10073:     if ($type eq 'course') {
10074: 	$result=&get_courseresdata($name,$domain);
10075:     } elsif ($type eq 'user') {
10076: 	$result=&get_userresdata($name,$domain);
10077:     }
10078:     if (!ref($result)) { return $result; }    
10079:     foreach my $item (@which) {
10080: 	if (defined($result->{$item->[0]})) {
10081: 	    return [$result->{$item->[0]},$item->[1]];
10082: 	}
10083:     }
10084:     return undef;
10085: }
10086: 
10087: sub get_numsuppfiles {
10088:     my ($cnum,$cdom,$ignorecache)=@_;
10089:     my $hashid=$cnum.':'.$cdom;
10090:     my ($suppcount,$cached);
10091:     unless ($ignorecache) {
10092:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10093:     }
10094:     unless (defined($cached)) {
10095:         my $chome=&homeserver($cnum,$cdom);
10096:         unless ($chome eq 'no_host') {
10097:             ($suppcount,my $errors) = (0,0);
10098:             my $suppmap = 'supplemental.sequence';
10099:             ($suppcount,$errors) = 
10100:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10101:         }
10102:         &do_cache_new('suppcount',$hashid,$suppcount,600);
10103:     }
10104:     return $suppcount;
10105: }
10106: 
10107: #
10108: # EXT resource caching routines
10109: #
10110: 
10111: sub clear_EXT_cache_status {
10112:     &delenv('cache.EXT.');
10113: }
10114: 
10115: sub EXT_cache_status {
10116:     my ($target_domain,$target_user) = @_;
10117:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10118:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10119:         # We know already the user has no data
10120:         return 1;
10121:     } else {
10122:         return 0;
10123:     }
10124: }
10125: 
10126: sub EXT_cache_set {
10127:     my ($target_domain,$target_user) = @_;
10128:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10129:     #&appenv({$cachename => time});
10130: }
10131: 
10132: # --------------------------------------------------------- Value of a Variable
10133: sub EXT {
10134: 
10135:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10136:     unless ($varname) { return ''; }
10137:     #get real user name/domain, courseid and symb
10138:     my $courseid;
10139:     my $publicuser;
10140:     if ($symbparm) {
10141: 	$symbparm=&get_symb_from_alias($symbparm);
10142:     }
10143:     if (!($uname && $udom)) {
10144:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10145:       if (!$symbparm) {	$symbparm=$cursymb; }
10146:     } else {
10147: 	$courseid=$env{'request.course.id'};
10148:     }
10149:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10150:     my $rest;
10151:     if (defined($therest[0])) {
10152:        $rest=join('.',@therest);
10153:     } else {
10154:        $rest='';
10155:     }
10156: 
10157:     my $qualifierrest=$qualifier;
10158:     if ($rest) { $qualifierrest.='.'.$rest; }
10159:     my $spacequalifierrest=$space;
10160:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10161:     if ($realm eq 'user') {
10162: # --------------------------------------------------------------- user.resource
10163: 	if ($space eq 'resource') {
10164: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10165: 		  || defined($Apache::lonhomework::parsing_a_task))
10166: 		 &&
10167: 		 ($symbparm eq &symbread()) ) {	
10168: 		# if we are in the middle of processing the resource the
10169: 		# get the value we are planning on committing
10170:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10171:                     return $Apache::lonhomework::results{$qualifierrest};
10172:                 } else {
10173:                     return $Apache::lonhomework::history{$qualifierrest};
10174:                 }
10175: 	    } else {
10176: 		my %restored;
10177: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10178: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10179: 		} else {
10180: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10181: 		}
10182: 		return $restored{$qualifierrest};
10183: 	    }
10184: # ----------------------------------------------------------------- user.access
10185:         } elsif ($space eq 'access') {
10186: 	    # FIXME - not supporting calls for a specific user
10187:             return &allowed($qualifier,$rest);
10188: # ------------------------------------------ user.preferences, user.environment
10189:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10190: 	    if (($uname eq $env{'user.name'}) &&
10191: 		($udom eq $env{'user.domain'})) {
10192: 		return $env{join('.',('environment',$qualifierrest))};
10193: 	    } else {
10194: 		my %returnhash;
10195: 		if (!$publicuser) {
10196: 		    %returnhash=&userenvironment($udom,$uname,
10197: 						 $qualifierrest);
10198: 		}
10199: 		return $returnhash{$qualifierrest};
10200: 	    }
10201: # ----------------------------------------------------------------- user.course
10202:         } elsif ($space eq 'course') {
10203: 	    # FIXME - not supporting calls for a specific user
10204:             return $env{join('.',('request.course',$qualifier))};
10205: # ------------------------------------------------------------------- user.role
10206:         } elsif ($space eq 'role') {
10207: 	    # FIXME - not supporting calls for a specific user
10208:             my ($role,$where)=split(/\./,$env{'request.role'});
10209:             if ($qualifier eq 'value') {
10210: 		return $role;
10211:             } elsif ($qualifier eq 'extent') {
10212:                 return $where;
10213:             }
10214: # ----------------------------------------------------------------- user.domain
10215:         } elsif ($space eq 'domain') {
10216:             return $udom;
10217: # ------------------------------------------------------------------- user.name
10218:         } elsif ($space eq 'name') {
10219:             return $uname;
10220: # ---------------------------------------------------- Any other user namespace
10221:         } else {
10222: 	    my %reply;
10223: 	    if (!$publicuser) {
10224: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10225: 	    }
10226: 	    return $reply{$qualifierrest};
10227:         }
10228:     } elsif ($realm eq 'query') {
10229: # ---------------------------------------------- pull stuff out of query string
10230:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10231: 						[$spacequalifierrest]);
10232: 	return $env{'form.'.$spacequalifierrest}; 
10233:    } elsif ($realm eq 'request') {
10234: # ------------------------------------------------------------- request.browser
10235:         if ($space eq 'browser') {
10236:             return $env{'browser.'.$qualifier};
10237: # ------------------------------------------------------------ request.filename
10238:         } else {
10239:             return $env{'request.'.$spacequalifierrest};
10240:         }
10241:     } elsif ($realm eq 'course') {
10242: # ---------------------------------------------------------- course.description
10243:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10244:     } elsif ($realm eq 'resource') {
10245: 
10246: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10247: 	    if (!$symbparm) { $symbparm=&symbread(); }
10248: 	}
10249: 
10250:         if ($qualifier eq '') {
10251: 	    if ($space eq 'title') {
10252: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10253: 	        return &gettitle($symbparm);
10254: 	    }
10255: 	
10256: 	    if ($space eq 'map') {
10257: 	        my ($map) = &decode_symb($symbparm);
10258: 	        return &symbread($map);
10259: 	    }
10260:             if ($space eq 'maptitle') {
10261:                 my ($map) = &decode_symb($symbparm);
10262:                 return &gettitle($map);
10263:             }
10264: 	    if ($space eq 'filename') {
10265: 	        if ($symbparm) {
10266: 		    return &clutter((&decode_symb($symbparm))[2]);
10267: 	        }
10268: 	        return &hreflocation('',$env{'request.filename'});
10269: 	    }
10270: 
10271:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10272:                 if ($space eq 'visibleparts') {
10273:                     my $navmap = Apache::lonnavmaps::navmap->new();
10274:                     my $item;
10275:                     if (ref($navmap)) {
10276:                         my $res = $navmap->getBySymb($symbparm);
10277:                         my $parts = $res->parts();
10278:                         if (ref($parts) eq 'ARRAY') {
10279:                             $item = join(',',@{$parts});
10280:                         }
10281:                         undef($navmap);
10282:                     }
10283:                     return $item;
10284:                 }
10285:             }
10286:         }
10287: 
10288: 	my ($section, $group, @groups);
10289: 	my ($courselevelm,$courselevel);
10290:         if (($courseid eq '') && ($cid)) {
10291:             $courseid = $cid;
10292:         }
10293: 	if (($symbparm && $courseid) && 
10294: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10295: 
10296: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10297: 
10298: # ----------------------------------------------------- Cascading lookup scheme
10299: 	    my $symbp=$symbparm;
10300: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10301: 
10302: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10303: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10304: 
10305: 	    if (($env{'user.name'} eq $uname) &&
10306: 		($env{'user.domain'} eq $udom)) {
10307: 		$section=$env{'request.course.sec'};
10308:                 @groups = split(/:/,$env{'request.course.groups'});  
10309:                 @groups=&sort_course_groups($courseid,@groups); 
10310: 	    } else {
10311: 		if (! defined($usection)) {
10312: 		    $section=&getsection($udom,$uname,$courseid);
10313: 		} else {
10314: 		    $section = $usection;
10315: 		}
10316:                 @groups = &get_users_groups($udom,$uname,$courseid);
10317: 	    }
10318: 
10319: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10320: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10321: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10322: 
10323: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10324: 	    my $courselevelr=$courseid.'.'.$symbparm;
10325: 	    $courselevelm=$courseid.'.'.$mapparm;
10326: 
10327: # ----------------------------------------------------------- first, check user
10328: 
10329: 	    my $userreply=&resdata($uname,$udom,'user',
10330: 				       ([$courselevelr,'resource'],
10331: 					[$courselevelm,'map'     ],
10332: 					[$courselevel, 'course'  ]));
10333: 	    if (defined($userreply)) { return &get_reply($userreply); }
10334: 
10335: # ------------------------------------------------ second, check some of course
10336:             my $coursereply;
10337:             if (@groups > 0) {
10338:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10339:                                        $mapparm,$spacequalifierrest);
10340:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10341:             }
10342: 
10343: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10344: 				  $env{'course.'.$courseid.'.domain'},
10345: 				  'course',
10346: 				  ([$seclevelr,   'resource'],
10347: 				   [$seclevelm,   'map'     ],
10348: 				   [$seclevel,    'course'  ],
10349: 				   [$courselevelr,'resource']));
10350: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10351: 
10352: # ------------------------------------------------------ third, check map parms
10353: 	    my %parmhash=();
10354: 	    my $thisparm='';
10355: 	    if (tie(%parmhash,'GDBM_File',
10356: 		    $env{'request.course.fn'}.'_parms.db',
10357: 		    &GDBM_READER(),0640)) {
10358: 		$thisparm=$parmhash{$symbparm};
10359: 		untie(%parmhash);
10360: 	    }
10361: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10362: 	}
10363: # ------------------------------------------ fourth, look in resource metadata
10364: 
10365: 	$spacequalifierrest=~s/\./\_/;
10366: 	my $filename;
10367: 	if (!$symbparm) { $symbparm=&symbread(); }
10368: 	if ($symbparm) {
10369: 	    $filename=(&decode_symb($symbparm))[2];
10370: 	} else {
10371: 	    $filename=$env{'request.filename'};
10372: 	}
10373: 	my $metadata=&metadata($filename,$spacequalifierrest);
10374: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10375: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10376: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10377: 
10378: # ---------------------------------------------- fourth, look in rest of course
10379: 	if ($symbparm && defined($courseid) && 
10380: 	    $courseid eq $env{'request.course.id'}) {
10381: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10382: 				     $env{'course.'.$courseid.'.domain'},
10383: 				     'course',
10384: 				     ([$courselevelm,'map'   ],
10385: 				      [$courselevel, 'course']));
10386: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10387: 	}
10388: # ------------------------------------------------------------------ Cascade up
10389: 	unless ($space eq '0') {
10390: 	    my @parts=split(/_/,$space);
10391: 	    my $id=pop(@parts);
10392: 	    my $part=join('_',@parts);
10393: 	    if ($part eq '') { $part='0'; }
10394: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10395: 				 $symbparm,$udom,$uname,$section,1);
10396: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10397: 	}
10398: 	if ($recurse) { return undef; }
10399: 	my $pack_def=&packages_tab_default($filename,$varname);
10400: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10401: # ---------------------------------------------------- Any other user namespace
10402:     } elsif ($realm eq 'environment') {
10403: # ----------------------------------------------------------------- environment
10404: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10405: 	    return $env{'environment.'.$spacequalifierrest};
10406: 	} else {
10407: 	    if ($uname eq 'anonymous' && $udom eq '') {
10408: 		return '';
10409: 	    }
10410: 	    my %returnhash=&userenvironment($udom,$uname,
10411: 					    $spacequalifierrest);
10412: 	    return $returnhash{$spacequalifierrest};
10413: 	}
10414:     } elsif ($realm eq 'system') {
10415: # ----------------------------------------------------------------- system.time
10416: 	if ($space eq 'time') {
10417: 	    return time;
10418:         }
10419:     } elsif ($realm eq 'server') {
10420: # ----------------------------------------------------------------- system.time
10421: 	if ($space eq 'name') {
10422: 	    return $ENV{'SERVER_NAME'};
10423:         }
10424:     }
10425:     return '';
10426: }
10427: 
10428: sub get_reply {
10429:     my ($reply_value) = @_;
10430:     if (ref($reply_value) eq 'ARRAY') {
10431:         if (wantarray) {
10432: 	    return @$reply_value;
10433:         }
10434:         return $reply_value->[0];
10435:     } else {
10436:         return $reply_value;
10437:     }
10438: }
10439: 
10440: sub check_group_parms {
10441:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10442:     my @groupitems = ();
10443:     my $resultitem;
10444:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10445:     foreach my $group (@{$groups}) {
10446:         foreach my $level (@levels) {
10447:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10448:              push(@groupitems,[$item,$level->[1]]);
10449:         }
10450:     }
10451:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10452:                             $env{'course.'.$courseid.'.domain'},
10453:                                      'course',@groupitems);
10454:     return $coursereply;
10455: }
10456: 
10457: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10458:     my ($courseid,@groups) = @_;
10459:     @groups = sort(@groups);
10460:     return @groups;
10461: }
10462: 
10463: sub packages_tab_default {
10464:     my ($uri,$varname)=@_;
10465:     my (undef,$part,$name)=split(/\./,$varname);
10466: 
10467:     my (@extension,@specifics,$do_default);
10468:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10469: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10470: 	if ($pack_type eq 'default') {
10471: 	    $do_default=1;
10472: 	} elsif ($pack_type eq 'extension') {
10473: 	    push(@extension,[$package,$pack_type,$pack_part]);
10474: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10475: 	    # only look at packages defaults for packages that this id is
10476: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10477: 	}
10478:     }
10479:     # first look for a package that matches the requested part id
10480:     foreach my $package (@specifics) {
10481: 	my (undef,$pack_type,$pack_part)=@{$package};
10482: 	next if ($pack_part ne $part);
10483: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10484: 	    return $packagetab{"$pack_type&$name&default"};
10485: 	}
10486:     }
10487:     # look for any possible matching non extension_ package
10488:     foreach my $package (@specifics) {
10489: 	my (undef,$pack_type,$pack_part)=@{$package};
10490: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10491: 	    return $packagetab{"$pack_type&$name&default"};
10492: 	}
10493: 	if ($pack_type eq 'part') { $pack_part='0'; }
10494: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10495: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10496: 	}
10497:     }
10498:     # look for any posible extension_ match
10499:     foreach my $package (@extension) {
10500: 	my ($package,$pack_type)=@{$package};
10501: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10502: 	    return $packagetab{"$pack_type&$name&default"};
10503: 	}
10504: 	if (defined($packagetab{$package."&$name&default"})) {
10505: 	    return $packagetab{$package."&$name&default"};
10506: 	}
10507:     }
10508:     # look for a global default setting
10509:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10510: 	return $packagetab{"default&$name&default"};
10511:     }
10512:     return undef;
10513: }
10514: 
10515: sub add_prefix_and_part {
10516:     my ($prefix,$part)=@_;
10517:     my $keyroot;
10518:     if (defined($prefix) && $prefix !~ /^__/) {
10519: 	# prefix that has a part already
10520: 	$keyroot=$prefix;
10521:     } elsif (defined($prefix)) {
10522: 	# prefix that is missing a part
10523: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10524:     } else {
10525: 	# no prefix at all
10526: 	if (defined($part)) { $keyroot='_'.$part; }
10527:     }
10528:     return $keyroot;
10529: }
10530: 
10531: # ---------------------------------------------------------------- Get metadata
10532: 
10533: my %metaentry;
10534: my %importedpartids;
10535: sub metadata {
10536:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10537:     $uri=&declutter($uri);
10538:     # if it is a non metadata possible uri return quickly
10539:     if (($uri eq '') || 
10540: 	(($uri =~ m|^/*adm/|) && 
10541: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10542:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10543: 	return undef;
10544:     }
10545:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10546: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10547: 	return undef;
10548:     }
10549:     my $filename=$uri;
10550:     $uri=~s/\.meta$//;
10551: #
10552: # Is the metadata already cached?
10553: # Look at timestamp of caching
10554: # Everything is cached by the main uri, libraries are never directly cached
10555: #
10556:     if (!defined($liburi)) {
10557: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10558: 	if (defined($cached)) { return $result->{':'.$what}; }
10559:     }
10560:     {
10561: # Imported parts would go here
10562:         my %importedids=();
10563:         my @origfileimportpartids=();
10564:         my $importedparts=0;
10565: #
10566: # Is this a recursive call for a library?
10567: #
10568: #	if (! exists($metacache{$uri})) {
10569: #	    $metacache{$uri}={};
10570: #	}
10571: 	my $cachetime = 60*60;
10572:         if ($liburi) {
10573: 	    $liburi=&declutter($liburi);
10574:             $filename=$liburi;
10575:         } else {
10576: 	    &devalidate_cache_new('meta',$uri);
10577: 	    undef(%metaentry);
10578: 	}
10579:         my %metathesekeys=();
10580:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10581: 	my $metastring;
10582: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10583: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10584: 	    $metastring = 
10585: 		&Apache::lonnet::ssi_body($which,
10586: 					  ('grade_target' => 'meta'));
10587: 	    $cachetime = 1; # only want this cached in the child not long term
10588: 	} elsif (($uri !~ m -^(editupload)/-) && 
10589:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10590: 	    my $file=&filelocation('',&clutter($filename));
10591: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10592: 	    $metastring=&getfile($file);
10593: 	}
10594:         my $parser=HTML::LCParser->new(\$metastring);
10595:         my $token;
10596:         undef %metathesekeys;
10597:         while ($token=$parser->get_token) {
10598: 	    if ($token->[0] eq 'S') {
10599: 		if (defined($token->[2]->{'package'})) {
10600: #
10601: # This is a package - get package info
10602: #
10603: 		    my $package=$token->[2]->{'package'};
10604: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10605: 		    if (defined($token->[2]->{'id'})) { 
10606: 			$keyroot.='_'.$token->[2]->{'id'}; 
10607: 		    }
10608: 		    if ($metaentry{':packages'}) {
10609: 			$metaentry{':packages'}.=','.$package.$keyroot;
10610: 		    } else {
10611: 			$metaentry{':packages'}=$package.$keyroot;
10612: 		    }
10613: 		    foreach my $pack_entry (keys(%packagetab)) {
10614: 			my $part=$keyroot;
10615: 			$part=~s/^\_//;
10616: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10617: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10618: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10619: 			    # ignore package.tab specified default values
10620:                             # here &package_tab_default() will fetch those
10621: 			    if ($subp eq 'default') { next; }
10622: 			    my $value=$packagetab{$pack_entry};
10623: 			    my $unikey;
10624: 			    if ($pack =~ /_0$/) {
10625: 				$unikey='parameter_0_'.$name;
10626: 				$part=0;
10627: 			    } else {
10628: 				$unikey='parameter'.$keyroot.'_'.$name;
10629: 			    }
10630: 			    if ($subp eq 'display') {
10631: 				$value.=' [Part: '.$part.']';
10632: 			    }
10633: 			    $metaentry{':'.$unikey.'.part'}=$part;
10634: 			    $metathesekeys{$unikey}=1;
10635: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10636: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10637: 			    }
10638: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10639: 				$metaentry{':'.$unikey}=
10640: 				    $metaentry{':'.$unikey.'.default'};
10641: 			    }
10642: 			}
10643: 		    }
10644: 		} else {
10645: #
10646: # This is not a package - some other kind of start tag
10647: #
10648: 		    my $entry=$token->[1];
10649: 		    my $unikey='';
10650: 
10651: 		    if ($entry eq 'import') {
10652: #
10653: # Importing a library here
10654: #
10655:                         my $location=$parser->get_text('/import');
10656:                         my $dir=$filename;
10657:                         $dir=~s|[^/]*$||;
10658:                         $location=&filelocation($dir,$location);
10659:                        
10660:                         my $importmode=$token->[2]->{'importmode'};
10661:                         if ($importmode eq 'problem') {
10662: # Import as problem/response
10663:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10664:                         } elsif ($importmode eq 'part') {
10665: # Import as part(s)
10666:                            $importedparts=1;
10667: # We need to get the original file and the imported file to get the part order correct
10668: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10669: # Load and inspect original file
10670:                            if ($#origfileimportpartids<0) {
10671:                               undef(%importedpartids);
10672:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10673:                               my $origfile=&getfile($origfilelocation);
10674:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10675:                            }
10676: 
10677: # Load and inspect imported file
10678:                            my $impfile=&getfile($location);
10679:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10680:                            if ($#impfilepartids>=0) {
10681: # This problem had parts
10682:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10683:                            } else {
10684: # Importing by turning a single problem into a problem part
10685: # It gets the import-tags ID as part-ID
10686:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10687:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10688:                            }
10689:                         } else {
10690: # Normal import
10691:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10692:                            if (defined($token->[2]->{'id'})) {
10693:                               $unikey.='_'.$token->[2]->{'id'};
10694:                            }
10695:                         }
10696: 
10697: 			if ($depthcount<20) {
10698: 			    my $metadata = 
10699: 				&metadata($uri,'keys', $location,$unikey,
10700: 					  $depthcount+1);
10701: 			    foreach my $meta (split(',',$metadata)) {
10702: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10703: 				$metathesekeys{$meta}=1;
10704: 			    }
10705: 			
10706:                         }
10707: 		    } else {
10708: #
10709: # Not importing, some other kind of non-package, non-library start tag
10710: # 
10711:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10712:                         if (defined($token->[2]->{'id'})) {
10713:                             $unikey.='_'.$token->[2]->{'id'};
10714:                         }
10715: 			if (defined($token->[2]->{'name'})) { 
10716: 			    $unikey.='_'.$token->[2]->{'name'}; 
10717: 			}
10718: 			$metathesekeys{$unikey}=1;
10719: 			foreach my $param (@{$token->[3]}) {
10720: 			    $metaentry{':'.$unikey.'.'.$param} =
10721: 				$token->[2]->{$param};
10722: 			}
10723: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10724: 			my $default=$metaentry{':'.$unikey.'.default'};
10725: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10726: 		 # only ws inside the tag, and not in default, so use default
10727: 		 # as value
10728: 			    $metaentry{':'.$unikey}=$default;
10729: 			} elsif ( $internaltext =~ /\S/ ) {
10730: 		  # something interesting inside the tag
10731: 			    $metaentry{':'.$unikey}=$internaltext;
10732: 			} else {
10733: 		  # no interesting values, don't set a default
10734: 			}
10735: # end of not-a-package not-a-library import
10736: 		    }
10737: # end of not-a-package start tag
10738: 		}
10739: # the next is the end of "start tag"
10740: 	    }
10741: 	}
10742: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10743: 	$extension = lc($extension);
10744: 	if ($extension eq 'htm') { $extension='html'; }
10745: 
10746: 	foreach my $key (keys(%packagetab)) {
10747: 	    #no specific packages #how's our extension
10748: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10749: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10750: 					 \%metathesekeys);
10751: 	}
10752: 
10753: 	if (!exists($metaentry{':packages'})
10754: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10755: 	    foreach my $key (keys(%packagetab)) {
10756: 		#no specific packages well let's get default then
10757: 		if ($key!~/^default&/) { next; }
10758: 		&metadata_create_package_def($uri,$key,'default',
10759: 					     \%metathesekeys);
10760: 	    }
10761: 	}
10762: # are there custom rights to evaluate
10763: 	if ($metaentry{':copyright'} eq 'custom') {
10764: 
10765:     #
10766:     # Importing a rights file here
10767:     #
10768: 	    unless ($depthcount) {
10769: 		my $location=$metaentry{':customdistributionfile'};
10770: 		my $dir=$filename;
10771: 		$dir=~s|[^/]*$||;
10772: 		$location=&filelocation($dir,$location);
10773: 		my $rights_metadata =
10774: 		    &metadata($uri,'keys',$location,'_rights',
10775: 			      $depthcount+1);
10776: 		foreach my $rights (split(',',$rights_metadata)) {
10777: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10778: 		    $metathesekeys{$rights}=1;
10779: 		}
10780: 	    }
10781: 	}
10782: 	# uniqifiy package listing
10783: 	my %seen;
10784: 	my @uniq_packages =
10785: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10786: 	$metaentry{':packages'} = join(',',@uniq_packages);
10787: 
10788:         if ($importedparts) {
10789: # We had imported parts and need to rebuild partorder
10790:            $metaentry{':partorder'}='';
10791:            $metathesekeys{'partorder'}=1;
10792:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10793:                if ($origfileimportpartids[$index] eq 'part') {
10794: # original part, part of the problem
10795:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10796:                } else {
10797: # we have imported parts at this position
10798:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10799:                }
10800:            }
10801:            $metaentry{':partorder'}=~s/^\,//;
10802:         }
10803: 
10804: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10805: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10806: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10807: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10808: # this is the end of "was not already recently cached
10809:     }
10810:     return $metaentry{':'.$what};
10811: }
10812: 
10813: sub metadata_create_package_def {
10814:     my ($uri,$key,$package,$metathesekeys)=@_;
10815:     my ($pack,$name,$subp)=split(/\&/,$key);
10816:     if ($subp eq 'default') { next; }
10817:     
10818:     if (defined($metaentry{':packages'})) {
10819: 	$metaentry{':packages'}.=','.$package;
10820:     } else {
10821: 	$metaentry{':packages'}=$package;
10822:     }
10823:     my $value=$packagetab{$key};
10824:     my $unikey;
10825:     $unikey='parameter_0_'.$name;
10826:     $metaentry{':'.$unikey.'.part'}=0;
10827:     $$metathesekeys{$unikey}=1;
10828:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10829: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10830:     }
10831:     if (defined($metaentry{':'.$unikey.'.default'})) {
10832: 	$metaentry{':'.$unikey}=
10833: 	    $metaentry{':'.$unikey.'.default'};
10834:     }
10835: }
10836: 
10837: sub metadata_generate_part0 {
10838:     my ($metadata,$metacache,$uri) = @_;
10839:     my %allnames;
10840:     foreach my $metakey (keys(%$metadata)) {
10841: 	if ($metakey=~/^parameter\_(.*)/) {
10842: 	  my $part=$$metacache{':'.$metakey.'.part'};
10843: 	  my $name=$$metacache{':'.$metakey.'.name'};
10844: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10845: 	    $allnames{$name}=$part;
10846: 	  }
10847: 	}
10848:     }
10849:     foreach my $name (keys(%allnames)) {
10850:       $$metadata{"parameter_0_$name"}=1;
10851:       my $key=":parameter_0_$name";
10852:       $$metacache{"$key.part"}='0';
10853:       $$metacache{"$key.name"}=$name;
10854:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10855: 					   $allnames{$name}.'_'.$name.
10856: 					   '.type'};
10857:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10858: 			     '.display'};
10859:       my $expr='[Part: '.$allnames{$name}.']';
10860:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10861:       $$metacache{"$key.display"}=$olddis;
10862:     }
10863: }
10864: 
10865: # ------------------------------------------------------ Devalidate title cache
10866: 
10867: sub devalidate_title_cache {
10868:     my ($url)=@_;
10869:     if (!$env{'request.course.id'}) { return; }
10870:     my $symb=&symbread($url);
10871:     if (!$symb) { return; }
10872:     my $key=$env{'request.course.id'}."\0".$symb;
10873:     &devalidate_cache_new('title',$key);
10874: }
10875: 
10876: # ------------------------------------------------- Get the title of a course
10877: 
10878: sub current_course_title {
10879:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10880: }
10881: # ------------------------------------------------- Get the title of a resource
10882: 
10883: sub gettitle {
10884:     my $urlsymb=shift;
10885:     my $symb=&symbread($urlsymb);
10886:     if ($symb) {
10887: 	my $key=$env{'request.course.id'}."\0".$symb;
10888: 	my ($result,$cached)=&is_cached_new('title',$key);
10889: 	if (defined($cached)) { 
10890: 	    return $result;
10891: 	}
10892: 	my ($map,$resid,$url)=&decode_symb($symb);
10893: 	my $title='';
10894: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10895: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10896: 	} else {
10897: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10898: 		    &GDBM_READER(),0640)) {
10899: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10900: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10901: 		untie(%bighash);
10902: 	    }
10903: 	}
10904: 	$title=~s/\&colon\;/\:/gs;
10905: 	if ($title) {
10906: # Remember both $symb and $title for dynamic metadata
10907:             $accesshash{$symb.'___crstitle'}=$title;
10908:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10909: # Cache this title and then return it
10910: 	    return &do_cache_new('title',$key,$title,600);
10911: 	}
10912: 	$urlsymb=$url;
10913:     }
10914:     my $title=&metadata($urlsymb,'title');
10915:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10916:     return $title;
10917: }
10918: 
10919: sub get_slot {
10920:     my ($which,$cnum,$cdom)=@_;
10921:     if (!$cnum || !$cdom) {
10922: 	(undef,my $courseid)=&whichuser();
10923: 	$cdom=$env{'course.'.$courseid.'.domain'};
10924: 	$cnum=$env{'course.'.$courseid.'.num'};
10925:     }
10926:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10927:     my %slotinfo;
10928:     if (exists($remembered{$key})) {
10929: 	$slotinfo{$which} = $remembered{$key};
10930:     } else {
10931: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10932: 	&Apache::lonhomework::showhash(%slotinfo);
10933: 	my ($tmp)=keys(%slotinfo);
10934: 	if ($tmp=~/^error:/) { return (); }
10935: 	$remembered{$key} = $slotinfo{$which};
10936:     }
10937:     if (ref($slotinfo{$which}) eq 'HASH') {
10938: 	return %{$slotinfo{$which}};
10939:     }
10940:     return $slotinfo{$which};
10941: }
10942: 
10943: sub get_reservable_slots {
10944:     my ($cnum,$cdom,$uname,$udom) = @_;
10945:     my $now = time;
10946:     my $reservable_info;
10947:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10948:     if (exists($remembered{$key})) {
10949:         $reservable_info = $remembered{$key};
10950:     } else {
10951:         my %resv;
10952:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10953:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10954:         $reservable_info = \%resv;
10955:         $remembered{$key} = $reservable_info;
10956:     }
10957:     return $reservable_info;
10958: }
10959: 
10960: sub get_course_slots {
10961:     my ($cnum,$cdom) = @_;
10962:     my $hashid=$cnum.':'.$cdom;
10963:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10964:     if (defined($cached)) {
10965:         if (ref($result) eq 'HASH') {
10966:             return %{$result};
10967:         }
10968:     } else {
10969:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10970:         my ($tmp) = keys(%slots);
10971:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10972:             &do_cache_new('allslots',$hashid,\%slots,600);
10973:             return %slots;
10974:         }
10975:     }
10976:     return;
10977: }
10978: 
10979: sub devalidate_slots_cache {
10980:     my ($cnum,$cdom)=@_;
10981:     my $hashid=$cnum.':'.$cdom;
10982:     &devalidate_cache_new('allslots',$hashid);
10983: }
10984: 
10985: sub get_coursechange {
10986:     my ($cdom,$cnum) = @_;
10987:     if ($cdom eq '' || $cnum eq '') {
10988:         return unless ($env{'request.course.id'});
10989:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10990:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10991:     }
10992:     my $hashid=$cdom.'_'.$cnum;
10993:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10994:     if ((defined($cached)) && ($change ne '')) {
10995:         return $change;
10996:     } else {
10997:         my %crshash;
10998:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10999:         if ($crshash{'internal.contentchange'} eq '') {
11000:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11001:             if ($change eq '') {
11002:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11003:                 $change = $crshash{'internal.created'};
11004:             }
11005:         } else {
11006:             $change = $crshash{'internal.contentchange'};
11007:         }
11008:         my $cachetime = 600;
11009:         &do_cache_new('crschange',$hashid,$change,$cachetime);
11010:     }
11011:     return $change;
11012: }
11013: 
11014: sub devalidate_coursechange_cache {
11015:     my ($cnum,$cdom)=@_;
11016:     my $hashid=$cnum.':'.$cdom;
11017:     &devalidate_cache_new('crschange',$hashid);
11018: }
11019: 
11020: # ------------------------------------------------- Update symbolic store links
11021: 
11022: sub symblist {
11023:     my ($mapname,%newhash)=@_;
11024:     $mapname=&deversion(&declutter($mapname));
11025:     my %hash;
11026:     if (($env{'request.course.fn'}) && (%newhash)) {
11027:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11028:                       &GDBM_WRCREAT(),0640)) {
11029: 	    foreach my $url (keys(%newhash)) {
11030: 		next if ($url eq 'last_known'
11031: 			 && $env{'form.no_update_last_known'});
11032: 		$hash{declutter($url)}=&encode_symb($mapname,
11033: 						    $newhash{$url}->[1],
11034: 						    $newhash{$url}->[0]);
11035:             }
11036:             if (untie(%hash)) {
11037: 		return 'ok';
11038:             }
11039:         }
11040:     }
11041:     return 'error';
11042: }
11043: 
11044: # --------------------------------------------------------------- Verify a symb
11045: 
11046: sub symbverify {
11047:     my ($symb,$thisurl,$encstate)=@_;
11048:     my $thisfn=$thisurl;
11049:     $thisfn=&declutter($thisfn);
11050: # direct jump to resource in page or to a sequence - will construct own symbs
11051:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11052: # check URL part
11053:     my ($map,$resid,$url)=&decode_symb($symb);
11054: 
11055:     unless ($url eq $thisfn) { return 0; }
11056: 
11057:     $symb=&symbclean($symb);
11058:     $thisurl=&deversion($thisurl);
11059:     $thisfn=&deversion($thisfn);
11060: 
11061:     my %bighash;
11062:     my $okay=0;
11063: 
11064:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11065:                             &GDBM_READER(),0640)) {
11066:         my $noclutter;
11067:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11068:             $thisurl =~ s/\?.+$//;
11069:             if ($map =~ m{^uploaded/.+\.page$}) {
11070:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11071:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
11072:                 $noclutter = 1;
11073:             }
11074:         }
11075:         my $ids;
11076:         if ($noclutter) {
11077:             $ids=$bighash{'ids_'.$thisurl};
11078:         } else {
11079:             $ids=$bighash{'ids_'.&clutter($thisurl)};
11080:         }
11081:         unless ($ids) {
11082:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
11083:             $ids=$bighash{$idkey};
11084:         }
11085:         if ($ids) {
11086: # ------------------------------------------------------------------- Has ID(s)
11087:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11088:                 $symb =~ s/\?.+$//;
11089:             }
11090: 	    foreach my $id (split(/\,/,$ids)) {
11091: 	       my ($mapid,$resid)=split(/\./,$id);
11092:                if (
11093:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11094:    eq $symb) {
11095:                    if (ref($encstate)) {
11096:                        $$encstate = $bighash{'encrypted_'.$id};
11097:                    }
11098: 		   if (($env{'request.role.adv'}) ||
11099: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11100:                        ($thisurl eq '/adm/navmaps')) {
11101: 		       $okay=1;
11102:                        last;
11103: 		   }
11104: 	       }
11105: 	   }
11106:         }
11107: 	untie(%bighash);
11108:     }
11109:     return $okay;
11110: }
11111: 
11112: # --------------------------------------------------------------- Clean-up symb
11113: 
11114: sub symbclean {
11115:     my $symb=shift;
11116:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11117: # remove version from map
11118:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11119: 
11120: # remove version from URL
11121:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11122: 
11123: # remove wrapper
11124: 
11125:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11126:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11127:     return $symb;
11128: }
11129: 
11130: # ---------------------------------------------- Split symb to find map and url
11131: 
11132: sub encode_symb {
11133:     my ($map,$resid,$url)=@_;
11134:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11135: }
11136: 
11137: sub decode_symb {
11138:     my $symb=shift;
11139:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11140:     my ($map,$resid,$url)=split(/___/,$symb);
11141:     return (&fixversion($map),$resid,&fixversion($url));
11142: }
11143: 
11144: sub fixversion {
11145:     my $fn=shift;
11146:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11147:     my %bighash;
11148:     my $uri=&clutter($fn);
11149:     my $key=$env{'request.course.id'}.'_'.$uri;
11150: # is this cached?
11151:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11152:     if (defined($cached)) { return $result; }
11153: # unfortunately not cached, or expired
11154:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11155: 	    &GDBM_READER(),0640)) {
11156:  	if ($bighash{'version_'.$uri}) {
11157:  	    my $version=$bighash{'version_'.$uri};
11158:  	    unless (($version eq 'mostrecent') || 
11159: 		    ($version==&getversion($uri))) {
11160:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11161:  	    }
11162:  	}
11163:  	untie %bighash;
11164:     }
11165:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11166: }
11167: 
11168: sub deversion {
11169:     my $url=shift;
11170:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11171:     return $url;
11172: }
11173: 
11174: # ------------------------------------------------------ Return symb list entry
11175: 
11176: sub symbread {
11177:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
11178:     my $cache_str='request.symbread.cached.'.$thisfn;
11179:     if (defined($env{$cache_str})) {
11180:         if ($ignorecachednull) {
11181:             return $env{$cache_str} unless ($env{$cache_str} eq '');
11182:         } else {
11183:             return $env{$cache_str};
11184:         }
11185:     }
11186: # no filename provided? try from environment
11187:     unless ($thisfn) {
11188:         if ($env{'request.symb'}) {
11189: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
11190: 	}
11191: 	$thisfn=$env{'request.filename'};
11192:     }
11193:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11194: # is that filename actually a symb? Verify, clean, and return
11195:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11196: 	if (&symbverify($thisfn,$1)) {
11197: 	    return $env{$cache_str}=&symbclean($thisfn);
11198: 	}
11199:     }
11200:     $thisfn=declutter($thisfn);
11201:     my %hash;
11202:     my %bighash;
11203:     my $syval='';
11204:     if (($env{'request.course.fn'}) && ($thisfn)) {
11205:         my $targetfn = $thisfn;
11206:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11207:             $targetfn = 'adm/wrapper/'.$thisfn;
11208:         }
11209: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11210: 	    $targetfn=$1;
11211: 	}
11212:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11213:                       &GDBM_READER(),0640)) {
11214: 	    $syval=$hash{$targetfn};
11215:             untie(%hash);
11216:         }
11217: # ---------------------------------------------------------- There was an entry
11218:         if ($syval) {
11219: 	    #unless ($syval=~/\_\d+$/) {
11220: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11221: 		    #&appenv({'request.ambiguous' => $thisfn});
11222: 		    #return $env{$cache_str}='';
11223: 		#}    
11224: 		#$syval.=$1;
11225: 	    #}
11226:         } else {
11227: # ------------------------------------------------------- Was not in symb table
11228:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11229:                             &GDBM_READER(),0640)) {
11230: # ---------------------------------------------- Get ID(s) for current resource
11231:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11232:               unless ($ids) { 
11233:                  $ids=$bighash{'ids_/'.$thisfn};
11234:               }
11235:               unless ($ids) {
11236: # alias?
11237: 		  $ids=$bighash{'mapalias_'.$thisfn};
11238:               }
11239:               if ($ids) {
11240: # ------------------------------------------------------------------- Has ID(s)
11241:                  my @possibilities=split(/\,/,$ids);
11242:                  if ($#possibilities==0) {
11243: # ----------------------------------------------- There is only one possibility
11244: 		     my ($mapid,$resid)=split(/\./,$ids);
11245: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11246: 						    $resid,$thisfn);
11247:                      if (ref($possibles) eq 'HASH') {
11248:                          $possibles->{$syval} = 1;    
11249:                      }
11250:                      if ($checkforblock) {
11251:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11252:                          if (@blockers) {
11253:                              $syval = '';
11254:                              return;
11255:                          }
11256:                      }
11257:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
11258: # ------------------------------------------ There is more than one possibility
11259:                      my $realpossible=0;
11260:                      foreach my $id (@possibilities) {
11261: 			 my $file=$bighash{'src_'.$id};
11262:                          my $canaccess;
11263:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11264:                              $canaccess = 1;
11265:                          } else { 
11266:                              $canaccess = &allowed('bre',$file);
11267:                          }
11268:                          if ($canaccess) {
11269:          		     my ($mapid,$resid)=split(/\./,$id);
11270:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
11271:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11272: 						             $resid,$thisfn);
11273:                                  if (ref($possibles) eq 'HASH') {
11274:                                      $possibles->{$syval} = 1;
11275:                                  }
11276:                                  if ($checkforblock) {
11277:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11278:                                      unless (@blockers > 0) {
11279:                                          $syval = $poss_syval;
11280:                                          $realpossible++;
11281:                                      }
11282:                                  } else {
11283:                                      $syval = $poss_syval;
11284:                                      $realpossible++;
11285:                                  }
11286:                              }
11287: 			 }
11288:                      }
11289: 		     if ($realpossible!=1) { $syval=''; }
11290:                  } else {
11291:                      $syval='';
11292:                  }
11293: 	      }
11294:               untie(%bighash);
11295:            }
11296:         }
11297:         if ($syval) {
11298: 	    return $env{$cache_str}=$syval;
11299:         }
11300:     }
11301:     &appenv({'request.ambiguous' => $thisfn});
11302:     return $env{$cache_str}='';
11303: }
11304: 
11305: # ---------------------------------------------------------- Return random seed
11306: 
11307: sub numval {
11308:     my $txt=shift;
11309:     $txt=~tr/A-J/0-9/;
11310:     $txt=~tr/a-j/0-9/;
11311:     $txt=~tr/K-T/0-9/;
11312:     $txt=~tr/k-t/0-9/;
11313:     $txt=~tr/U-Z/0-5/;
11314:     $txt=~tr/u-z/0-5/;
11315:     $txt=~s/\D//g;
11316:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11317:     return int($txt);
11318: }
11319: 
11320: sub numval2 {
11321:     my $txt=shift;
11322:     $txt=~tr/A-J/0-9/;
11323:     $txt=~tr/a-j/0-9/;
11324:     $txt=~tr/K-T/0-9/;
11325:     $txt=~tr/k-t/0-9/;
11326:     $txt=~tr/U-Z/0-5/;
11327:     $txt=~tr/u-z/0-5/;
11328:     $txt=~s/\D//g;
11329:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11330:     my $total;
11331:     foreach my $val (@txts) { $total+=$val; }
11332:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11333:     return int($total);
11334: }
11335: 
11336: sub numval3 {
11337:     use integer;
11338:     my $txt=shift;
11339:     $txt=~tr/A-J/0-9/;
11340:     $txt=~tr/a-j/0-9/;
11341:     $txt=~tr/K-T/0-9/;
11342:     $txt=~tr/k-t/0-9/;
11343:     $txt=~tr/U-Z/0-5/;
11344:     $txt=~tr/u-z/0-5/;
11345:     $txt=~s/\D//g;
11346:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11347:     my $total;
11348:     foreach my $val (@txts) { $total+=$val; }
11349:     if ($_64bit) { $total=(($total<<32)>>32); }
11350:     return $total;
11351: }
11352: 
11353: sub digest {
11354:     my ($data)=@_;
11355:     my $digest=&Digest::MD5::md5($data);
11356:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11357:     my ($e,$f);
11358:     {
11359:         use integer;
11360:         $e=($a+$b);
11361:         $f=($c+$d);
11362:         if ($_64bit) {
11363:             $e=(($e<<32)>>32);
11364:             $f=(($f<<32)>>32);
11365:         }
11366:     }
11367:     if (wantarray) {
11368: 	return ($e,$f);
11369:     } else {
11370: 	my $g;
11371: 	{
11372: 	    use integer;
11373: 	    $g=($e+$f);
11374: 	    if ($_64bit) {
11375: 		$g=(($g<<32)>>32);
11376: 	    }
11377: 	}
11378: 	return $g;
11379:     }
11380: }
11381: 
11382: sub latest_rnd_algorithm_id {
11383:     return '64bit5';
11384: }
11385: 
11386: sub get_rand_alg {
11387:     my ($courseid)=@_;
11388:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11389:     if ($courseid) {
11390: 	return $env{"course.$courseid.rndseed"};
11391:     }
11392:     return &latest_rnd_algorithm_id();
11393: }
11394: 
11395: sub validCODE {
11396:     my ($CODE)=@_;
11397:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11398:     return 0;
11399: }
11400: 
11401: sub getCODE {
11402:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11403:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11404: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11405: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11406: 	return $Apache::lonhomework::history{'resource.CODE'};
11407:     }
11408:     return undef;
11409: }
11410: #
11411: #  Determines the random seed for a specific context:
11412: #
11413: # parameters:
11414: #   symb      - in course context the symb for the seed.
11415: #   course_id - The course id of the form domain_coursenum.
11416: #   domain    - Domain for the user.
11417: #   course    - Course for the user.
11418: #   cenv      - environment of the course.
11419: #
11420: # NOTE:
11421: #   All parameters are picked out of the environment if missing
11422: #   or not defined.
11423: #   If a symb cannot be determined the current time is used instead.
11424: #
11425: #  For a given well defined symb, courside, domain, username,
11426: #  and course environment, the seed is reproducible.
11427: #
11428: sub rndseed {
11429:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11430:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11431:     if (!defined($symb)) {
11432: 	unless ($symb=$wsymb) { return time; }
11433:     }
11434:     if (!defined $courseid) { 
11435: 	$courseid=$wcourseid; 
11436:     }
11437:     if (!defined $domain) { $domain=$wdomain; }
11438:     if (!defined $username) { $username=$wusername }
11439: 
11440:     my $which;
11441:     if (defined($cenv->{'rndseed'})) {
11442: 	$which = $cenv->{'rndseed'};
11443:     } else {
11444: 	$which =&get_rand_alg($courseid);
11445:     }
11446:     if (defined(&getCODE())) {
11447: 
11448: 	if ($which eq '64bit5') {
11449: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11450: 	} elsif ($which eq '64bit4') {
11451: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11452: 	} else {
11453: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11454: 	}
11455:     } elsif ($which eq '64bit5') {
11456: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11457:     } elsif ($which eq '64bit4') {
11458: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11459:     } elsif ($which eq '64bit3') {
11460: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11461:     } elsif ($which eq '64bit2') {
11462: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11463:     } elsif ($which eq '64bit') {
11464: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11465:     }
11466:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11467: }
11468: 
11469: sub rndseed_32bit {
11470:     my ($symb,$courseid,$domain,$username)=@_;
11471:     {
11472: 	use integer;
11473: 	my $symbchck=unpack("%32C*",$symb) << 27;
11474: 	my $symbseed=numval($symb) << 22;
11475: 	my $namechck=unpack("%32C*",$username) << 17;
11476: 	my $nameseed=numval($username) << 12;
11477: 	my $domainseed=unpack("%32C*",$domain) << 7;
11478: 	my $courseseed=unpack("%32C*",$courseid);
11479: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11480: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11481: 	#&logthis("rndseed :$num:$symb");
11482: 	if ($_64bit) { $num=(($num<<32)>>32); }
11483: 	return $num;
11484:     }
11485: }
11486: 
11487: sub rndseed_64bit {
11488:     my ($symb,$courseid,$domain,$username)=@_;
11489:     {
11490: 	use integer;
11491: 	my $symbchck=unpack("%32S*",$symb) << 21;
11492: 	my $symbseed=numval($symb) << 10;
11493: 	my $namechck=unpack("%32S*",$username);
11494: 	
11495: 	my $nameseed=numval($username) << 21;
11496: 	my $domainseed=unpack("%32S*",$domain) << 10;
11497: 	my $courseseed=unpack("%32S*",$courseid);
11498: 	
11499: 	my $num1=$symbchck+$symbseed+$namechck;
11500: 	my $num2=$nameseed+$domainseed+$courseseed;
11501: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11502: 	#&logthis("rndseed :$num:$symb");
11503: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11504: 	return "$num1,$num2";
11505:     }
11506: }
11507: 
11508: sub rndseed_64bit2 {
11509:     my ($symb,$courseid,$domain,$username)=@_;
11510:     {
11511: 	use integer;
11512: 	# strings need to be an even # of cahracters long, it it is odd the
11513:         # last characters gets thrown away
11514: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11515: 	my $symbseed=numval($symb) << 10;
11516: 	my $namechck=unpack("%32S*",$username.' ');
11517: 	
11518: 	my $nameseed=numval($username) << 21;
11519: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11520: 	my $courseseed=unpack("%32S*",$courseid.' ');
11521: 	
11522: 	my $num1=$symbchck+$symbseed+$namechck;
11523: 	my $num2=$nameseed+$domainseed+$courseseed;
11524: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11525: 	#&logthis("rndseed :$num:$symb");
11526: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11527: 	return "$num1,$num2";
11528:     }
11529: }
11530: 
11531: sub rndseed_64bit3 {
11532:     my ($symb,$courseid,$domain,$username)=@_;
11533:     {
11534: 	use integer;
11535: 	# strings need to be an even # of cahracters long, it it is odd the
11536:         # last characters gets thrown away
11537: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11538: 	my $symbseed=numval2($symb) << 10;
11539: 	my $namechck=unpack("%32S*",$username.' ');
11540: 	
11541: 	my $nameseed=numval2($username) << 21;
11542: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11543: 	my $courseseed=unpack("%32S*",$courseid.' ');
11544: 	
11545: 	my $num1=$symbchck+$symbseed+$namechck;
11546: 	my $num2=$nameseed+$domainseed+$courseseed;
11547: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11548: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11549: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11550: 	
11551: 	return "$num1:$num2";
11552:     }
11553: }
11554: 
11555: sub rndseed_64bit4 {
11556:     my ($symb,$courseid,$domain,$username)=@_;
11557:     {
11558: 	use integer;
11559: 	# strings need to be an even # of cahracters long, it it is odd the
11560:         # last characters gets thrown away
11561: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11562: 	my $symbseed=numval3($symb) << 10;
11563: 	my $namechck=unpack("%32S*",$username.' ');
11564: 	
11565: 	my $nameseed=numval3($username) << 21;
11566: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11567: 	my $courseseed=unpack("%32S*",$courseid.' ');
11568: 	
11569: 	my $num1=$symbchck+$symbseed+$namechck;
11570: 	my $num2=$nameseed+$domainseed+$courseseed;
11571: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11572: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11573: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11574: 	
11575: 	return "$num1:$num2";
11576:     }
11577: }
11578: 
11579: sub rndseed_64bit5 {
11580:     my ($symb,$courseid,$domain,$username)=@_;
11581:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11582:     return "$num1:$num2";
11583: }
11584: 
11585: sub rndseed_CODE_64bit {
11586:     my ($symb,$courseid,$domain,$username)=@_;
11587:     {
11588: 	use integer;
11589: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11590: 	my $symbseed=numval2($symb);
11591: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11592: 	my $CODEseed=numval(&getCODE());
11593: 	my $courseseed=unpack("%32S*",$courseid.' ');
11594: 	my $num1=$symbseed+$CODEchck;
11595: 	my $num2=$CODEseed+$courseseed+$symbchck;
11596: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11597: 	#&logthis("rndseed :$num1:$num2:$symb");
11598: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11599: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11600: 	return "$num1:$num2";
11601:     }
11602: }
11603: 
11604: sub rndseed_CODE_64bit4 {
11605:     my ($symb,$courseid,$domain,$username)=@_;
11606:     {
11607: 	use integer;
11608: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11609: 	my $symbseed=numval3($symb);
11610: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11611: 	my $CODEseed=numval3(&getCODE());
11612: 	my $courseseed=unpack("%32S*",$courseid.' ');
11613: 	my $num1=$symbseed+$CODEchck;
11614: 	my $num2=$CODEseed+$courseseed+$symbchck;
11615: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11616: 	#&logthis("rndseed :$num1:$num2:$symb");
11617: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11618: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11619: 	return "$num1:$num2";
11620:     }
11621: }
11622: 
11623: sub rndseed_CODE_64bit5 {
11624:     my ($symb,$courseid,$domain,$username)=@_;
11625:     my $code = &getCODE();
11626:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11627:     return "$num1:$num2";
11628: }
11629: 
11630: sub setup_random_from_rndseed {
11631:     my ($rndseed)=@_;
11632:     if ($rndseed =~/([,:])/) {
11633:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11634:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11635:             &Math::Random::random_set_seed_from_phrase($rndseed);
11636:         } else {
11637:             &Math::Random::random_set_seed($num1,$num2);
11638:         }
11639:     } else {
11640: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11641:     }
11642: }
11643: 
11644: sub latest_receipt_algorithm_id {
11645:     return 'receipt3';
11646: }
11647: 
11648: sub recunique {
11649:     my $fucourseid=shift;
11650:     my $unique;
11651:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11652: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11653: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11654:     } else {
11655: 	$unique=$perlvar{'lonReceipt'};
11656:     }
11657:     return unpack("%32C*",$unique);
11658: }
11659: 
11660: sub recprefix {
11661:     my $fucourseid=shift;
11662:     my $prefix;
11663:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11664: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11665: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11666:     } else {
11667: 	$prefix=$perlvar{'lonHostID'};
11668:     }
11669:     return unpack("%32C*",$prefix);
11670: }
11671: 
11672: sub ireceipt {
11673:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11674: 
11675:     my $return =&recprefix($fucourseid).'-';
11676: 
11677:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11678: 	$env{'request.state'} eq 'construct') {
11679: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11680: 	return $return;
11681:     }
11682: 
11683:     my $cuname=unpack("%32C*",$funame);
11684:     my $cudom=unpack("%32C*",$fudom);
11685:     my $cucourseid=unpack("%32C*",$fucourseid);
11686:     my $cusymb=unpack("%32C*",$fusymb);
11687:     my $cunique=&recunique($fucourseid);
11688:     my $cpart=unpack("%32S*",$part);
11689:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11690: 
11691: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11692: 			       
11693: 	$return.= ($cunique%$cuname+
11694: 		   $cunique%$cudom+
11695: 		   $cusymb%$cuname+
11696: 		   $cusymb%$cudom+
11697: 		   $cucourseid%$cuname+
11698: 		   $cucourseid%$cudom+
11699: 		   $cpart%$cuname+
11700: 		   $cpart%$cudom);
11701:     } else {
11702: 	$return.= ($cunique%$cuname+
11703: 		   $cunique%$cudom+
11704: 		   $cusymb%$cuname+
11705: 		   $cusymb%$cudom+
11706: 		   $cucourseid%$cuname+
11707: 		   $cucourseid%$cudom);
11708:     }
11709:     return $return;
11710: }
11711: 
11712: sub receipt {
11713:     my ($part)=@_;
11714:     my ($symb,$courseid,$domain,$name) = &whichuser();
11715:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11716: }
11717: 
11718: sub whichuser {
11719:     my ($passedsymb)=@_;
11720:     my ($symb,$courseid,$domain,$name,$publicuser);
11721:     if (defined($env{'form.grade_symb'})) {
11722: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11723: 	my $allowed=&allowed('vgr',$tmp_courseid);
11724: 	if (!$allowed &&
11725: 	    exists($env{'request.course.sec'}) &&
11726: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11727: 	    $allowed=&allowed('vgr',$tmp_courseid.
11728: 			      '/'.$env{'request.course.sec'});
11729: 	}
11730: 	if ($allowed) {
11731: 	    ($symb)=&get_env_multiple('form.grade_symb');
11732: 	    $courseid=$tmp_courseid;
11733: 	    ($domain)=&get_env_multiple('form.grade_domain');
11734: 	    ($name)=&get_env_multiple('form.grade_username');
11735: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11736: 	}
11737:     }
11738:     if (!$passedsymb) {
11739: 	$symb=&symbread();
11740:     } else {
11741: 	$symb=$passedsymb;
11742:     }
11743:     $courseid=$env{'request.course.id'};
11744:     $domain=$env{'user.domain'};
11745:     $name=$env{'user.name'};
11746:     if ($name eq 'public' && $domain eq 'public') {
11747: 	if (!defined($env{'form.username'})) {
11748: 	    $env{'form.username'}.=time.rand(10000000);
11749: 	}
11750: 	$name.=$env{'form.username'};
11751:     }
11752:     return ($symb,$courseid,$domain,$name,$publicuser);
11753: 
11754: }
11755: 
11756: # ------------------------------------------------------------ Serves up a file
11757: # returns either the contents of the file or 
11758: # -1 if the file doesn't exist
11759: #
11760: # if the target is a file that was uploaded via DOCS, 
11761: # a check will be made to see if a current copy exists on the local server,
11762: # if it does this will be served, otherwise a copy will be retrieved from
11763: # the home server for the course and stored in /home/httpd/html/userfiles on
11764: # the local server.   
11765: 
11766: sub getfile {
11767:     my ($file) = @_;
11768:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11769:     &repcopy($file);
11770:     return &readfile($file);
11771: }
11772: 
11773: sub repcopy_userfile {
11774:     my ($file)=@_;
11775:     my $londocroot = $perlvar{'lonDocRoot'};
11776:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11777:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11778:     my ($cdom,$cnum,$filename) = 
11779: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11780:     my $uri="/uploaded/$cdom/$cnum/$filename";
11781:     if (-e "$file") {
11782: # we already have a local copy, check it out
11783: 	my @fileinfo = stat($file);
11784: 	my $rtncode;
11785: 	my $info;
11786: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11787: 	if ($lwpresp ne 'ok') {
11788: # there is no such file anymore, even though we had a local copy
11789: 	    if ($rtncode eq '404') {
11790: 		unlink($file);
11791: 	    }
11792: 	    return -1;
11793: 	}
11794: 	if ($info < $fileinfo[9]) {
11795: # nice, the file we have is up-to-date, just say okay
11796: 	    return 'ok';
11797: 	} else {
11798: # the file is outdated, get rid of it
11799: 	    unlink($file);
11800: 	}
11801:     }
11802: # one way or the other, at this point, we don't have the file
11803: # construct the correct path for the file
11804:     my @parts = ($cdom,$cnum); 
11805:     if ($filename =~ m|^(.+)/[^/]+$|) {
11806: 	push @parts, split(/\//,$1);
11807:     }
11808:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11809:     foreach my $part (@parts) {
11810: 	$path .= '/'.$part;
11811: 	if (!-e $path) {
11812: 	    mkdir($path,0770);
11813: 	}
11814:     }
11815: # now the path exists for sure
11816: # get a user agent
11817:     my $ua=new LWP::UserAgent;
11818:     my $transferfile=$file.'.in.transfer';
11819: # FIXME: this should flock
11820:     if (-e $transferfile) { return 'ok'; }
11821:     my $request;
11822:     $uri=~s/^\///;
11823:     my $homeserver = &homeserver($cnum,$cdom);
11824:     my $protocol = $protocol{$homeserver};
11825:     $protocol = 'http' if ($protocol ne 'https');
11826:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11827:     my $response=$ua->request($request,$transferfile);
11828: # did it work?
11829:     if ($response->is_error()) {
11830: 	unlink($transferfile);
11831: 	&logthis("Userfile repcopy failed for $uri");
11832: 	return -1;
11833:     }
11834: # worked, rename the transfer file
11835:     rename($transferfile,$file);
11836:     return 'ok';
11837: }
11838: 
11839: sub tokenwrapper {
11840:     my $uri=shift;
11841:     $uri=~s|^https?\://([^/]+)||;
11842:     $uri=~s|^/||;
11843:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11844:     my $token=$1;
11845:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11846:     if ($udom && $uname && $file) {
11847: 	$file=~s|(\?\.*)*$||;
11848:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11849:         my $homeserver = &homeserver($uname,$udom);
11850:         my $protocol = $protocol{$homeserver};
11851:         $protocol = 'http' if ($protocol ne 'https');
11852:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11853:                (($uri=~/\?/)?'&':'?').'token='.$token.
11854:                                '&tokenissued='.$perlvar{'lonHostID'};
11855:     } else {
11856:         return '/adm/notfound.html';
11857:     }
11858: }
11859: 
11860: # call with reqtype HEAD: get last modification time
11861: # call with reqtype GET: get the file contents
11862: # Do not call this with reqtype GET for large files! It loads everything into memory
11863: #
11864: sub getuploaded {
11865:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11866:     $uri=~s/^\///;
11867:     my $homeserver = &homeserver($cnum,$cdom);
11868:     my $protocol = $protocol{$homeserver};
11869:     $protocol = 'http' if ($protocol ne 'https');
11870:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11871:     my $ua=new LWP::UserAgent;
11872:     my $request=new HTTP::Request($reqtype,$uri);
11873:     my $response=$ua->request($request);
11874:     $$rtncode = $response->code;
11875:     if (! $response->is_success()) {
11876: 	return 'failed';
11877:     }      
11878:     if ($reqtype eq 'HEAD') {
11879: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11880:     } elsif ($reqtype eq 'GET') {
11881: 	$$info = $response->content;
11882:     }
11883:     return 'ok';
11884: }
11885: 
11886: sub readfile {
11887:     my $file = shift;
11888:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11889:     my $fh;
11890:     open($fh,"<$file");
11891:     my $a='';
11892:     while (my $line = <$fh>) { $a .= $line; }
11893:     return $a;
11894: }
11895: 
11896: sub filelocation {
11897:     my ($dir,$file) = @_;
11898:     my $location;
11899:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11900: 
11901:     if ($file =~ m-^/adm/-) {
11902: 	$file=~s-^/adm/wrapper/-/-;
11903: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11904:     }
11905: 
11906:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11907:         $location = $file;
11908:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11909:         my ($udom,$uname,$filename)=
11910:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11911:         my $home=&homeserver($uname,$udom);
11912:         my $is_me=0;
11913:         my @ids=&current_machine_ids();
11914:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11915:         if ($is_me) {
11916:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11917:         } else {
11918:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11919:   	      $udom.'/'.$uname.'/'.$filename;
11920:         }
11921:     } elsif ($file =~ m-^/adm/-) {
11922: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11923:     } else {
11924:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11925:         $file=~s:^/(res|priv)/:/:;
11926:         my $space=$1;
11927:         if ( !( $file =~ m:^/:) ) {
11928:             $location = $dir. '/'.$file;
11929:         } else {
11930:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11931:         }
11932:     }
11933:     $location=~s://+:/:g; # remove duplicate /
11934:     while ($location=~m{/\.\./}) {
11935: 	if ($location =~ m{/[^/]+/\.\./}) {
11936: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11937: 	} else {
11938: 	    $location=~ s{/\.\./}{/}g;
11939: 	}
11940:     } #remove dir/..
11941:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11942:     return $location;
11943: }
11944: 
11945: sub hreflocation {
11946:     my ($dir,$file)=@_;
11947:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11948: 	$file=filelocation($dir,$file);
11949:     } elsif ($file=~m-^/adm/-) {
11950: 	$file=~s-^/adm/wrapper/-/-;
11951: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11952:     }
11953:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11954: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11955:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11956: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11957: 	        {/uploaded/$1/$2/}x;
11958:     }
11959:     if ($file=~ m{^/userfiles/}) {
11960: 	$file =~ s{^/userfiles/}{/uploaded/};
11961:     }
11962:     return $file;
11963: }
11964: 
11965: 
11966: 
11967: 
11968: 
11969: sub current_machine_domains {
11970:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11971: }
11972: 
11973: sub machine_domains {
11974:     my ($hostname) = @_;
11975:     my @domains;
11976:     my %hostname = &all_hostnames();
11977:     while( my($id, $name) = each(%hostname)) {
11978: #	&logthis("-$id-$name-$hostname-");
11979: 	if ($hostname eq $name) {
11980: 	    push(@domains,&host_domain($id));
11981: 	}
11982:     }
11983:     return @domains;
11984: }
11985: 
11986: sub current_machine_ids {
11987:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11988: }
11989: 
11990: sub machine_ids {
11991:     my ($hostname) = @_;
11992:     $hostname ||= &hostname($perlvar{'lonHostID'});
11993:     my @ids;
11994:     my %name_to_host = &all_names();
11995:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11996: 	return @{ $name_to_host{$hostname} };
11997:     }
11998:     return;
11999: }
12000: 
12001: sub additional_machine_domains {
12002:     my @domains;
12003:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12004:     while( my $line = <$fh>) {
12005:         $line =~ s/\s//g;
12006:         push(@domains,$line);
12007:     }
12008:     return @domains;
12009: }
12010: 
12011: sub default_login_domain {
12012:     my $domain = $perlvar{'lonDefDomain'};
12013:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12014:     foreach my $posdom (&current_machine_domains(),
12015:                         &additional_machine_domains()) {
12016:         if (lc($posdom) eq lc($testdomain)) {
12017:             $domain=$posdom;
12018:             last;
12019:         }
12020:     }
12021:     return $domain;
12022: }
12023: 
12024: # ------------------------------------------------------------- Declutters URLs
12025: 
12026: sub declutter {
12027:     my $thisfn=shift;
12028:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12029:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12030:         $thisfn=~s{^/home/httpd/html}{};
12031:     }
12032:     $thisfn=~s/^\///;
12033:     $thisfn=~s|^adm/wrapper/||;
12034:     $thisfn=~s|^adm/coursedocs/showdoc/||;
12035:     $thisfn=~s/^res\///;
12036:     $thisfn=~s/^priv\///;
12037:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12038:         $thisfn=~s/\?.+$//;
12039:     }
12040:     return $thisfn;
12041: }
12042: 
12043: # ------------------------------------------------------------- Clutter up URLs
12044: 
12045: sub clutter {
12046:     my $thisfn='/'.&declutter(shift);
12047:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
12048: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
12049:        $thisfn='/res'.$thisfn; 
12050:     }
12051:     if ($thisfn !~m|^/adm|) {
12052: 	if ($thisfn =~ m|^/ext/|) {
12053: 	    $thisfn='/adm/wrapper'.$thisfn;
12054: 	} else {
12055: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
12056: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
12057: 	    if ($embstyle eq 'ssi'
12058: 		|| ($embstyle eq 'hdn')
12059: 		|| ($embstyle eq 'rat')
12060: 		|| ($embstyle eq 'prv')
12061: 		|| ($embstyle eq 'ign')) {
12062: 		#do nothing with these
12063: 	    } elsif (($embstyle eq 'img') 
12064: 		|| ($embstyle eq 'emb')
12065: 		|| ($embstyle eq 'wrp')) {
12066: 		$thisfn='/adm/wrapper'.$thisfn;
12067: 	    } elsif ($embstyle eq 'unk'
12068: 		     && $thisfn!~/\.(sequence|page)$/) {
12069: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
12070: 	    } else {
12071: #		&logthis("Got a blank emb style");
12072: 	    }
12073: 	}
12074:     }
12075:     return $thisfn;
12076: }
12077: 
12078: sub clutter_with_no_wrapper {
12079:     my $uri = &clutter(shift);
12080:     if ($uri =~ m-^/adm/-) {
12081: 	$uri =~ s-^/adm/wrapper/-/-;
12082: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
12083:     }
12084:     return $uri;
12085: }
12086: 
12087: sub freeze_escape {
12088:     my ($value)=@_;
12089:     if (ref($value)) {
12090: 	$value=&nfreeze($value);
12091: 	return '__FROZEN__'.&escape($value);
12092:     }
12093:     return &escape($value);
12094: }
12095: 
12096: 
12097: sub thaw_unescape {
12098:     my ($value)=@_;
12099:     if ($value =~ /^__FROZEN__/) {
12100: 	substr($value,0,10,undef);
12101: 	$value=&unescape($value);
12102: 	return &thaw($value);
12103:     }
12104:     return &unescape($value);
12105: }
12106: 
12107: sub correct_line_ends {
12108:     my ($result)=@_;
12109:     $$result =~s/\r\n/\n/mg;
12110:     $$result =~s/\r/\n/mg;
12111: }
12112: # ================================================================ Main Program
12113: 
12114: sub goodbye {
12115:    &logthis("Starting Shut down");
12116: #not converted to using infrastruture and probably shouldn't be
12117:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
12118: #converted
12119: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
12120:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12121: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12122: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
12123: #1.1 only
12124: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12125: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12126: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12127: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12128:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12129:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12130:    &logthis(sprintf("%-20s is %s",'hits',$hits));
12131:    &flushcourselogs();
12132:    &logthis("Shutting down");
12133: }
12134: 
12135: sub get_dns {
12136:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12137:     if (!$ignore_cache) {
12138: 	my ($content,$cached)=
12139: 	    &Apache::lonnet::is_cached_new('dns',$url);
12140: 	if ($cached) {
12141: 	    &$func($content,$hashref);
12142: 	    return;
12143: 	}
12144:     }
12145: 
12146:     my %alldns;
12147:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12148:     foreach my $dns (<$config>) {
12149: 	next if ($dns !~ /^\^(\S*)/x);
12150:         my $line = $1;
12151:         my ($host,$protocol) = split(/:/,$line);
12152:         if ($protocol ne 'https') {
12153:             $protocol = 'http';
12154:         }
12155: 	$alldns{$host} = $protocol;
12156:     }
12157:     while (%alldns) {
12158: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12159: 	my $ua=new LWP::UserAgent;
12160:         $ua->timeout(30);
12161: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12162: 	my $response=$ua->request($request);
12163:         delete($alldns{$dns});
12164: 	next if ($response->is_error());
12165: 	my @content = split("\n",$response->content);
12166: 	unless ($nocache) {
12167: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12168: 	}
12169: 	&$func(\@content,$hashref);
12170: 	return;
12171:     }
12172:     close($config);
12173:     my $which = (split('/',$url))[3];
12174:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12175:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12176:     my @content = <$config>;
12177:     &$func(\@content,$hashref);
12178:     return;
12179: }
12180: 
12181: # ------------------------------------------------------Get DNS checksums file
12182: sub parse_dns_checksums_tab {
12183:     my ($lines,$hashref) = @_;
12184:     my $lonhost = $perlvar{'lonHostID'};
12185:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12186:     my $loncaparev = &get_server_loncaparev($machine_dom);
12187:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12188:     my $webconfdir = '/etc/httpd/conf';
12189:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12190:         $webconfdir = '/etc/apache2';
12191:     } elsif ($distro =~ /^sles(\d+)$/) {
12192:         if ($1 >= 10) {
12193:             $webconfdir = '/etc/apache2';
12194:         }
12195:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12196:         if ($1 >= 10.0) {
12197:             $webconfdir = '/etc/apache2';
12198:         }
12199:     }
12200:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12201:     my (%chksum,%revnum);
12202:     if (ref($lines) eq 'ARRAY') {
12203:         chomp(@{$lines});
12204:         my $version = shift(@{$lines});
12205:         if ($version eq $release) {  
12206:             foreach my $line (@{$lines}) {
12207:                 my ($file,$version,$shasum) = split(/,/,$line);
12208:                 if ($file =~ m{^/etc/httpd/conf}) {
12209:                     if ($webconfdir eq '/etc/apache2') {
12210:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12211:                     }
12212:                 }
12213:                 $chksum{$file} = $shasum;
12214:                 $revnum{$file} = $version;
12215:             }
12216:             if (ref($hashref) eq 'HASH') {
12217:                 %{$hashref} = (
12218:                                 sums     => \%chksum,
12219:                                 versions => \%revnum,
12220:                               );
12221:             }
12222:         }
12223:     }
12224:     return;
12225: }
12226: 
12227: sub fetch_dns_checksums {
12228:     my %checksums;
12229:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12230:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12231:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12232:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12233:              \%checksums);
12234:     return \%checksums;
12235: }
12236: 
12237: # ------------------------------------------------------------ Read domain file
12238: {
12239:     my $loaded;
12240:     my %domain;
12241: 
12242:     sub parse_domain_tab {
12243: 	my ($lines) = @_;
12244: 	foreach my $line (@$lines) {
12245: 	    next if ($line =~ /^(\#|\s*$ )/x);
12246: 
12247: 	    chomp($line);
12248: 	    my ($name,@elements) = split(/:/,$line,9);
12249: 	    my %this_domain;
12250: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12251: 			       'lang_def', 'city', 'longi', 'lati',
12252: 			       'primary') {
12253: 		$this_domain{$field} = shift(@elements);
12254: 	    }
12255: 	    $domain{$name} = \%this_domain;
12256: 	}
12257:     }
12258: 
12259:     sub reset_domain_info {
12260: 	undef($loaded);
12261: 	undef(%domain);
12262:     }
12263: 
12264:     sub load_domain_tab {
12265: 	my ($ignore_cache) = @_;
12266: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
12267: 	my $fh;
12268: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12269: 	    my @lines = <$fh>;
12270: 	    &parse_domain_tab(\@lines);
12271: 	}
12272: 	close($fh);
12273: 	$loaded = 1;
12274:     }
12275: 
12276:     sub domain {
12277: 	&load_domain_tab() if (!$loaded);
12278: 
12279: 	my ($name,$what) = @_;
12280: 	return if ( !exists($domain{$name}) );
12281: 
12282: 	if (!$what) {
12283: 	    return $domain{$name}{'description'};
12284: 	}
12285: 	return $domain{$name}{$what};
12286:     }
12287: 
12288:     sub domain_info {
12289:         &load_domain_tab() if (!$loaded);
12290:         return %domain;
12291:     }
12292: 
12293: }
12294: 
12295: 
12296: # ------------------------------------------------------------- Read hosts file
12297: {
12298:     my %hostname;
12299:     my %hostdom;
12300:     my %libserv;
12301:     my $loaded;
12302:     my %name_to_host;
12303:     my %internetdom;
12304:     my %LC_dns_serv;
12305: 
12306:     sub parse_hosts_tab {
12307: 	my ($file) = @_;
12308: 	foreach my $configline (@$file) {
12309: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12310:             chomp($configline);
12311: 	    if ($configline =~ /^\^/) {
12312:                 if ($configline =~ /^\^([\w.\-]+)/) {
12313:                     $LC_dns_serv{$1} = 1;
12314:                 }
12315:                 next;
12316:             }
12317: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12318: 	    $name=~s/\s//g;
12319: 	    if ($id && $domain && $role && $name) {
12320: 		$hostname{$id}=$name;
12321: 		push(@{$name_to_host{$name}}, $id);
12322: 		$hostdom{$id}=$domain;
12323: 		if ($role eq 'library') { $libserv{$id}=$name; }
12324:                 if (defined($protocol)) {
12325:                     if ($protocol eq 'https') {
12326:                         $protocol{$id} = $protocol;
12327:                     } else {
12328:                         $protocol{$id} = 'http'; 
12329:                     }
12330:                 } else {
12331:                     $protocol{$id} = 'http';
12332:                 }
12333:                 if (defined($intdom)) {
12334:                     $internetdom{$id} = $intdom;
12335:                 }
12336: 	    }
12337: 	}
12338:     }
12339:     
12340:     sub reset_hosts_info {
12341: 	&purge_remembered();
12342: 	&reset_domain_info();
12343: 	&reset_hosts_ip_info();
12344: 	undef(%name_to_host);
12345: 	undef(%hostname);
12346: 	undef(%hostdom);
12347: 	undef(%libserv);
12348: 	undef($loaded);
12349:     }
12350: 
12351:     sub load_hosts_tab {
12352: 	my ($ignore_cache) = @_;
12353: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12354: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12355: 	my @config = <$config>;
12356: 	&parse_hosts_tab(\@config);
12357: 	close($config);
12358: 	$loaded=1;
12359:     }
12360: 
12361:     sub hostname {
12362: 	&load_hosts_tab() if (!$loaded);
12363: 
12364: 	my ($lonid) = @_;
12365: 	return $hostname{$lonid};
12366:     }
12367: 
12368:     sub all_hostnames {
12369: 	&load_hosts_tab() if (!$loaded);
12370: 
12371: 	return %hostname;
12372:     }
12373: 
12374:     sub all_names {
12375: 	&load_hosts_tab() if (!$loaded);
12376: 
12377: 	return %name_to_host;
12378:     }
12379: 
12380:     sub all_host_domain {
12381:         &load_hosts_tab() if (!$loaded);
12382:         return %hostdom;
12383:     }
12384: 
12385:     sub is_library {
12386: 	&load_hosts_tab() if (!$loaded);
12387: 
12388: 	return exists($libserv{$_[0]});
12389:     }
12390: 
12391:     sub all_library {
12392: 	&load_hosts_tab() if (!$loaded);
12393: 
12394: 	return %libserv;
12395:     }
12396: 
12397:     sub unique_library {
12398: 	#2x reverse removes all hostnames that appear more than once
12399:         my %unique = reverse &all_library();
12400:         return reverse %unique;
12401:     }
12402: 
12403:     sub get_servers {
12404: 	&load_hosts_tab() if (!$loaded);
12405: 
12406: 	my ($domain,$type) = @_;
12407: 	my %possible_hosts = ($type eq 'library') ? %libserv
12408: 	                                          : %hostname;
12409: 	my %result;
12410: 	if (ref($domain) eq 'ARRAY') {
12411: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12412: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12413: 		    $result{$host} = $hostname;
12414: 		}
12415: 	    }
12416: 	} else {
12417: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12418: 		if ($hostdom{$host} eq $domain) {
12419: 		    $result{$host} = $hostname;
12420: 		}
12421: 	    }
12422: 	}
12423: 	return %result;
12424:     }
12425: 
12426:     sub get_unique_servers {
12427:         my %unique = reverse &get_servers(@_);
12428: 	return reverse %unique;
12429:     }
12430: 
12431:     sub host_domain {
12432: 	&load_hosts_tab() if (!$loaded);
12433: 
12434: 	my ($lonid) = @_;
12435: 	return $hostdom{$lonid};
12436:     }
12437: 
12438:     sub all_domains {
12439: 	&load_hosts_tab() if (!$loaded);
12440: 
12441: 	my %seen;
12442: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12443: 	return @uniq;
12444:     }
12445: 
12446:     sub internet_dom {
12447:         &load_hosts_tab() if (!$loaded);
12448: 
12449:         my ($lonid) = @_;
12450:         return $internetdom{$lonid};
12451:     }
12452: 
12453:     sub is_LC_dns {
12454:         &load_hosts_tab() if (!$loaded);
12455: 
12456:         my ($hostname) = @_;
12457:         return exists($LC_dns_serv{$hostname});
12458:     }
12459: 
12460: }
12461: 
12462: { 
12463:     my %iphost;
12464:     my %name_to_ip;
12465:     my %lonid_to_ip;
12466: 
12467:     sub get_hosts_from_ip {
12468: 	my ($ip) = @_;
12469: 	my %iphosts = &get_iphost();
12470: 	if (ref($iphosts{$ip})) {
12471: 	    return @{$iphosts{$ip}};
12472: 	}
12473: 	return;
12474:     }
12475:     
12476:     sub reset_hosts_ip_info {
12477: 	undef(%iphost);
12478: 	undef(%name_to_ip);
12479: 	undef(%lonid_to_ip);
12480:     }
12481: 
12482:     sub get_host_ip {
12483: 	my ($lonid) = @_;
12484: 	if (exists($lonid_to_ip{$lonid})) {
12485: 	    return $lonid_to_ip{$lonid};
12486: 	}
12487: 	my $name=&hostname($lonid);
12488:    	my $ip = gethostbyname($name);
12489: 	return if (!$ip || length($ip) ne 4);
12490: 	$ip=inet_ntoa($ip);
12491: 	$name_to_ip{$name}   = $ip;
12492: 	$lonid_to_ip{$lonid} = $ip;
12493: 	return $ip;
12494:     }
12495:     
12496:     sub get_iphost {
12497: 	my ($ignore_cache) = @_;
12498: 
12499: 	if (!$ignore_cache) {
12500: 	    if (%iphost) {
12501: 		return %iphost;
12502: 	    }
12503: 	    my ($ip_info,$cached)=
12504: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12505: 	    if ($cached) {
12506: 		%iphost      = %{$ip_info->[0]};
12507: 		%name_to_ip  = %{$ip_info->[1]};
12508: 		%lonid_to_ip = %{$ip_info->[2]};
12509: 		return %iphost;
12510: 	    }
12511: 	}
12512: 
12513: 	# get yesterday's info for fallback
12514: 	my %old_name_to_ip;
12515: 	my ($ip_info,$cached)=
12516: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12517: 	if ($cached) {
12518: 	    %old_name_to_ip = %{$ip_info->[1]};
12519: 	}
12520: 
12521: 	my %name_to_host = &all_names();
12522: 	foreach my $name (keys(%name_to_host)) {
12523: 	    my $ip;
12524: 	    if (!exists($name_to_ip{$name})) {
12525: 		$ip = gethostbyname($name);
12526: 		if (!$ip || length($ip) ne 4) {
12527: 		    if (defined($old_name_to_ip{$name})) {
12528: 			$ip = $old_name_to_ip{$name};
12529: 			&logthis("Can't find $name defaulting to old $ip");
12530: 		    } else {
12531: 			&logthis("Name $name no IP found");
12532: 			next;
12533: 		    }
12534: 		} else {
12535: 		    $ip=inet_ntoa($ip);
12536: 		}
12537: 		$name_to_ip{$name} = $ip;
12538: 	    } else {
12539: 		$ip = $name_to_ip{$name};
12540: 	    }
12541: 	    foreach my $id (@{ $name_to_host{$name} }) {
12542: 		$lonid_to_ip{$id} = $ip;
12543: 	    }
12544: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12545: 	}
12546: 	&do_cache_new('iphost','iphost',
12547: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12548: 		      48*60*60);
12549: 
12550: 	return %iphost;
12551:     }
12552: 
12553:     #
12554:     #  Given a DNS returns the loncapa host name for that DNS 
12555:     # 
12556:     sub host_from_dns {
12557:         my ($dns) = @_;
12558:         my @hosts;
12559:         my $ip;
12560: 
12561:         if (exists($name_to_ip{$dns})) {
12562:             $ip = $name_to_ip{$dns};
12563:         }
12564:         if (!$ip) {
12565:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12566:             if (length($ip) == 4) { 
12567: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12568:             }
12569:         }
12570:         if ($ip) {
12571: 	    @hosts = get_hosts_from_ip($ip);
12572: 	    return $hosts[0];
12573:         }
12574:         return undef;
12575:     }
12576: 
12577:     sub get_internet_names {
12578:         my ($lonid) = @_;
12579:         return if ($lonid eq '');
12580:         my ($idnref,$cached)=
12581:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12582:         if ($cached) {
12583:             return $idnref;
12584:         }
12585:         my $ip = &get_host_ip($lonid);
12586:         my @hosts = &get_hosts_from_ip($ip);
12587:         my %iphost = &get_iphost();
12588:         my (@idns,%seen);
12589:         foreach my $id (@hosts) {
12590:             my $dom = &host_domain($id);
12591:             my $prim_id = &domain($dom,'primary');
12592:             my $prim_ip = &get_host_ip($prim_id);
12593:             next if ($seen{$prim_ip});
12594:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12595:                 foreach my $id (@{$iphost{$prim_ip}}) {
12596:                     my $intdom = &internet_dom($id);
12597:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12598:                         push(@idns,$intdom);
12599:                     }
12600:                 }
12601:             }
12602:             $seen{$prim_ip} = 1;
12603:         }
12604:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12605:     }
12606: 
12607: }
12608: 
12609: sub all_loncaparevs {
12610:     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);
12611: }
12612: 
12613: # ---------------------------------------------------------- Read loncaparev table
12614: {
12615:     sub load_loncaparevs { 
12616:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12617:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12618:                 while (my $configline=<$config>) {
12619:                     chomp($configline);
12620:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12621:                     $loncaparevs{$hostid}=$loncaparev;
12622:                 }
12623:                 close($config);
12624:             }
12625:         }
12626:     }
12627: }
12628: 
12629: # ---------------------------------------------------------- Read serverhostID table
12630: {
12631:     sub load_serverhomeIDs {
12632:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12633:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12634:                 while (my $configline=<$config>) {
12635:                     chomp($configline);
12636:                     my ($name,$id)=split(/:/,$configline);
12637:                     $serverhomeIDs{$name}=$id;
12638:                 }
12639:                 close($config);
12640:             }
12641:         }
12642:     }
12643: }
12644: 
12645: 
12646: BEGIN {
12647: 
12648: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12649:     unless ($readit) {
12650: {
12651:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12652:     %perlvar = (%perlvar,%{$configvars});
12653: }
12654: 
12655: 
12656: # ------------------------------------------------------ Read spare server file
12657: {
12658:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12659: 
12660:     while (my $configline=<$config>) {
12661:        chomp($configline);
12662:        if ($configline) {
12663: 	   my ($host,$type) = split(':',$configline,2);
12664: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12665: 	   push(@{ $spareid{$type} }, $host);
12666:        }
12667:     }
12668:     close($config);
12669: }
12670: # ------------------------------------------------------------ Read permissions
12671: {
12672:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12673: 
12674:     while (my $configline=<$config>) {
12675: 	chomp($configline);
12676: 	if ($configline) {
12677: 	    my ($role,$perm)=split(/ /,$configline);
12678: 	    if ($perm ne '') { $pr{$role}=$perm; }
12679: 	}
12680:     }
12681:     close($config);
12682: }
12683: 
12684: # -------------------------------------------- Read plain texts for permissions
12685: {
12686:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12687: 
12688:     while (my $configline=<$config>) {
12689: 	chomp($configline);
12690: 	if ($configline) {
12691: 	    my ($short,@plain)=split(/:/,$configline);
12692:             %{$prp{$short}} = ();
12693: 	    if (@plain > 0) {
12694:                 $prp{$short}{'std'} = $plain[0];
12695:                 for (my $i=1; $i<@plain; $i++) {
12696:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12697:                 }
12698:             }
12699: 	}
12700:     }
12701:     close($config);
12702: }
12703: 
12704: # ---------------------------------------------------------- Read package table
12705: {
12706:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12707: 
12708:     while (my $configline=<$config>) {
12709: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12710: 	chomp($configline);
12711: 	my ($short,$plain)=split(/:/,$configline);
12712: 	my ($pack,$name)=split(/\&/,$short);
12713: 	if ($plain ne '') {
12714: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12715: 	    $packagetab{$short}=$plain; 
12716: 	}
12717:     }
12718:     close($config);
12719: }
12720: 
12721: # ---------------------------------------------------------- Read loncaparev table
12722: 
12723: &load_loncaparevs();
12724: 
12725: # ---------------------------------------------------------- Read serverhostID table
12726: 
12727: &load_serverhomeIDs();
12728: 
12729: # ---------------------------------------------------------- Read releaseslist XML
12730: {
12731:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12732:     if (-e $file) {
12733:         my $parser = HTML::LCParser->new($file);
12734:         while (my $token = $parser->get_token()) {
12735:             if ($token->[0] eq 'S') {
12736:                 my $item = $token->[1];
12737:                 my $name = $token->[2]{'name'};
12738:                 my $value = $token->[2]{'value'};
12739:                 my $valuematch = $token->[2]{'valuematch'};
12740:                 if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
12741:                     my $release = $parser->get_text();
12742:                     $release =~ s/(^\s*|\s*$ )//gx;
12743:                     $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
12744:                 }
12745:             }
12746:         }
12747:     }
12748: }
12749: 
12750: # ---------------------------------------------------------- Read managers table
12751: {
12752:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12753:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12754:             while (my $configline=<$config>) {
12755:                 chomp($configline);
12756:                 next if ($configline =~ /^\#/);
12757:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12758:                     $managerstab{$configline} = 1;
12759:                 }
12760:             }
12761:             close($config);
12762:         }
12763:     }
12764: }
12765: 
12766: # ------------- set up temporary directory
12767: {
12768:     $tmpdir = LONCAPA::tempdir();
12769: 
12770: }
12771: 
12772: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12773: 				'compress_threshold'=> 20_000,
12774:  			        });
12775: 
12776: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12777: $dumpcount=0;
12778: $locknum=0;
12779: 
12780: &logtouch();
12781: &logthis('<font color="yellow">INFO: Read configuration</font>');
12782: $readit=1;
12783:     {
12784: 	use integer;
12785: 	my $test=(2**32)+1;
12786: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12787: 	&logthis(" Detected 64bit platform ($_64bit)");
12788:     }
12789: }
12790: }
12791: 
12792: 1;
12793: __END__
12794: 
12795: =pod
12796: 
12797: =head1 NAME
12798: 
12799: Apache::lonnet - Subroutines to ask questions about things in the network.
12800: 
12801: =head1 SYNOPSIS
12802: 
12803: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12804: 
12805:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12806: 
12807: Common parameters:
12808: 
12809: =over 4
12810: 
12811: =item *
12812: 
12813: $uname : an internal username (if $cname expecting a course Id specifically)
12814: 
12815: =item *
12816: 
12817: $udom : a domain (if $cdom expecting a course's domain specifically)
12818: 
12819: =item *
12820: 
12821: $symb : a resource instance identifier
12822: 
12823: =item *
12824: 
12825: $namespace : the name of a .db file that contains the data needed or
12826: being set.
12827: 
12828: =back
12829: 
12830: =head1 OVERVIEW
12831: 
12832: lonnet provides subroutines which interact with the
12833: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12834: about classes, users, and resources.
12835: 
12836: For many of these objects you can also use this to store data about
12837: them or modify them in various ways.
12838: 
12839: =head2 Symbs
12840: 
12841: To identify a specific instance of a resource, LON-CAPA uses symbols
12842: or "symbs"X<symb>. These identifiers are built from the URL of the
12843: map, the resource number of the resource in the map, and the URL of
12844: the resource itself. The latter is somewhat redundant, but might help
12845: if maps change.
12846: 
12847: An example is
12848: 
12849:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12850: 
12851: The respective map entry is
12852: 
12853:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12854:   title="Problem 2">
12855:  </resource>
12856: 
12857: Symbs are used by the random number generator, as well as to store and
12858: restore data specific to a certain instance of for example a problem.
12859: 
12860: =head2 Storing And Retrieving Data
12861: 
12862: X<store()>X<cstore()>X<restore()>Three of the most important functions
12863: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12864: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12865: is is the non-critical message twin of cstore. These functions are for
12866: handlers to store a perl hash to a user's permanent data space in an
12867: easy manner, and to retrieve it again on another call. It is expected
12868: that a handler would use this once at the beginning to retrieve data,
12869: and then again once at the end to send only the new data back.
12870: 
12871: The data is stored in the user's data directory on the user's
12872: homeserver under the ID of the course.
12873: 
12874: The hash that is returned by restore will have all of the previous
12875: value for all of the elements of the hash.
12876: 
12877: Example:
12878: 
12879:  #creating a hash
12880:  my %hash;
12881:  $hash{'foo'}='bar';
12882: 
12883:  #storing it
12884:  &Apache::lonnet::cstore(\%hash);
12885: 
12886:  #changing a value
12887:  $hash{'foo'}='notbar';
12888: 
12889:  #adding a new value
12890:  $hash{'bar'}='foo';
12891:  &Apache::lonnet::cstore(\%hash);
12892: 
12893:  #retrieving the hash
12894:  my %history=&Apache::lonnet::restore();
12895: 
12896:  #print the hash
12897:  foreach my $key (sort(keys(%history))) {
12898:    print("\%history{$key} = $history{$key}");
12899:  }
12900: 
12901: Will print out:
12902: 
12903:  %history{1:foo} = bar
12904:  %history{1:keys} = foo:timestamp
12905:  %history{1:timestamp} = 990455579
12906:  %history{2:bar} = foo
12907:  %history{2:foo} = notbar
12908:  %history{2:keys} = foo:bar:timestamp
12909:  %history{2:timestamp} = 990455580
12910:  %history{bar} = foo
12911:  %history{foo} = notbar
12912:  %history{timestamp} = 990455580
12913:  %history{version} = 2
12914: 
12915: Note that the special hash entries C<keys>, C<version> and
12916: C<timestamp> were added to the hash. C<version> will be equal to the
12917: total number of versions of the data that have been stored. The
12918: C<timestamp> attribute will be the UNIX time the hash was
12919: stored. C<keys> is available in every historical section to list which
12920: keys were added or changed at a specific historical revision of a
12921: hash.
12922: 
12923: B<Warning>: do not store the hash that restore returns directly. This
12924: will cause a mess since it will restore the historical keys as if the
12925: were new keys. I.E. 1:foo will become 1:1:foo etc.
12926: 
12927: Calling convention:
12928: 
12929:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12930:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
12931: 
12932: For more detailed information, see lonnet specific documentation.
12933: 
12934: =head1 RETURN MESSAGES
12935: 
12936: =over 4
12937: 
12938: =item * B<con_lost>: unable to contact remote host
12939: 
12940: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12941: when the connection is brought back up
12942: 
12943: =item * B<con_failed>: unable to contact remote host and unable to save message
12944: for later delivery
12945: 
12946: =item * B<error:>: an error a occurred, a description of the error follows the :
12947: 
12948: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12949: that was requested
12950: 
12951: =back
12952: 
12953: =head1 PUBLIC SUBROUTINES
12954: 
12955: =head2 Session Environment Functions
12956: 
12957: =over 4
12958: 
12959: =item * 
12960: X<appenv()>
12961: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12962: the user envirnoment file, and will be restored for each access this
12963: user makes during this session, also modifies the %env for the current
12964: process. Optional rolesarrayref - if defined contains a reference to an array
12965: of roles which are exempt from the restriction on modifying user.role entries 
12966: in the user's environment.db and in %env.    
12967: 
12968: =item *
12969: X<delenv()>
12970: B<delenv($delthis,$regexp)>: removes all items from the session
12971: environment file that begin with $delthis. If the 
12972: optional second arg - $regexp - is true, $delthis is treated as a 
12973: regular expression, otherwise \Q$delthis\E is used. 
12974: The values are also deleted from the current processes %env.
12975: 
12976: =item * get_env_multiple($name) 
12977: 
12978: gets $name from the %env hash, it seemlessly handles the cases where multiple
12979: values may be defined and end up as an array ref.
12980: 
12981: returns an array of values
12982: 
12983: =back
12984: 
12985: =head2 User Information
12986: 
12987: =over 4
12988: 
12989: =item *
12990: X<queryauthenticate()>
12991: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12992: authentication scheme
12993: 
12994: =item *
12995: X<authenticate()>
12996: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12997: authenticate user from domain's lib servers (first use the current
12998: one). C<$upass> should be the users password.
12999: $checkdefauth is optional (value is 1 if a check should be made to
13000:    authenticate user using default authentication method, and allow
13001:    account creation if username does not have account in the domain).
13002: $clientcancheckhost is optional (value is 1 if checking whether the
13003:    server can host will occur on the client side in lonauth.pm).   
13004: 
13005: =item *
13006: X<homeserver()>
13007: B<homeserver($uname,$udom)>: find the server which has
13008: the user's directory and files (there must be only one), this caches
13009: the answer, and also caches if there is a borken connection.
13010: 
13011: =item *
13012: X<idget()>
13013: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13014: (IDs are a unique resource in a domain, there must be only 1 ID per
13015: username, and only 1 username per ID in a specific domain) (returns
13016: hash: id=>name,id=>name)
13017: 
13018: =item *
13019: X<idrget()>
13020: B<idrget($udom,@unames)>: find the IDs behind a list of
13021: usernames (returns hash: name=>id,name=>id)
13022: 
13023: =item *
13024: X<idput()>
13025: B<idput($udom,%ids)>: store away a list of names and associated IDs
13026: 
13027: =item *
13028: X<rolesinit()>
13029: B<rolesinit($udom,$username)>: get user privileges.
13030: returns user role, first access and timer interval hashes
13031: 
13032: =item *
13033: X<privileged()>
13034: B<privileged($username,$domain)>: returns a true if user has a
13035: privileged and active role (i.e. su or dc), false otherwise.
13036: 
13037: =item *
13038: X<getsection()>
13039: B<getsection($udom,$uname,$cname)>: finds the section of student in the
13040: course $cname, return section name/number or '' for "not in course"
13041: and '-1' for "no section"
13042: 
13043: =item *
13044: X<userenvironment()>
13045: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
13046: passed in @what from the requested user's environment, returns a hash
13047: 
13048: =item * 
13049: X<userlog_query()>
13050: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13051: activity.log file. %filters defines filters applied when parsing the
13052: log file. These can be start or end timestamps, or the type of action
13053: - log to look for Login or Logout events, check for Checkin or
13054: Checkout, role for role selection. The response is in the form
13055: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
13056: escaped strings of the action recorded in the activity.log file.
13057: 
13058: =back
13059: 
13060: =head2 User Roles
13061: 
13062: =over 4
13063: 
13064: =item *
13065: 
13066: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
13067: returns codes for allowed actions.
13068: 
13069: The first argument is required, all others are optional.
13070: 
13071: $priv is the privilege being checked.
13072: $uri contains additional information about what is being checked for access (e.g.,
13073: URL, course ID etc.). 
13074: $symb is the unique resource instance identifier in a course; if needed,
13075: but not provided, it will be retrieved via a call to &symbread(). 
13076: $role is the role for which a priv is being checked (only used if priv is evb). 
13077: $clientip is the user's IP address (only used when checking for access to portfolio 
13078: files).
13079: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
13080: prevents recursive calls to &allowed.
13081: 
13082:  F: full access
13083:  U,I,K: authentication modes (cxx only)
13084:  '': forbidden
13085:  1: user needs to choose course
13086:  2: browse allowed
13087:  A: passphrase authentication needed
13088:  B: access temporarily blocked because of a blocking event in a course.
13089: 
13090: =item *
13091: 
13092: constructaccess($url,$setpriv) : check for access to construction space URL
13093: 
13094: See if the owner domain and name in the URL match those in the
13095: expected environment.  If so, return three element list
13096: ($ownername,$ownerdomain,$ownerhome).
13097: 
13098: Otherwise return the null string.
13099: 
13100: If second argument 'setpriv' is true, it assigns the privileges,
13101: and returns the same three element list, unless the owner has
13102: blocked "ad hoc" Domain Coordinator access to the Author Space,
13103: in which case the null string is returned.
13104: 
13105: =item *
13106: 
13107: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13108: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13109: and course level
13110: 
13111: =item *
13112: 
13113: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
13114: (rolesplain.tab); plain text explanation of a user role term.
13115: $type is Course (default) or Community.
13116: If $forcedefault evaluates to true, text returned will be default 
13117: text for $type. Otherwise, if this is a course, the text returned 
13118: will be a custom name for the role (if defined in the course's 
13119: environment).  If no custom name is defined the default is returned.
13120:    
13121: =item *
13122: 
13123: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
13124: All arguments are optional. Returns a hash of a roles, either for
13125: co-author/assistant author roles for a user's Construction Space
13126: (default), or if $context is 'userroles', roles for the user himself,
13127: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13128: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13129: For each key, value is set to colon-separated start and end times for
13130: the role.  If no username and domain are specified, will default to
13131: current user/domain. Types, roles, and roledoms are references to arrays
13132: of role statuses (active, future or previous), roles 
13133: (e.g., cc,in, st etc.) and domains of the roles which can be used
13134: to restrict the list of roles reported. If no array ref is 
13135: provided for types, will default to return only active roles.
13136: 
13137: =item *
13138: 
13139: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13140: user: $uname:$udom has a role in the course: $cdom_$cnum. 
13141: 
13142: Additional optional arguments are: $type (if role checking is to be restricted 
13143: to certain user status types -- previous (expired roles), active (currently
13144: available roles) or future (roles available in the future), and
13145: $hideprivileged -- if true will not report course roles for users who
13146: have active Domain Coordinator role in course's domain or in additional
13147: domains (specified in 'Domains to check for privileged users' in course
13148: environment -- set via:  Course Settings -> Classlists and staff listing).
13149: 
13150: =item *
13151: 
13152: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13153: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13154: $possdomains and $possroles are optional array refs -- to domains to check and
13155: roles to check.  If $possdomains is not specified, a dump will be done of the
13156: users' roles.db to check for a dc or su role in any domain. This can be
13157: time consuming if &privileged is called repeatedly (e.g., when displaying a
13158: classlist), so in such cases, supplying a $possdomains array is preferred, as
13159: this then allows &privileged_by_domain() to be used, which caches the identity
13160: of privileged users, eliminating the need for repeated calls to &dump().
13161: 
13162: =item *
13163: 
13164: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13165: where the outer hash keys are domains specified in the $possdomains array ref,
13166: next inner hash keys are privileged roles specified in the $roles array ref,
13167: and the innermost hash contains key = value pairs for username:domain = end:start
13168: for active or future "privileged" users with that role in that domain. To avoid
13169: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13170: innerhash are cached using priv_$role and $dom as the identifiers.
13171: 
13172: =back
13173: 
13174: =head2 User Modification
13175: 
13176: =over 4
13177: 
13178: =item *
13179: 
13180: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13181: user for the level given by URL.  Optional start and end dates (leave empty
13182: string or zero for "no date")
13183: 
13184: =item *
13185: 
13186: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13187: change a users, password, possible return values are: ok,
13188: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13189: refused
13190: 
13191: =item *
13192: 
13193: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13194: 
13195: =item *
13196: 
13197: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13198:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13199: 
13200: will update user information (firstname,middlename,lastname,generation,
13201: permanentemail), and if forceid is true, student/employee ID also.
13202: A user's institutional affiliation(s) can also be updated.
13203: User information fields will not be overwritten with empty entries 
13204: unless the field is included in the $candelete array reference.
13205: This array is included when a single user is modified via "Manage Users",
13206: or when Autoupdate.pl is run by cron in a domain.
13207: 
13208: =item *
13209: 
13210: modifystudent
13211: 
13212: modify a student's enrollment and identification information.
13213: The course id is resolved based on the current user's environment.  
13214: This means the invoking user must be a course coordinator or otherwise
13215: associated with a course.
13216: 
13217: This call is essentially a wrapper for lonnet::modifyuser and
13218: lonnet::modify_student_enrollment
13219: 
13220: Inputs: 
13221: 
13222: =over 4
13223: 
13224: =item B<$udom> Student's loncapa domain
13225: 
13226: =item B<$uname> Student's loncapa login name
13227: 
13228: =item B<$uid> Student/Employee ID
13229: 
13230: =item B<$umode> Student's authentication mode
13231: 
13232: =item B<$upass> Student's password
13233: 
13234: =item B<$first> Student's first name
13235: 
13236: =item B<$middle> Student's middle name
13237: 
13238: =item B<$last> Student's last name
13239: 
13240: =item B<$gene> Student's generation
13241: 
13242: =item B<$usec> Student's section in course
13243: 
13244: =item B<$end> Unix time of the roles expiration
13245: 
13246: =item B<$start> Unix time of the roles start date
13247: 
13248: =item B<$forceid> If defined, allow $uid to be changed
13249: 
13250: =item B<$desiredhome> server to use as home server for student
13251: 
13252: =item B<$email> Student's permanent e-mail address
13253: 
13254: =item B<$type> Type of enrollment (auto or manual)
13255: 
13256: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13257: 
13258: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13259: 
13260: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13261: 
13262: =item B<$context> role change context (shown in User Management Logs display in a course)
13263: 
13264: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13265: 
13266: =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.
13267: 
13268: =back
13269: 
13270: =item *
13271: 
13272: modify_student_enrollment
13273: 
13274: Change a student's enrollment status in a class.  The environment variable
13275: 'role.request.course' must be defined for this function to proceed.
13276: 
13277: Inputs:
13278: 
13279: =over 4
13280: 
13281: =item $udom, student's domain
13282: 
13283: =item $uname, student's name
13284: 
13285: =item $uid, student's user id
13286: 
13287: =item $first, student's first name
13288: 
13289: =item $middle
13290: 
13291: =item $last
13292: 
13293: =item $gene
13294: 
13295: =item $usec
13296: 
13297: =item $end
13298: 
13299: =item $start
13300: 
13301: =item $type
13302: 
13303: =item $locktype
13304: 
13305: =item $cid
13306: 
13307: =item $selfenroll
13308: 
13309: =item $context
13310: 
13311: =item $credits, number of credits student will earn from this class
13312: 
13313: =back
13314: 
13315: 
13316: =item *
13317: 
13318: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13319: custom role; give a custom role to a user for the level given by URL.  Specify
13320: name and domain of role author, and role name
13321: 
13322: =item *
13323: 
13324: revokerole($udom,$uname,$url,$role) : revoke a role for url
13325: 
13326: =item *
13327: 
13328: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13329: 
13330: =back
13331: 
13332: =head2 Course Infomation
13333: 
13334: =over 4
13335: 
13336: =item *
13337: 
13338: coursedescription($courseid,$options) : returns a hash of information about the
13339: specified course id, including all environment settings for the
13340: course, the description of the course will be in the hash under the
13341: key 'description'
13342: 
13343: $options is an optional parameter that if supplied is a hash reference that controls
13344: what how this function works.  It has the following key/values:
13345: 
13346: =over 4
13347: 
13348: =item freshen_cache
13349: 
13350: If defined, and the environment cache for the course is valid, it is 
13351: returned in the returned hash.
13352: 
13353: =item one_time
13354: 
13355: If defined, the last cache time is set to _now_
13356: 
13357: =item user
13358: 
13359: If defined, the supplied username is used instead of the current user.
13360: 
13361: 
13362: =back
13363: 
13364: =item *
13365: 
13366: resdata($name,$domain,$type,@which) : request for current parameter
13367: setting for a specific $type, where $type is either 'course' or 'user',
13368: @what should be a list of parameters to ask about. This routine caches
13369: answers for 10 minutes.
13370: 
13371: =item *
13372: 
13373: get_courseresdata($courseid, $domain) : dump the entire course resource
13374: data base, returning a hash that is keyed by the resource name and has
13375: values that are the resource value.  I believe that the timestamps and
13376: versions are also returned.
13377: 
13378: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13379: supplemental content area. This routine caches the number of files for 
13380: 10 minutes.
13381: 
13382: =back
13383: 
13384: =head2 Course Modification
13385: 
13386: =over 4
13387: 
13388: =item *
13389: 
13390: writecoursepref($courseid,%prefs) : write preferences (environment
13391: database) for a course
13392: 
13393: =item *
13394: 
13395: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13396: 
13397: =item *
13398: 
13399: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13400: 
13401: =item *
13402: 
13403: is_course($courseid), is_course($cdom, $cnum)
13404: 
13405: Accepts either a combined $courseid (in the form of domain_courseid) or the
13406: two component version $cdom, $cnum. It checks if the specified course exists.
13407: 
13408: Returns:
13409:     undef if the course doesn't exist, otherwise
13410:     in scalar context the combined courseid.
13411:     in list context the two components of the course identifier, domain and 
13412:     courseid.    
13413: 
13414: =back
13415: 
13416: =head2 Resource Subroutines
13417: 
13418: =over 4
13419: 
13420: =item *
13421: 
13422: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13423: 
13424: =item *
13425: 
13426: repcopy($filename) : subscribes to the requested file, and attempts to
13427: replicate from the owning library server, Might return
13428: 'unavailable', 'not_found', 'forbidden', 'ok', or
13429: 'bad_request', also attempts to grab the metadata for the
13430: resource. Expects the local filesystem pathname
13431: (/home/httpd/html/res/....)
13432: 
13433: =back
13434: 
13435: =head2 Resource Information
13436: 
13437: =over 4
13438: 
13439: =item *
13440: 
13441: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13442: and returns the value of a variety of different possible values,
13443: $varname should be a request string, and the other parameters can be
13444: used to specify who and what one is asking about. Ordinarily, $cid 
13445: does not need to be specified, as it is retrived from 
13446: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13447: within lonuserstate::loadmap() when initializing a course, before
13448: $env{'request.course.id'} has been set, so it needs to be provided
13449: in that one case.
13450: 
13451: Possible values for $varname are environment.lastname (or other item
13452: from the envirnment hash), user.name (or someother aspect about the
13453: user), resource.0.maxtries (or some other part and parameter of a
13454: resource)
13455: 
13456: =item *
13457: 
13458: directcondval($number) : get current value of a condition; reads from a state
13459: string
13460: 
13461: =item *
13462: 
13463: condval($condidx) : value of condition index based on state
13464: 
13465: =item *
13466: 
13467: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13468: resource's metadata, $what should be either a specific key, or either
13469: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13470: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13471: 
13472: this function automatically caches all requests
13473: 
13474: =item *
13475: 
13476: metadata_query($query,$custom,$customshow) : make a metadata query against the
13477: network of library servers; returns file handle of where SQL and regex results
13478: will be stored for query
13479: 
13480: =item *
13481: 
13482: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
13483: return symbolic list entry (all arguments optional). 
13484: 
13485: Args: filename is the filename (including path) for the file for which a symb 
13486: is required; donotrecurse, if true will prevent calls to allowed() being made 
13487: to check access status if more than one resource was found in the bighash 
13488: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
13489: a randompick); ignorecachednull, if true will prevent a symb of '' being 
13490: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13491: cause possible symbs to be checked to determine if they are subject to content
13492: blocking, if so they will not be included as possible symbs; possibles is a
13493: ref to a hash, which, as a side effect, will be populated with all possible 
13494: symbs (content blocking not tested).
13495:  
13496: returns the data handle
13497: 
13498: =item *
13499: 
13500: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13501: and is a possible symb for the URL in $thisfn, and if is an encrypted
13502: resource that the user accessed using /enc/ returns a 1 on success, 0
13503: on failure, user must be in a course, as it assumes the existence of
13504: the course initial hash, and uses $env('request.course.id'}.  The third
13505: arg is an optional reference to a scalar.  If this arg is passed in the 
13506: call to symbverify, it will be set to 1 if the symb has been set to be 
13507: encrypted; otherwise it will be null.  
13508: 
13509: =item *
13510: 
13511: symbclean($symb) : removes versions numbers from a symb, returns the
13512: cleaned symb
13513: 
13514: =item *
13515: 
13516: is_on_map($uri) : checks if the $uri is somewhere on the current
13517: course map, user must be in a course for it to work.
13518: 
13519: =item *
13520: 
13521: numval($salt) : return random seed value (addend for rndseed)
13522: 
13523: =item *
13524: 
13525: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13526: a random seed, all arguments are optional, if they aren't sent it uses the
13527: environment to derive them. Note: if symb isn't sent and it can't get one
13528: from &symbread it will use the current time as its return value
13529: 
13530: =item *
13531: 
13532: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13533: unfakeable, receipt
13534: 
13535: =item *
13536: 
13537: receipt() : API to ireceipt working off of env values; given out to users
13538: 
13539: =item *
13540: 
13541: countacc($url) : count the number of accesses to a given URL
13542: 
13543: =item *
13544: 
13545: 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
13546: 
13547: =item *
13548: 
13549: 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)
13550: 
13551: =item *
13552: 
13553: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13554: 
13555: =item *
13556: 
13557: devalidate($symb) : devalidate temporary spreadsheet calculations,
13558: forcing spreadsheet to reevaluate the resource scores next time.
13559: 
13560: =item * 
13561: 
13562: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13563: when viewing in course context.
13564: 
13565:  input: six args -- filename (decluttered), course number, course domain,
13566:                     url, symb (if registered) and group (if this is a 
13567:                     group item -- e.g., bulletin board, group page etc.).
13568: 
13569:  output: array of five scalars --
13570:          $cfile -- url for file editing if editable on current server
13571:          $home -- homeserver of resource (i.e., for author if published,
13572:                                           or course if uploaded.).
13573:          $switchserver --  1 if server switch will be needed.
13574:          $forceedit -- 1 if icon/link should be to go to edit mode 
13575:          $forceview -- 1 if icon/link should be to go to view mode
13576: 
13577: =item *
13578: 
13579: is_course_upload($file,$cnum,$cdom)
13580: 
13581: Used in course context to determine if current file was uploaded to 
13582: the course (i.e., would be found in /userfiles/docs on the course's 
13583: homeserver.
13584: 
13585:   input: 3 args -- filename (decluttered), course number and course domain.
13586:   output: boolean -- 1 if file was uploaded.
13587: 
13588: =back
13589: 
13590: =head2 Storing/Retreiving Data
13591: 
13592: =over 4
13593: 
13594: =item *
13595: 
13596: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13597: permanently for this url; hashref needs to be given and should be a \%hashname;
13598: the remaining args aren't required and if they aren't passed or are '' they will
13599: be derived from the env (with the exception of $laststore, which is an 
13600: optional arg used when a user's submission is stored in grading).
13601: $laststore is $version=$timestamp, where $version is the most recent version
13602: number retrieved for the corresponding $symb in the $namespace db file, and
13603: $timestamp is the timestamp for that transaction (UNIX time).
13604: $laststore is currently only passed when cstore() is called by 
13605: structuretags::finalize_storage().
13606: 
13607: =item *
13608: 
13609: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13610: but uses critical subroutine
13611: 
13612: =item *
13613: 
13614: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13615: all args are optional
13616: 
13617: =item *
13618: 
13619: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13620: dumps the complete (or key matching regexp) namespace into a hash
13621: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13622: normally &store()ed into
13623: 
13624: $range should be either an integer '100' (give me the first 100
13625:                                            matching records)
13626:               or be  two integers sperated by a - with no spaces
13627:                  '30-50' (give me the 30th through the 50th matching
13628:                           records)
13629: 
13630: 
13631: =item *
13632: 
13633: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13634: replaces a &store() version of data with a replacement set of data
13635: for a particular resource in a namespace passed in the $storehash hash 
13636: reference. If $tolog is true, the transaction is logged in the courselog
13637: with an action=PUTSTORE.
13638: 
13639: =item *
13640: 
13641: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13642: works very similar to store/cstore, but all data is stored in a
13643: temporary location and can be reset using tmpreset, $storehash should
13644: be a hash reference, returns nothing on success
13645: 
13646: =item *
13647: 
13648: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13649: similar to restore, but all data is stored in a temporary location and
13650: can be reset using tmpreset. Returns a hash of values on success,
13651: error string otherwise.
13652: 
13653: =item *
13654: 
13655: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13656: deltes all keys for $symb form the temporary storage hash.
13657: 
13658: =item *
13659: 
13660: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13661: reference filled in from namesp ($udom and $uname are optional)
13662: 
13663: =item *
13664: 
13665: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13666: namesp ($udom and $uname are optional)
13667: 
13668: =item *
13669: 
13670: dump($namespace,$udom,$uname,$regexp,$range) : 
13671: dumps the complete (or key matching regexp) namespace into a hash
13672: ($udom, $uname, $regexp, $range are optional)
13673: 
13674: $range should be either an integer '100' (give me the first 100
13675:                                            matching records)
13676:               or be  two integers sperated by a - with no spaces
13677:                  '30-50' (give me the 30th through the 50th matching
13678:                           records)
13679: =item *
13680: 
13681: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13682: $store can be a scalar, an array reference, or if the amount to be 
13683: incremented is > 1, a hash reference.
13684: 
13685: ($udom and $uname are optional)
13686: 
13687: =item *
13688: 
13689: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13690: ($udom and $uname are optional)
13691: 
13692: =item *
13693: 
13694: cput($namespace,$storehash,$udom,$uname) : critical put
13695: ($udom and $uname are optional)
13696: 
13697: =item *
13698: 
13699: newput($namespace,$storehash,$udom,$uname) :
13700: 
13701: Attempts to store the items in the $storehash, but only if they don't
13702: currently exist, if this succeeds you can be certain that you have 
13703: successfully created a new key value pair in the $namespace db.
13704: 
13705: 
13706: Args:
13707:  $namespace: name of database to store values to
13708:  $storehash: hashref to store to the db
13709:  $udom: (optional) domain of user containing the db
13710:  $uname: (optional) name of user caontaining the db
13711: 
13712: Returns:
13713:  'ok' -> succeeded in storing all keys of $storehash
13714:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13715:                         least <key> already existed in the db (other
13716:                         requested keys may also already exist)
13717:  'error: <msg>' -> unable to tie the DB or other error occurred
13718:  'con_lost' -> unable to contact request server
13719:  'refused' -> action was not allowed by remote machine
13720: 
13721: 
13722: =item *
13723: 
13724: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13725: reference filled in from namesp (encrypts the return communication)
13726: ($udom and $uname are optional)
13727: 
13728: =item *
13729: 
13730: log($udom,$name,$home,$message) : write to permanent log for user; use
13731: critical subroutine
13732: 
13733: =item *
13734: 
13735: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13736: array reference filled in from namespace found in domain level on either
13737: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13738: 
13739: =item *
13740: 
13741: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13742: domain level either on specified domain server ($uhome) or primary domain 
13743: server ($udom and $uhome are optional)
13744: 
13745: =item * 
13746: 
13747: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13748: for: authentication, language, quotas, timezone, date locale, and portal URL in
13749: the target domain.
13750: 
13751: May also include additional key => value pairs for the following groups:
13752: 
13753: =over
13754: 
13755: =item
13756: disk quotas (MB allocated by default to portfolios and authoring spaces).
13757: 
13758: =over
13759: 
13760: =item defaultquota, authorquota
13761: 
13762: =back
13763: 
13764: =item
13765: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13766: portfolio for users).
13767: 
13768: =over
13769: 
13770: =item
13771: aboutme, blog, webdav, portfolio
13772: 
13773: =back
13774: 
13775: =item
13776: requestcourses: ability to request courses, and how requests are processed.
13777: 
13778: =over
13779: 
13780: =item
13781: official, unofficial, community, textbook
13782: 
13783: =back
13784: 
13785: =item
13786: inststatus: types of institutional affiliation, and order in which they are displayed.
13787: 
13788: =over
13789: 
13790: =item
13791: inststatustypes, inststatusorder, inststatusguest
13792: 
13793: =back
13794: 
13795: =item
13796: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13797: for course's uploaded content.
13798: 
13799: =over
13800: 
13801: =item
13802: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13803: communityquota, textbookquota
13804: 
13805: =back
13806: 
13807: =item
13808: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13809: on your servers.
13810: 
13811: =over
13812: 
13813: =item 
13814: remotesessions, hostedsessions
13815: 
13816: =back
13817: 
13818: =back
13819: 
13820: In cases where a domain coordinator has never used the "Set Domain Configuration"
13821: utility to create a configuration.db file on a domain's primary library server 
13822: only the following domain defaults: auth_def, auth_arg_def, lang_def
13823: -- corresponding values are authentication type (internal, krb4, krb5,
13824: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13825: will be available. Values are retrieved from cache (if current), unless the
13826: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13827: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13828: 
13829: Typical usage:
13830: 
13831: %domdefaults = &get_domain_defaults($target_domain);
13832: 
13833: =back
13834: 
13835: =head2 Network Status Functions
13836: 
13837: =over 4
13838: 
13839: =item *
13840: 
13841: dirlist() : return directory list based on URI (first arg).
13842: 
13843: Inputs: 1 required, 5 optional.
13844: 
13845: =over
13846: 
13847: =item 
13848: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13849: 
13850: =item
13851: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13852: 
13853: =item
13854: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13855: 
13856: =item
13857: $getpropath - boolean: 1 if prepend path using &propath(). 
13858: 
13859: =item
13860: $getuserdir - boolean: 1 if prepend path for "userfiles".
13861: 
13862: =item 
13863: $alternateRoot - path to prepend in place of path from $uri.
13864: 
13865: =back
13866: 
13867: Returns: Array of up to two items.
13868: 
13869: =over
13870: 
13871: a reference to an array of files/subdirectories
13872: 
13873: =over
13874: 
13875: Each element in the array of files/subdirectories is a & separated list of
13876: item name and the result of running stat on the item.  If dirlist was requested
13877: for a file instead of a directory, the item name will be ''. For a directory 
13878: listing, if the item is a metadata file, the element will end &N&M 
13879: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13880: default copyright set (1).  
13881: 
13882: =back
13883: 
13884: a scalar containing error condition (if encountered).
13885: 
13886: =over
13887: 
13888: =item 
13889: no_host (no homeserver identified for $username:$domain).
13890: 
13891: =item 
13892: no_such_host (server contacted for listing not identified as valid host).
13893: 
13894: =item 
13895: con_lost (connection to remote server failed).
13896: 
13897: =item 
13898: refused (invalid $username:$domain received on lond side).
13899: 
13900: =item 
13901: no_such_dir (directory at specified path on lond side does not exist). 
13902: 
13903: =item 
13904: empty (directory at specified path on lond side is empty).
13905: 
13906: =over
13907: 
13908: This is currently not encountered because the &ls3, &ls2, 
13909: &ls (_handler) routines on the lond side do not filter out
13910: . and .. from a directory listing. 
13911: 
13912: =back
13913: 
13914: =back
13915: 
13916: =back
13917: 
13918: =item *
13919: 
13920: spareserver() : find server with least workload from spare.tab
13921: 
13922: 
13923: =item *
13924: 
13925: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13926: if there is no corresponding loncapa host.
13927: 
13928: =back
13929: 
13930: 
13931: =head2 Apache Request
13932: 
13933: =over 4
13934: 
13935: =item *
13936: 
13937: ssi($url,%hash) : server side include, does a complete request cycle on url to
13938: localhost, posts hash
13939: 
13940: =back
13941: 
13942: =head2 Data to String to Data
13943: 
13944: =over 4
13945: 
13946: =item *
13947: 
13948: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13949: and '&' separators, supports elements that are arrayrefs and hashrefs
13950: 
13951: =item *
13952: 
13953: hashref2str($hashref) : convert a hashref into a string complete with
13954: escaping and '=' and '&' separators, supports elements that are
13955: arrayrefs and hashrefs
13956: 
13957: =item *
13958: 
13959: arrayref2str($arrayref) : convert an arrayref into a string complete
13960: with escaping and '&' separators, supports elements that are arrayrefs
13961: and hashrefs
13962: 
13963: =item *
13964: 
13965: str2hash($string) : convert string to hash using unescaping and
13966: splitting on '=' and '&', supports elements that are arrayrefs and
13967: hashrefs
13968: 
13969: =item *
13970: 
13971: str2array($string) : convert string to hash using unescaping and
13972: splitting on '&', supports elements that are arrayrefs and hashrefs
13973: 
13974: =back
13975: 
13976: =head2 Logging Routines
13977: 
13978: 
13979: These routines allow one to make log messages in the lonnet.log and
13980: lonnet.perm logfiles.
13981: 
13982: =over 4
13983: 
13984: =item *
13985: 
13986: logtouch() : make sure the logfile, lonnet.log, exists
13987: 
13988: =item *
13989: 
13990: logthis() : append message to the normal lonnet.log file, it gets
13991: preiodically rolled over and deleted.
13992: 
13993: =item *
13994: 
13995: logperm() : append a permanent message to lonnet.perm.log, this log
13996: file never gets deleted by any automated portion of the system, only
13997: messages of critical importance should go in here.
13998: 
13999: 
14000: =back
14001: 
14002: =head2 General File Helper Routines
14003: 
14004: =over 4
14005: 
14006: =item *
14007: 
14008: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14009: (a) files in /uploaded
14010:   (i) If a local copy of the file exists - 
14011:       compares modification date of local copy with last-modified date for 
14012:       definitive version stored on home server for course. If local copy is 
14013:       stale, requests a new version from the home server and stores it. 
14014:       If the original has been removed from the home server, then local copy 
14015:       is unlinked.
14016:   (ii) If local copy does not exist -
14017:       requests the file from the home server and stores it. 
14018:   
14019:   If $caller is 'uploadrep':  
14020:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14021:     for request for files originally uploaded via DOCS. 
14022:      - returns 'ok' if fresh local copy now available, -1 otherwise.
14023:   
14024:   Otherwise:
14025:      This indicates a call from the content generation phase of the request.
14026:      -  returns the entire contents of the file or -1.
14027:      
14028: (b) files in /res
14029:    - returns the entire contents of a file or -1; 
14030:    it properly subscribes to and replicates the file if neccessary.
14031: 
14032: 
14033: =item *
14034: 
14035: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14036:                   reference
14037: 
14038: returns either a stat() list of data about the file or an empty list
14039: if the file doesn't exist or couldn't find out about it (connection
14040: problems or user unknown)
14041: 
14042: =item *
14043: 
14044: filelocation($dir,$file) : returns file system location of a file
14045: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14046: directory that relative $file lookups are to looked in ($dir of /a/dir
14047: and a file of ../bob will become /a/bob)
14048: 
14049: =item *
14050: 
14051: hreflocation($dir,$file) : returns file system location or a URL; same as
14052: filelocation except for hrefs
14053: 
14054: =item *
14055: 
14056: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14057: also removes beginning /home/httpd/html unless /priv/ follows it.
14058: 
14059: =back
14060: 
14061: =head2 Usererfile file routines (/uploaded*)
14062: 
14063: =over 4
14064: 
14065: =item *
14066: 
14067: userfileupload(): main rotine for putting a file in a user or course's
14068:                   filespace, arguments are,
14069: 
14070:  formname - required - this is the name of the element in $env where the
14071:            filename, and the contents of the file to create/modifed exist
14072:            the filename is in $env{'form.'.$formname.'.filename'} and the
14073:            contents of the file is located in $env{'form.'.$formname}
14074:  context - if coursedoc, store the file in the course of the active role
14075:              of the current user; 
14076:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14077:            if 'canceloverwrite': delete file in tmp/overwrites directory
14078:  subdir - required - subdirectory to put the file in under ../userfiles/
14079:          if undefined, it will be placed in "unknown"
14080: 
14081:  (This routine calls clean_filename() to remove any dangerous
14082:  characters from the filename, and then calls finuserfileupload() to
14083:  complete the transaction)
14084: 
14085:  returns either the url of the uploaded file (/uploaded/....) if successful
14086:  and /adm/notfound.html if unsuccessful
14087: 
14088: =item *
14089: 
14090: clean_filename(): routine for cleaing a filename up for storage in
14091:                  userfile space, argument is:
14092: 
14093:  filename - proposed filename
14094: 
14095: returns: the new clean filename
14096: 
14097: =item *
14098: 
14099: finishuserfileupload(): routine that creates and sends the file to
14100: userspace, probably shouldn't be called directly
14101: 
14102:   docuname: username or courseid of destination for the file
14103:   docudom: domain of user/course of destination for the file
14104:   formname: same as for userfileupload()
14105:   fname: filename (including subdirectories) for the file
14106:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14107:   allfiles: reference to hash used to store objects found by parser
14108:   codebase: reference to hash used for codebases of java objects found by parser
14109:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14110:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
14111:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
14112:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
14113:   context: if 'overwrite', will move the uploaded file from its temporary location to
14114:             userfiles to facilitate overwriting a previously uploaded file with same name.
14115:   mimetype: reference to scalar to accommodate mime type determined
14116:             from File::MMagic if $parser = parse.
14117: 
14118:  returns either the url of the uploaded file (/uploaded/....) if successful
14119:  and /adm/notfound.html if unsuccessful (or an error message if context 
14120:  was 'overwrite').
14121:  
14122: 
14123: =item *
14124: 
14125: renameuserfile(): renames an existing userfile to a new name
14126: 
14127:   Args:
14128:    docuname: username or courseid of destination for the file
14129:    docudom: domain of user/course of destination for the file
14130:    old: current file name (including any subdirs under userfiles)
14131:    new: desired file name (including any subdirs under userfiles)
14132: 
14133: =item *
14134: 
14135: mkdiruserfile(): creates a directory is a userfiles dir
14136: 
14137:   Args:
14138:    docuname: username or courseid of destination for the file
14139:    docudom: domain of user/course of destination for the file
14140:    dir: dir to create (including any subdirs under userfiles)
14141: 
14142: =item *
14143: 
14144: removeuserfile(): removes a file that exists in userfiles
14145: 
14146:   Args:
14147:    docuname: username or courseid of destination for the file
14148:    docudom: domain of user/course of destination for the file
14149:    fname: filname to delete (including any subdirs under userfiles)
14150: 
14151: =item *
14152: 
14153: removeuploadedurl(): convience function for removeuserfile()
14154: 
14155:   Args:
14156:    url:  a full /uploaded/... url to delete
14157: 
14158: =item * 
14159: 
14160: get_portfile_permissions():
14161:   Args:
14162:     domain: domain of user or course contain the portfolio files
14163:     user: name of user or num of course contain the portfolio files
14164:   Returns:
14165:     hashref of a dump of the proper file_permissions.db
14166:    
14167: 
14168: =item * 
14169: 
14170: get_access_controls():
14171: 
14172: Args:
14173:   current_permissions: the hash ref returned from get_portfile_permissions()
14174:   group: (optional) the group you want the files associated with
14175:   file: (optional) the file you want access info on
14176: 
14177: Returns:
14178:     a hash (keys are file names) of hashes containing
14179:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14180:         values are XML containing access control settings (see below) 
14181: 
14182: Internal notes:
14183: 
14184:  access controls are stored in file_permissions.db as key=value pairs.
14185:     key -> path to file/file_name\0uniqueID:scope_end_start
14186:         where scope -> public,guest,course,group,domains or users.
14187:               end -> UNIX time for end of access (0 -> no end date)
14188:               start -> UNIX time for start of access
14189: 
14190:     value -> XML description of access control
14191:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14192:             <start></start>
14193:             <end></end>
14194: 
14195:             <password></password>  for scope type = guest
14196: 
14197:             <domain></domain>     for scope type = course or group
14198:             <number></number>
14199:             <roles id="">
14200:              <role></role>
14201:              <access></access>
14202:              <section></section>
14203:              <group></group>
14204:             </roles>
14205: 
14206:             <dom></dom>         for scope type = domains
14207: 
14208:             <users>             for scope type = users
14209:              <user>
14210:               <uname></uname>
14211:               <udom></udom>
14212:              </user>
14213:             </users>
14214:            </scope> 
14215:               
14216:  Access data is also aggregated for each file in an additional key=value pair:
14217:  key -> path to file/file_name\0accesscontrol 
14218:  value -> reference to hash
14219:           hash contains key = value pairs
14220:           where key = uniqueID:scope_end_start
14221:                 value = UNIX time record was last updated
14222: 
14223:           Used to improve speed of look-ups of access controls for each file.  
14224:  
14225:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14226: 
14227: =item *
14228: 
14229: modify_access_controls():
14230: 
14231: Modifies access controls for a portfolio file
14232: Args
14233: 1. file name
14234: 2. reference to hash of required changes,
14235: 3. domain
14236: 4. username
14237:   where domain,username are the domain of the portfolio owner 
14238:   (either a user or a course) 
14239: 
14240: Returns:
14241: 1. result of additions or updates ('ok' or 'error', with error message). 
14242: 2. result of deletions ('ok' or 'error', with error message).
14243: 3. reference to hash of any new or updated access controls.
14244: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14245:    key = integer (inbound ID)
14246:    value = uniqueID
14247: 
14248: =item *
14249: 
14250: get_timebased_id():
14251: 
14252: Attempts to get a unique timestamp-based suffix for use with items added to a 
14253: course via the Course Editor (e.g., folders, composite pages, 
14254: group bulletin boards).
14255: 
14256: Args: (first three required; six others optional)
14257: 
14258: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14259:    docssequence, or name of group
14260: 
14261: 2. keyid (alphanumeric): name of temporary locking key in hash,
14262:    e.g., num, boardids
14263: 
14264: 3. namespace: name of gdbm file used to store suffixes already assigned;  
14265:    file will be named nohist_namespace.db
14266: 
14267: 4. cdom: domain of course; default is current course domain from %env
14268: 
14269: 5. cnum: course number; default is current course number from %env
14270: 
14271: 6. idtype: set to concat if an additional digit is to be appended to the 
14272:    unix timestamp to form the suffix, if the plain timestamp is already
14273:    in use.  Default is to not do this, but simply increment the unix 
14274:    timestamp by 1 until a unique key is obtained.
14275: 
14276: 7. who: holder of locking key; defaults to user:domain for user.
14277: 
14278: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
14279:    retrying); default is 3.
14280: 
14281: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
14282: 
14283: Returns:
14284: 
14285: 1. suffix obtained (numeric)
14286: 
14287: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14288: 
14289: 3. error: contains (localized) error message if an error occurred.
14290: 
14291: 
14292: =back
14293: 
14294: =head2 HTTP Helper Routines
14295: 
14296: =over 4
14297: 
14298: =item *
14299: 
14300: escape() : unpack non-word characters into CGI-compatible hex codes
14301: 
14302: =item *
14303: 
14304: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14305: 
14306: =back
14307: 
14308: =head1 PRIVATE SUBROUTINES
14309: 
14310: =head2 Underlying communication routines (Shouldn't call)
14311: 
14312: =over 4
14313: 
14314: =item *
14315: 
14316: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14317: 
14318: =item *
14319: 
14320: reply() : uses subreply to send a message to remote machine, logs all failures
14321: 
14322: =item *
14323: 
14324: critical() : passes a critical message to another server; if cannot
14325: get through then place message in connection buffer directory and
14326: returns con_delayed, if incapable of saving message, returns
14327: con_failed
14328: 
14329: =item *
14330: 
14331: reconlonc() : tries to reconnect lonc client processes.
14332: 
14333: =back
14334: 
14335: =head2 Resource Access Logging
14336: 
14337: =over 4
14338: 
14339: =item *
14340: 
14341: flushcourselogs() : flush (save) buffer logs and access logs
14342: 
14343: =item *
14344: 
14345: courselog($what) : save message for course in hash
14346: 
14347: =item *
14348: 
14349: courseacclog($what) : save message for course using &courselog().  Perform
14350: special processing for specific resource types (problems, exams, quizzes, etc).
14351: 
14352: =item *
14353: 
14354: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14355: as a PerlChildExitHandler
14356: 
14357: =back
14358: 
14359: =head2 Other
14360: 
14361: =over 4
14362: 
14363: =item *
14364: 
14365: symblist($mapname,%newhash) : update symbolic storage links
14366: 
14367: =back
14368: 
14369: =cut
14370: 

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