File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1284: download - view: text, annotated - select for diffs
Sun Apr 19 20:34:25 2015 UTC (9 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Reinstate documentation changes for allowed() in 1.1281, unintentionally
  removed in rev. 1.1282.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1284 2015/04/19 20:34:25 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  853:                                              $try_server));
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     next unless (&spare_can_host($udom,$uint_dom,
  865:                                                  $remotesessions,$try_server));
  866: 	            ($spare_server, $lowest_load) =
  867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  868:                 }
  869: 	    }
  870:         }
  871:     }
  872: 
  873:     if (!$want_server_name) {
  874:         my $protocol = 'http';
  875:         if ($protocol{$spare_server} eq 'https') {
  876:             $protocol = $protocol{$spare_server};
  877:         }
  878:         if (defined($spare_server)) {
  879:             my $hostname = &hostname($spare_server);
  880:             if (defined($hostname)) {
  881: 	        $spare_server = $protocol.'://'.$hostname;
  882:             }
  883:         }
  884:     }
  885:     return $spare_server;
  886: }
  887: 
  888: sub compare_server_load {
  889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  890: 
  891:     if ($required) {
  892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  895:         if (($major eq '' && $minor eq '') ||
  896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  897:             return ($spare_server,$lowest_load);
  898:         }
  899:     }
  900: 
  901:     my $loadans     = &reply('load',    $try_server);
  902:     my $userloadans = &reply('userload',$try_server);
  903: 
  904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  906:     }
  907: 
  908:     my $load;
  909:     if ($loadans =~ /\d/) {
  910: 	if ($userloadans =~ /\d/) {
  911: 	    #both are numbers, pick the bigger one
  912: 	    $load = ($loadans > $userloadans) ? $loadans 
  913: 		                              : $userloadans;
  914: 	} else {
  915: 	    $load = $loadans;
  916: 	}
  917:     } else {
  918: 	$load = $userloadans;
  919:     }
  920: 
  921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  922: 	$spare_server = $try_server;
  923: 	$lowest_load  = $load;
  924:     }
  925:     return ($spare_server,$lowest_load);
  926: }
  927: 
  928: # --------------------------- ask offload servers if user already has a session
  929: sub find_existing_session {
  930:     my ($udom,$uname) = @_;
  931:     my $spareshash = &this_host_spares($udom);
  932:     if (ref($spareshash) eq 'HASH') {
  933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  941:             }
  942:         }
  943:     }
  944:     return;
  945: }
  946: 
  947: # -------------------------------- ask if server already has a session for user
  948: sub has_user_session {
  949:     my ($lonid,$udom,$uname) = @_;
  950:     my $result = &reply(join(':','userhassession',
  951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  952:     return 1 if ($result eq 'ok');
  953: 
  954:     return 0;
  955: }
  956: 
  957: # --------- determine least loaded server in a user's domain which allows login
  958: 
  959: sub choose_server {
  960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  962:     my %servers = &get_servers($udom);
  963:     my $lowest_load = 30000;
  964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  965:     if ($skiploadbal) {
  966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  967:         unless (defined($cached)) {
  968:             my $cachetime = 60*60*24;
  969:             my %domconfig =
  970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  973:                                            $cachetime);
  974:             }
  975:         }
  976:     }
  977:     foreach my $lonhost (keys(%servers)) {
  978:         if ($skiploadbal) {
  979:             if (ref($balancers) eq 'HASH') {
  980:                 next if (exists($balancers->{$lonhost}));
  981:             }
  982:         }   
  983:         my $loginvia;
  984:         if ($checkloginvia) {
  985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  986:             if ($loginvia) {
  987:                 my ($server,$path) = split(/:/,$loginvia);
  988:                 ($login_host, $lowest_load) =
  989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  990:                 if ($login_host eq $server) {
  991:                     $portal_path = $path;
  992:                     $isredirect = 1;
  993:                 }
  994:             } else {
  995:                 ($login_host, $lowest_load) =
  996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  997:                 if ($login_host eq $lonhost) {
  998:                     $portal_path = '';
  999:                     $isredirect = ''; 
 1000:                 }
 1001:             }
 1002:         } else {
 1003:             ($login_host, $lowest_load) =
 1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1005:         }
 1006:     }
 1007:     if ($login_host ne '') {
 1008:         $hostname = &hostname($login_host);
 1009:     }
 1010:     return ($login_host,$hostname,$portal_path,$isredirect);
 1011: }
 1012: 
 1013: # --------------------------------------------- Try to change a user's password
 1014: 
 1015: sub changepass {
 1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1017:     $currentpass = &escape($currentpass);
 1018:     $newpass     = &escape($newpass);
 1019:     my $lonhost = $perlvar{'lonHostID'};
 1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1021: 		       $server);
 1022:     if (! $answer) {
 1023: 	&logthis("No reply on password change request to $server ".
 1024: 		 "by $uname in domain $udom.");
 1025:     } elsif ($answer =~ "^ok") {
 1026:         &logthis("$uname in $udom successfully changed their password ".
 1027: 		 "on $server.");
 1028:     } elsif ($answer =~ "^pwchange_failure") {
 1029: 	&logthis("$uname in $udom was unable to change their password ".
 1030: 		 "on $server.  The action was blocked by either lcpasswd ".
 1031: 		 "or pwchange");
 1032:     } elsif ($answer =~ "^non_authorized") {
 1033:         &logthis("$uname in $udom did not get their password correct when ".
 1034: 		 "attempting to change it on $server.");
 1035:     } elsif ($answer =~ "^auth_mode_error") {
 1036:         &logthis("$uname in $udom attempted to change their password despite ".
 1037: 		 "not being locally or internally authenticated on $server.");
 1038:     } elsif ($answer =~ "^unknown_user") {
 1039:         &logthis("$uname in $udom attempted to change their password ".
 1040: 		 "on $server but were unable to because $server is not ".
 1041: 		 "their home server.");
 1042:     } elsif ($answer =~ "^refused") {
 1043: 	&logthis("$server refused to change $uname in $udom password because ".
 1044: 		 "it was sent an unencrypted request to change the password.");
 1045:     } elsif ($answer =~ "invalid_client") {
 1046:         &logthis("$server refused to change $uname in $udom password because ".
 1047:                  "it was a reset by e-mail originating from an invalid server.");
 1048:     }
 1049:     return $answer;
 1050: }
 1051: 
 1052: # ----------------------- Try to determine user's current authentication scheme
 1053: 
 1054: sub queryauthenticate {
 1055:     my ($uname,$udom)=@_;
 1056:     my $uhome=&homeserver($uname,$udom);
 1057:     if (!$uhome) {
 1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1059: 	return 'no_host';
 1060:     }
 1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1064:     }
 1065:     return $answer;
 1066: }
 1067: 
 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
 1069: 
 1070: sub authenticate {
 1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1072:     $upass=&escape($upass);
 1073:     $uname= &LONCAPA::clean_username($uname);
 1074:     my $uhome=&homeserver($uname,$udom,1);
 1075:     my $newhome;
 1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1077: # Maybe the machine was offline and only re-appeared again recently?
 1078:         &reconlonc();
 1079: # One more
 1080: 	$uhome=&homeserver($uname,$udom,1);
 1081:         if (($uhome eq 'no_host') && $checkdefauth) {
 1082:             if (defined(&domain($udom,'primary'))) {
 1083:                 $newhome=&domain($udom,'primary');
 1084:             }
 1085:             if ($newhome ne '') {
 1086:                 $uhome = $newhome;
 1087:             }
 1088:         }
 1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1091: 	    return 'no_host';
 1092:         }
 1093:     }
 1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1095:     if ($answer eq 'authorized') {
 1096:         if ($newhome) {
 1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1098:             return 'no_account_on_host'; 
 1099:         } else {
 1100:             &logthis("User $uname at $udom authorized by $uhome");
 1101:             return $uhome;
 1102:         }
 1103:     }
 1104:     if ($answer eq 'non_authorized') {
 1105: 	&logthis("User $uname at $udom rejected by $uhome");
 1106: 	return 'no_host'; 
 1107:     }
 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1109:     return 'no_host';
 1110: }
 1111: 
 1112: sub can_host_session {
 1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1114:     my $canhost = 1;
 1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1116:     if (ref($remotesessions) eq 'HASH') {
 1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1119:                 $canhost = 0;
 1120:             } else {
 1121:                 $canhost = 1;
 1122:             }
 1123:         }
 1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1126:                 $canhost = 1;
 1127:             } else {
 1128:                 $canhost = 0;
 1129:             }
 1130:         }
 1131:         if ($canhost) {
 1132:             if ($remotesessions->{'version'} ne '') {
 1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1134:                 if ($reqmajor ne '' && $reqminor ne '') {
 1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1136:                         my $major = $1;
 1137:                         my $minor = $2;
 1138:                         if (($major < $reqmajor ) ||
 1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1140:                             $canhost = 0;
 1141:                         }
 1142:                     } else {
 1143:                         $canhost = 0;
 1144:                     }
 1145:                 }
 1146:             }
 1147:         }
 1148:     }
 1149:     if ($canhost) {
 1150:         if (ref($hostedsessions) eq 'HASH') {
 1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1154:                 if (($uint_dom ne '') && 
 1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1156:                     $canhost = 0;
 1157:                 } else {
 1158:                     $canhost = 1;
 1159:                 }
 1160:             }
 1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1162:                 if (($uint_dom ne '') && 
 1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1164:                     $canhost = 1;
 1165:                 } else {
 1166:                     $canhost = 0;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return $canhost;
 1172: }
 1173: 
 1174: sub spare_can_host {
 1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1176:     my $canhost=1;
 1177:     my $try_server_hostname = &hostname($try_server);
 1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1179:     my $serverhomedom = &host_domain($serverhomeID);
 1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1183:             $canhost = 0;
 1184:         }
 1185:     }
 1186:     if (($canhost) && ($uint_dom)) {
 1187:         my @intdoms;
 1188:         my $internet_names = &get_internet_names($try_server);
 1189:         if (ref($internet_names) eq 'ARRAY') {
 1190:             @intdoms = @{$internet_names};
 1191:         }
 1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1195:                                          $remotesessions,
 1196:                                          $defdomdefaults{'hostedsessions'});
 1197:         }
 1198:     }
 1199:     return $canhost;
 1200: }
 1201: 
 1202: sub this_host_spares {
 1203:     my ($dom) = @_;
 1204:     my ($dom_in_use,$lonhost_in_use,$result);
 1205:     my @hosts = &current_machine_ids();
 1206:     foreach my $lonhost (@hosts) {
 1207:         if (&host_domain($lonhost) eq $dom) {
 1208:             $dom_in_use = $dom;
 1209:             $lonhost_in_use = $lonhost;
 1210:             last;
 1211:         }
 1212:     }
 1213:     if ($dom_in_use ne '') {
 1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1215:     }
 1216:     if (ref($result) ne 'HASH') {
 1217:         $lonhost_in_use = $perlvar{'lonHostID'};
 1218:         $dom_in_use = &host_domain($lonhost_in_use);
 1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1220:         if (ref($result) ne 'HASH') {
 1221:             $result = \%spareid;
 1222:         }
 1223:     }
 1224:     return $result;
 1225: }
 1226: 
 1227: sub spares_for_offload  {
 1228:     my ($dom_in_use,$lonhost_in_use) = @_;
 1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1230:     if (defined($cached)) {
 1231:         return $result;
 1232:     } else {
 1233:         my $cachetime = 60*60*24;
 1234:         my %domconfig =
 1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1240:                 }
 1241:             }
 1242:         }
 1243:     }
 1244:     return;
 1245: }
 1246: 
 1247: sub get_lonbalancer_config {
 1248:     my ($servers) = @_;
 1249:     my ($currbalancer,$currtargets);
 1250:     if (ref($servers) eq 'HASH') {
 1251:         foreach my $server (keys(%{$servers})) {
 1252:             my %what = (
 1253:                          spareid => 1,
 1254:                          perlvar => 1,
 1255:                        );
 1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1257:             if ($result eq 'ok') {
 1258:                 if (ref($returnhash) eq 'HASH') {
 1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1261:                             $currbalancer = $server;
 1262:                             $currtargets = {};
 1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1266:                                 }
 1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1269:                                 }
 1270:                             }
 1271:                             last;
 1272:                         }
 1273:                     }
 1274:                 }
 1275:             }
 1276:         }
 1277:     }
 1278:     return ($currbalancer,$currtargets);
 1279: }
 1280: 
 1281: sub check_loadbalancing {
 1282:     my ($uname,$udom) = @_;
 1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1284:         $rule_in_effect,$offloadto,$otherserver);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my @hosts = &current_machine_ids();
 1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1290:     my $serverhomedom = &host_domain($lonhost);
 1291: 
 1292:     my $cachetime = 60*60*24;
 1293: 
 1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1295:         $dom_in_use = $udom;
 1296:         $homeintdom = 1;
 1297:     } else {
 1298:         $dom_in_use = $serverhomedom;
 1299:     }
 1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1301:     unless (defined($cached)) {
 1302:         my %domconfig =
 1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1306:         }
 1307:     }
 1308:     if (ref($result) eq 'HASH') {
 1309:         ($is_balancer,$currtargets,$currrules) = 
 1310:             &check_balancer_result($result,@hosts);
 1311:         if ($is_balancer) {
 1312:             if (ref($currrules) eq 'HASH') {
 1313:                 if ($homeintdom) {
 1314:                     if ($uname ne '') {
 1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1321:                             }
 1322:                         }
 1323:                         if ($rule_in_effect eq '') {
 1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1325:                             if ($userenv{'inststatus'} ne '') {
 1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1327:                                 my ($othertitle,$usertypes,$types) =
 1328:                                     &Apache::loncommon::sorted_inst_types($udom);
 1329:                                 if (ref($types) eq 'ARRAY') {
 1330:                                     foreach my $type (@{$types}) {
 1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1332:                                             if (exists($currrules->{$type})) {
 1333:                                                 $rule_in_effect = $currrules->{$type};
 1334:                                             }
 1335:                                         }
 1336:                                     }
 1337:                                 }
 1338:                             } else {
 1339:                                 if (exists($currrules->{'default'})) {
 1340:                                     $rule_in_effect = $currrules->{'default'};
 1341:                                 }
 1342:                             }
 1343:                         }
 1344:                     } else {
 1345:                         if (exists($currrules->{'default'})) {
 1346:                             $rule_in_effect = $currrules->{'default'};
 1347:                         }
 1348:                     }
 1349:                 } else {
 1350:                     if ($currrules->{'_LC_external'} ne '') {
 1351:                         $rule_in_effect = $currrules->{'_LC_external'};
 1352:                     }
 1353:                 }
 1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1355:                                                        $uname,$udom);
 1356:             }
 1357:         }
 1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1360:         unless (defined($cached)) {
 1361:             my %domconfig =
 1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1365:             }
 1366:         }
 1367:         if (ref($result) eq 'HASH') {
 1368:             ($is_balancer,$currtargets,$currrules) = 
 1369:                 &check_balancer_result($result,@hosts);
 1370:             if ($is_balancer) {
 1371:                 if (ref($currrules) eq 'HASH') {
 1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1374:                     }
 1375:                 }
 1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1377:                                                        $uname,$udom);
 1378:             }
 1379:         } else {
 1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1381:                 $is_balancer = 1;
 1382:                 $offloadto = &this_host_spares($dom_in_use);
 1383:             }
 1384:         }
 1385:     } else {
 1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1387:             $is_balancer = 1;
 1388:             $offloadto = &this_host_spares($dom_in_use);
 1389:         }
 1390:     }
 1391:     if ($is_balancer) {
 1392:         my $lowest_load = 30000;
 1393:         if (ref($offloadto) eq 'HASH') {
 1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1396:                     ($otherserver,$lowest_load) =
 1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1398:                 }
 1399:             }
 1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1401: 
 1402:             if (!$found_server) {
 1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1405:                         ($otherserver,$lowest_load) =
 1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1407:                     }
 1408:                 }
 1409:             }
 1410:         } elsif (ref($offloadto) eq 'ARRAY') {
 1411:             if (@{$offloadto} == 1) {
 1412:                 $otherserver = $offloadto->[0];
 1413:             } elsif (@{$offloadto} > 1) {
 1414:                 foreach my $try_server (@{$offloadto}) {
 1415:                     ($otherserver,$lowest_load) =
 1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1417:                 }
 1418:             }
 1419:         }
 1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1421:             $is_balancer = 0;
 1422:             if ($uname ne '' && $udom ne '') {
 1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1424:                     
 1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1426:                              'user.loadbalcheck.time' => time});
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return ($is_balancer,$otherserver);
 1432: }
 1433: 
 1434: sub check_balancer_result {
 1435:     my ($result,@hosts) = @_;
 1436:     my ($is_balancer,$currtargets,$currrules);
 1437:     if (ref($result) eq 'HASH') {
 1438:         if ($result->{'lonhost'} ne '') {
 1439:             my $currbalancer = $result->{'lonhost'};
 1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1441:                 $is_balancer = 1;
 1442:                 $currtargets = $result->{'targets'};
 1443:                 $currrules = $result->{'rules'};
 1444:             }
 1445:         } else {
 1446:             foreach my $key (keys(%{$result})) {
 1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1448:                     (ref($result->{$key}) eq 'HASH')) {
 1449:                     $is_balancer = 1;
 1450:                     $currrules = $result->{$key}{'rules'};
 1451:                     $currtargets = $result->{$key}{'targets'};
 1452:                     last;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     return ($is_balancer,$currtargets,$currrules);
 1458: }
 1459: 
 1460: sub get_loadbalancer_targets {
 1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1462:     my $offloadto;
 1463:     if ($rule_in_effect eq 'none') {
 1464:         return [$perlvar{'lonHostID'}];
 1465:     } elsif ($rule_in_effect eq '') {
 1466:         $offloadto = $currtargets;
 1467:     } else {
 1468:         if ($rule_in_effect eq 'homeserver') {
 1469:             my $homeserver = &homeserver($uname,$udom);
 1470:             if ($homeserver ne 'no_host') {
 1471:                 $offloadto = [$homeserver];
 1472:             }
 1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1474:             my %domconfig =
 1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1480:                     }
 1481:                 }
 1482:             } else {
 1483:                 my %servers = &internet_dom_servers($udom);
 1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1485:                 if (&hostname($remotebalancer) ne '') {
 1486:                     $offloadto = [$remotebalancer];
 1487:                 }
 1488:             }
 1489:         } elsif (&hostname($rule_in_effect) ne '') {
 1490:             $offloadto = [$rule_in_effect];
 1491:         }
 1492:     }
 1493:     return $offloadto;
 1494: }
 1495: 
 1496: sub internet_dom_servers {
 1497:     my ($dom) = @_;
 1498:     my (%uniqservers,%servers);
 1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1500:     my @machinedoms = &machine_domains($primaryserver);
 1501:     foreach my $mdom (@machinedoms) {
 1502:         my %currservers = %servers;
 1503:         my %server = &get_servers($mdom);
 1504:         %servers = (%currservers,%server);
 1505:     }
 1506:     my %by_hostname;
 1507:     foreach my $id (keys(%servers)) {
 1508:         push(@{$by_hostname{$servers{$id}}},$id);
 1509:     }
 1510:     foreach my $hostname (sort(keys(%by_hostname))) {
 1511:         if (@{$by_hostname{$hostname}} > 1) {
 1512:             my $match = 0;
 1513:             foreach my $id (@{$by_hostname{$hostname}}) {
 1514:                 if (&host_domain($id) eq $dom) {
 1515:                     $uniqservers{$id} = $hostname;
 1516:                     $match = 1;
 1517:                 }
 1518:             }
 1519:             unless ($match) {
 1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1521:             }
 1522:         } else {
 1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1524:         }
 1525:     }
 1526:     return %uniqservers;
 1527: }
 1528: 
 1529: # ---------------------- Find the homebase for a user from domain's lib servers
 1530: 
 1531: my %homecache;
 1532: sub homeserver {
 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
 1534:     my $index="$uname:$udom";
 1535: 
 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1537: 
 1538:     my %servers = &get_servers($udom,'library');
 1539:     foreach my $tryserver (keys(%servers)) {
 1540:         next if ($ignoreBadCache ne 'true' && 
 1541: 		 exists($badServerCache{$tryserver}));
 1542: 
 1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1544: 	if ($answer eq 'found') {
 1545: 	    delete($badServerCache{$tryserver}); 
 1546: 	    return $homecache{$index}=$tryserver;
 1547: 	} elsif ($answer eq 'no_host') {
 1548: 	    $badServerCache{$tryserver}=1;
 1549: 	}
 1550:     }    
 1551:     return 'no_host';
 1552: }
 1553: 
 1554: # ------------------------------------- Find the usernames behind a list of IDs
 1555: 
 1556: sub idget {
 1557:     my ($udom,@ids)=@_;
 1558:     my %returnhash=();
 1559:     
 1560:     my %servers = &get_servers($udom,'library');
 1561:     foreach my $tryserver (keys(%servers)) {
 1562: 	my $idlist=join('&',@ids);
 1563: 	$idlist=~tr/A-Z/a-z/; 
 1564: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1565: 	my @answer=();
 1566: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1567: 	    @answer=split(/\&/,$reply);
 1568: 	}                    ;
 1569: 	my $i;
 1570: 	for ($i=0;$i<=$#ids;$i++) {
 1571: 	    if ($answer[$i]) {
 1572: 		$returnhash{$ids[$i]}=$answer[$i];
 1573: 	    } 
 1574: 	}
 1575:     } 
 1576:     return %returnhash;
 1577: }
 1578: 
 1579: # ------------------------------------- Find the IDs behind a list of usernames
 1580: 
 1581: sub idrget {
 1582:     my ($udom,@unames)=@_;
 1583:     my %returnhash=();
 1584:     foreach my $uname (@unames) {
 1585:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1586:     }
 1587:     return %returnhash;
 1588: }
 1589: 
 1590: # ------------------------------- Store away a list of names and associated IDs
 1591: 
 1592: sub idput {
 1593:     my ($udom,%ids)=@_;
 1594:     my %servers=();
 1595:     foreach my $uname (keys(%ids)) {
 1596: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1597:         my $uhom=&homeserver($uname,$udom);
 1598:         if ($uhom ne 'no_host') {
 1599:             my $id=&escape($ids{$uname});
 1600:             $id=~tr/A-Z/a-z/;
 1601:             my $esc_unam=&escape($uname);
 1602: 	    if ($servers{$uhom}) {
 1603: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1604:             } else {
 1605:                 $servers{$uhom}=$id.'='.$esc_unam;
 1606:             }
 1607:         }
 1608:     }
 1609:     foreach my $server (keys(%servers)) {
 1610:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1611:     }
 1612: }
 1613: 
 1614: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1615: 
 1616: sub iddel {
 1617:     my ($udom,$idshashref,$uhome)=@_;
 1618:     my %result=();
 1619:     unless (ref($idshashref) eq 'HASH') {
 1620:         return %result;
 1621:     }
 1622:     my %servers=();
 1623:     while (my ($id,$uname) = each(%{$idshashref})) {
 1624:         my $uhom;
 1625:         if ($uhome) {
 1626:             $uhom = $uhome;
 1627:         } else {
 1628:             $uhom=&homeserver($uname,$udom);
 1629:         }
 1630:         if ($uhom ne 'no_host') {
 1631:             if ($servers{$uhom}) {
 1632:                 $servers{$uhom}.='&'.&escape($id);
 1633:             } else {
 1634:                 $servers{$uhom}=&escape($id);
 1635:             }
 1636:         }
 1637:     }
 1638:     foreach my $server (keys(%servers)) {
 1639:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1640:     }
 1641:     return %result;
 1642: }
 1643: 
 1644: # ------------------------------dump from db file owned by domainconfig user
 1645: sub dump_dom {
 1646:     my ($namespace, $udom, $regexp) = @_;
 1647: 
 1648:     $udom ||= $env{'user.domain'};
 1649: 
 1650:     return () unless $udom;
 1651: 
 1652:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1653: }
 1654: 
 1655: # ------------------------------------------ get items from domain db files   
 1656: 
 1657: sub get_dom {
 1658:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1659:     return if ($udom eq 'public');
 1660:     my $items='';
 1661:     foreach my $item (@$storearr) {
 1662:         $items.=&escape($item).'&';
 1663:     }
 1664:     $items=~s/\&$//;
 1665:     if (!$udom) {
 1666:         $udom=$env{'user.domain'};
 1667:         return if ($udom eq 'public');
 1668:         if (defined(&domain($udom,'primary'))) {
 1669:             $uhome=&domain($udom,'primary');
 1670:         } else {
 1671:             undef($uhome);
 1672:         }
 1673:     } else {
 1674:         if (!$uhome) {
 1675:             if (defined(&domain($udom,'primary'))) {
 1676:                 $uhome=&domain($udom,'primary');
 1677:             }
 1678:         }
 1679:     }
 1680:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1681:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1682:         my %returnhash;
 1683:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1684:             return %returnhash;
 1685:         }
 1686:         my @pairs=split(/\&/,$rep);
 1687:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1688:             return @pairs;
 1689:         }
 1690:         my $i=0;
 1691:         foreach my $item (@$storearr) {
 1692:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1693:             $i++;
 1694:         }
 1695:         return %returnhash;
 1696:     } else {
 1697:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1698:     }
 1699: }
 1700: 
 1701: # -------------------------------------------- put items in domain db files 
 1702: 
 1703: sub put_dom {
 1704:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1705:     if (!$udom) {
 1706:         $udom=$env{'user.domain'};
 1707:         if (defined(&domain($udom,'primary'))) {
 1708:             $uhome=&domain($udom,'primary');
 1709:         } else {
 1710:             undef($uhome);
 1711:         }
 1712:     } else {
 1713:         if (!$uhome) {
 1714:             if (defined(&domain($udom,'primary'))) {
 1715:                 $uhome=&domain($udom,'primary');
 1716:             }
 1717:         }
 1718:     } 
 1719:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1720:         my $items='';
 1721:         foreach my $item (keys(%$storehash)) {
 1722:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1723:         }
 1724:         $items=~s/\&$//;
 1725:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1726:     } else {
 1727:         &logthis("put_dom failed - no homeserver and/or domain");
 1728:     }
 1729: }
 1730: 
 1731: # --------------------- newput for items in db file owned by domainconfig user
 1732: sub newput_dom {
 1733:     my ($namespace,$storehash,$udom) = @_;
 1734:     my $result;
 1735:     if (!$udom) {
 1736:         $udom=$env{'user.domain'};
 1737:     }
 1738:     if ($udom) {
 1739:         my $uname = &get_domainconfiguser($udom);
 1740:         $result = &newput($namespace,$storehash,$udom,$uname);
 1741:     }
 1742:     return $result;
 1743: }
 1744: 
 1745: # --------------------- delete for items in db file owned by domainconfig user
 1746: sub del_dom {
 1747:     my ($namespace,$storearr,$udom)=@_;
 1748:     if (ref($storearr) eq 'ARRAY') {
 1749:         if (!$udom) {
 1750:             $udom=$env{'user.domain'};
 1751:         }
 1752:         if ($udom) {
 1753:             my $uname = &get_domainconfiguser($udom); 
 1754:             return &del($namespace,$storearr,$udom,$uname);
 1755:         }
 1756:     }
 1757: }
 1758: 
 1759: # ----------------------------------construct domainconfig user for a domain 
 1760: sub get_domainconfiguser {
 1761:     my ($udom) = @_;
 1762:     return $udom.'-domainconfig';
 1763: }
 1764: 
 1765: sub retrieve_inst_usertypes {
 1766:     my ($udom) = @_;
 1767:     my (%returnhash,@order);
 1768:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1769:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1770:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1771:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1772:     } else {
 1773:         if (defined(&domain($udom,'primary'))) {
 1774:             my $uhome=&domain($udom,'primary');
 1775:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1776:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1777:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1778:                 return (\%returnhash,\@order);
 1779:             }
 1780:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1781:             my @pairs=split(/\&/,$hashitems);
 1782:             foreach my $item (@pairs) {
 1783:                 my ($key,$value)=split(/=/,$item,2);
 1784:                 $key = &unescape($key);
 1785:                 next if ($key =~ /^error: 2 /);
 1786:                 $returnhash{$key}=&thaw_unescape($value);
 1787:             }
 1788:             my @esc_order = split(/\&/,$orderitems);
 1789:             foreach my $item (@esc_order) {
 1790:                 push(@order,&unescape($item));
 1791:             }
 1792:         } else {
 1793:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1794:         }
 1795:         return (\%returnhash,\@order);
 1796:     }
 1797: }
 1798: 
 1799: sub is_domainimage {
 1800:     my ($url) = @_;
 1801:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1802:         if (&domain($1) ne '') {
 1803:             return '1';
 1804:         }
 1805:     }
 1806:     return;
 1807: }
 1808: 
 1809: sub inst_directory_query {
 1810:     my ($srch) = @_;
 1811:     my $udom = $srch->{'srchdomain'};
 1812:     my %results;
 1813:     my $homeserver = &domain($udom,'primary');
 1814:     my $outcome;
 1815:     if ($homeserver ne '') {
 1816: 	my $queryid=&reply("querysend:instdirsearch:".
 1817: 			   &escape($srch->{'srchby'}).':'.
 1818: 			   &escape($srch->{'srchterm'}).':'.
 1819: 			   &escape($srch->{'srchtype'}),$homeserver);
 1820: 	my $host=&hostname($homeserver);
 1821: 	if ($queryid !~/^\Q$host\E\_/) {
 1822: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1823: 	    return;
 1824: 	}
 1825: 	my $response = &get_query_reply($queryid);
 1826: 	my $maxtries = 5;
 1827: 	my $tries = 1;
 1828: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1829: 	    $response = &get_query_reply($queryid);
 1830: 	    $tries ++;
 1831: 	}
 1832: 
 1833:         if (!&error($response) && $response ne 'refused') {
 1834:             if ($response eq 'unavailable') {
 1835:                 $outcome = $response;
 1836:             } else {
 1837:                 $outcome = 'ok';
 1838:                 my @matches = split(/\n/,$response);
 1839:                 foreach my $match (@matches) {
 1840:                     my ($key,$value) = split(/=/,$match);
 1841:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1842:                 }
 1843:             }
 1844:         }
 1845:     }
 1846:     return ($outcome,%results);
 1847: }
 1848: 
 1849: sub usersearch {
 1850:     my ($srch) = @_;
 1851:     my $dom = $srch->{'srchdomain'};
 1852:     my %results;
 1853:     my %libserv = &all_library();
 1854:     my $query = 'usersearch';
 1855:     foreach my $tryserver (keys(%libserv)) {
 1856:         if (&host_domain($tryserver) eq $dom) {
 1857:             my $host=&hostname($tryserver);
 1858:             my $queryid=
 1859:                 &reply("querysend:".&escape($query).':'.
 1860:                        &escape($srch->{'srchby'}).':'.
 1861:                        &escape($srch->{'srchtype'}).':'.
 1862:                        &escape($srch->{'srchterm'}),$tryserver);
 1863:             if ($queryid !~/^\Q$host\E\_/) {
 1864:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1865:                 next;
 1866:             }
 1867:             my $reply = &get_query_reply($queryid);
 1868:             my $maxtries = 1;
 1869:             my $tries = 1;
 1870:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1871:                 $reply = &get_query_reply($queryid);
 1872:                 $tries ++;
 1873:             }
 1874:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1875:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1876:             } else {
 1877:                 my @matches;
 1878:                 if ($reply =~ /\n/) {
 1879:                     @matches = split(/\n/,$reply);
 1880:                 } else {
 1881:                     @matches = split(/\&/,$reply);
 1882:                 }
 1883:                 foreach my $match (@matches) {
 1884:                     my ($uname,$udom,%userhash);
 1885:                     foreach my $entry (split(/:/,$match)) {
 1886:                         my ($key,$value) =
 1887:                             map {&unescape($_);} split(/=/,$entry);
 1888:                         $userhash{$key} = $value;
 1889:                         if ($key eq 'username') {
 1890:                             $uname = $value;
 1891:                         } elsif ($key eq 'domain') {
 1892:                             $udom = $value;
 1893:                         }
 1894:                     }
 1895:                     $results{$uname.':'.$udom} = \%userhash;
 1896:                 }
 1897:             }
 1898:         }
 1899:     }
 1900:     return %results;
 1901: }
 1902: 
 1903: sub get_instuser {
 1904:     my ($udom,$uname,$id) = @_;
 1905:     my $homeserver = &domain($udom,'primary');
 1906:     my ($outcome,%results);
 1907:     if ($homeserver ne '') {
 1908:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1909:                            &escape($id).':'.&escape($udom),$homeserver);
 1910:         my $host=&hostname($homeserver);
 1911:         if ($queryid !~/^\Q$host\E\_/) {
 1912:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1913:             return;
 1914:         }
 1915:         my $response = &get_query_reply($queryid);
 1916:         my $maxtries = 5;
 1917:         my $tries = 1;
 1918:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1919:             $response = &get_query_reply($queryid);
 1920:             $tries ++;
 1921:         }
 1922:         if (!&error($response) && $response ne 'refused') {
 1923:             if ($response eq 'unavailable') {
 1924:                 $outcome = $response;
 1925:             } else {
 1926:                 $outcome = 'ok';
 1927:                 my @matches = split(/\n/,$response);
 1928:                 foreach my $match (@matches) {
 1929:                     my ($key,$value) = split(/=/,$match);
 1930:                     $results{&unescape($key)} = &thaw_unescape($value);
 1931:                 }
 1932:             }
 1933:         }
 1934:     }
 1935:     my %userinfo;
 1936:     if (ref($results{$uname}) eq 'HASH') {
 1937:         %userinfo = %{$results{$uname}};
 1938:     } 
 1939:     return ($outcome,%userinfo);
 1940: }
 1941: 
 1942: sub inst_rulecheck {
 1943:     my ($udom,$uname,$id,$item,$rules) = @_;
 1944:     my %returnhash;
 1945:     if ($udom ne '') {
 1946:         if (ref($rules) eq 'ARRAY') {
 1947:             @{$rules} = map {&escape($_);} (@{$rules});
 1948:             my $rulestr = join(':',@{$rules});
 1949:             my $homeserver=&domain($udom,'primary');
 1950:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1951:                 my $response;
 1952:                 if ($item eq 'username') {                
 1953:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1954:                                               ':'.&escape($uname).':'.$rulestr,
 1955:                                               $homeserver));
 1956:                 } elsif ($item eq 'id') {
 1957:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1958:                                               ':'.&escape($id).':'.$rulestr,
 1959:                                               $homeserver));
 1960:                 } elsif ($item eq 'selfcreate') {
 1961:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1962:                                                &escape($udom).':'.&escape($uname).
 1963:                                               ':'.$rulestr,$homeserver));
 1964:                 }
 1965:                 if ($response ne 'refused') {
 1966:                     my @pairs=split(/\&/,$response);
 1967:                     foreach my $item (@pairs) {
 1968:                         my ($key,$value)=split(/=/,$item,2);
 1969:                         $key = &unescape($key);
 1970:                         next if ($key =~ /^error: 2 /);
 1971:                         $returnhash{$key}=&thaw_unescape($value);
 1972:                     }
 1973:                 }
 1974:             }
 1975:         }
 1976:     }
 1977:     return %returnhash;
 1978: }
 1979: 
 1980: sub inst_userrules {
 1981:     my ($udom,$check) = @_;
 1982:     my (%ruleshash,@ruleorder);
 1983:     if ($udom ne '') {
 1984:         my $homeserver=&domain($udom,'primary');
 1985:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1986:             my $response;
 1987:             if ($check eq 'id') {
 1988:                 $response=&reply('instidrules:'.&escape($udom),
 1989:                                  $homeserver);
 1990:             } elsif ($check eq 'email') {
 1991:                 $response=&reply('instemailrules:'.&escape($udom),
 1992:                                  $homeserver);
 1993:             } else {
 1994:                 $response=&reply('instuserrules:'.&escape($udom),
 1995:                                  $homeserver);
 1996:             }
 1997:             if (($response ne 'refused') && ($response ne 'error') && 
 1998:                 ($response ne 'unknown_cmd') && 
 1999:                 ($response ne 'no_such_host')) {
 2000:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2001:                 my @pairs=split(/\&/,$hashitems);
 2002:                 foreach my $item (@pairs) {
 2003:                     my ($key,$value)=split(/=/,$item,2);
 2004:                     $key = &unescape($key);
 2005:                     next if ($key =~ /^error: 2 /);
 2006:                     $ruleshash{$key}=&thaw_unescape($value);
 2007:                 }
 2008:                 my @esc_order = split(/\&/,$orderitems);
 2009:                 foreach my $item (@esc_order) {
 2010:                     push(@ruleorder,&unescape($item));
 2011:                 }
 2012:             }
 2013:         }
 2014:     }
 2015:     return (\%ruleshash,\@ruleorder);
 2016: }
 2017: 
 2018: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2019: 
 2020: sub get_domain_defaults {
 2021:     my ($domain,$ignore_cache) = @_;
 2022:     return if (($domain eq '') || ($domain eq 'public'));
 2023:     my $cachetime = 60*60*24;
 2024:     unless ($ignore_cache) {
 2025:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2026:         if (defined($cached)) {
 2027:             if (ref($result) eq 'HASH') {
 2028:                 return %{$result};
 2029:             }
 2030:         }
 2031:     }
 2032:     my %domdefaults;
 2033:     my %domconfig =
 2034:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2035:                                   'requestcourses','inststatus',
 2036:                                   'coursedefaults','usersessions',
 2037:                                   'requestauthor','selfenrollment',
 2038:                                   'coursecategories'],$domain);
 2039:     my @coursetypes = ('official','unofficial','community','textbook');
 2040:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2041:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2042:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2043:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2044:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2045:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2046:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2047:     } else {
 2048:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2049:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2050:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2051:     }
 2052:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2053:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2054:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2055:         } else {
 2056:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2057:         }
 2058:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2059:         foreach my $item (@usertools) {
 2060:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2061:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2062:             }
 2063:         }
 2064:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2065:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2066:         }
 2067:     }
 2068:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2069:         foreach my $item ('official','unofficial','community','textbook') {
 2070:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2071:         }
 2072:     }
 2073:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2074:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2075:     }
 2076:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2077:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2078:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2079:         }
 2080:     }
 2081:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2082:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2083:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2084:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2085:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2086:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2087:         }
 2088:         foreach my $type (@coursetypes) {
 2089:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2090:                 unless ($type eq 'community') {
 2091:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2092:                 }
 2093:             }
 2094:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2095:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2096:             }
 2097:             if ($domdefaults{'postsubmit'} eq 'on') {
 2098:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2099:                     $domdefaults{$type.'postsubtimeout'} = 
 2100:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2101:                 }
 2102:             }
 2103:         }
 2104:     }
 2105:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2106:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2107:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2108:         }
 2109:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2110:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2111:         }
 2112:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2113:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2114:         }
 2115:     }
 2116:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2117:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2118:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2119:                             'approval','limit');
 2120:             foreach my $type (@coursetypes) {
 2121:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2122:                     my @mgrdc = ();
 2123:                     foreach my $item (@settings) {
 2124:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2125:                             push(@mgrdc,$item);
 2126:                         }
 2127:                     }
 2128:                     if (@mgrdc) {
 2129:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2130:                     }
 2131:                 }
 2132:             }
 2133:         }
 2134:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2135:             foreach my $type (@coursetypes) {
 2136:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2137:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2138:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2139:                     }
 2140:                 }
 2141:             }
 2142:         }
 2143:     }
 2144:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2145:         $domdefaults{'catauth'} = 'std';
 2146:         $domdefaults{'catunauth'} = 'std';
 2147:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2148:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2149:         }
 2150:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2151:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2152:         }
 2153:     }
 2154:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2155:     return %domdefaults;
 2156: }
 2157: 
 2158: # --------------------------------------------------- Assign a key to a student
 2159: 
 2160: sub assign_access_key {
 2161: #
 2162: # a valid key looks like uname:udom#comments
 2163: # comments are being appended
 2164: #
 2165:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2166:     $kdom=
 2167:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2168:     $knum=
 2169:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2170:     $cdom=
 2171:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2172:     $cnum=
 2173:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2174:     $udom=$env{'user.name'} unless (defined($udom));
 2175:     $uname=$env{'user.domain'} unless (defined($uname));
 2176:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2177:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2178:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2179:                                                   # assigned to this person
 2180:                                                   # - this should not happen,
 2181:                                                   # unless something went wrong
 2182:                                                   # the first time around
 2183: # ready to assign
 2184:         $logentry=$1.'; '.$logentry;
 2185:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2186:                                                  $kdom,$knum) eq 'ok') {
 2187: # key now belongs to user
 2188: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2189:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2190:                 &appenv({'environment.'.$envkey => $ckey});
 2191:                 return 'ok';
 2192:             } else {
 2193:                 return 
 2194:   'error: Count not permanently assign key, will need to be re-entered later.';
 2195: 	    }
 2196:         } else {
 2197:             return 'error: Could not assign key, try again later.';
 2198:         }
 2199:     } elsif (!$existing{$ckey}) {
 2200: # the key does not exist
 2201: 	return 'error: The key does not exist';
 2202:     } else {
 2203: # the key is somebody else's
 2204: 	return 'error: The key is already in use';
 2205:     }
 2206: }
 2207: 
 2208: # ------------------------------------------ put an additional comment on a key
 2209: 
 2210: sub comment_access_key {
 2211: #
 2212: # a valid key looks like uname:udom#comments
 2213: # comments are being appended
 2214: #
 2215:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2216:     $cdom=
 2217:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2218:     $cnum=
 2219:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2220:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2221:     if ($existing{$ckey}) {
 2222:         $existing{$ckey}.='; '.$logentry;
 2223: # ready to assign
 2224:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2225:                                                  $cdom,$cnum) eq 'ok') {
 2226: 	    return 'ok';
 2227:         } else {
 2228: 	    return 'error: Count not store comment.';
 2229:         }
 2230:     } else {
 2231: # the key does not exist
 2232: 	return 'error: The key does not exist';
 2233:     }
 2234: }
 2235: 
 2236: # ------------------------------------------------------ Generate a set of keys
 2237: 
 2238: sub generate_access_keys {
 2239:     my ($number,$cdom,$cnum,$logentry)=@_;
 2240:     $cdom=
 2241:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2242:     $cnum=
 2243:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2244:     unless (&allowed('mky',$cdom)) { return 0; }
 2245:     unless (($cdom) && ($cnum)) { return 0; }
 2246:     if ($number>10000) { return 0; }
 2247:     sleep(2); # make sure don't get same seed twice
 2248:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2249:     my $total=0;
 2250:     for (my $i=1;$i<=$number;$i++) {
 2251:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2252:                   sprintf("%lx",int(100000*rand)).'-'.
 2253:                   sprintf("%lx",int(100000*rand));
 2254:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2255:        $newkey=~s/0/h/g; # and also 0 and O
 2256:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2257:        if ($existing{$newkey}) {
 2258:            $i--;
 2259:        } else {
 2260: 	  if (&put('accesskeys',
 2261:               { $newkey => '# generated '.localtime().
 2262:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2263:                            '; '.$logentry },
 2264: 		   $cdom,$cnum) eq 'ok') {
 2265:               $total++;
 2266: 	  }
 2267:        }
 2268:     }
 2269:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2270:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2271:     return $total;
 2272: }
 2273: 
 2274: # ------------------------------------------------------- Validate an accesskey
 2275: 
 2276: sub validate_access_key {
 2277:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2278:     $cdom=
 2279:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2280:     $cnum=
 2281:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2282:     $udom=$env{'user.domain'} unless (defined($udom));
 2283:     $uname=$env{'user.name'} unless (defined($uname));
 2284:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2285:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2286: }
 2287: 
 2288: # ------------------------------------- Find the section of student in a course
 2289: sub devalidate_getsection_cache {
 2290:     my ($udom,$unam,$courseid)=@_;
 2291:     my $hashid="$udom:$unam:$courseid";
 2292:     &devalidate_cache_new('getsection',$hashid);
 2293: }
 2294: 
 2295: sub courseid_to_courseurl {
 2296:     my ($courseid) = @_;
 2297:     #already url style courseid
 2298:     return $courseid if ($courseid =~ m{^/});
 2299: 
 2300:     if (exists($env{'course.'.$courseid.'.num'})) {
 2301: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2302: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2303: 	return "/$cdom/$cnum";
 2304:     }
 2305: 
 2306:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2307:     if (exists($courseinfo{'num'})) {
 2308: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2309:     }
 2310: 
 2311:     return undef;
 2312: }
 2313: 
 2314: sub getsection {
 2315:     my ($udom,$unam,$courseid)=@_;
 2316:     my $cachetime=1800;
 2317: 
 2318:     my $hashid="$udom:$unam:$courseid";
 2319:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2320:     if (defined($cached)) { return $result; }
 2321: 
 2322:     my %Pending; 
 2323:     my %Expired;
 2324:     #
 2325:     # Each role can either have not started yet (pending), be active, 
 2326:     #    or have expired.
 2327:     #
 2328:     # If there is an active role, we are done.
 2329:     #
 2330:     # If there is more than one role which has not started yet, 
 2331:     #     choose the one which will start sooner
 2332:     # If there is one role which has not started yet, return it.
 2333:     #
 2334:     # If there is more than one expired role, choose the one which ended last.
 2335:     # If there is a role which has expired, return it.
 2336:     #
 2337:     $courseid = &courseid_to_courseurl($courseid);
 2338:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2339:     foreach my $key (keys(%roleshash)) {
 2340:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2341:         my $section=$1;
 2342:         if ($key eq $courseid.'_st') { $section=''; }
 2343:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2344:         my $now=time;
 2345:         if (defined($end) && $end && ($now > $end)) {
 2346:             $Expired{$end}=$section;
 2347:             next;
 2348:         }
 2349:         if (defined($start) && $start && ($now < $start)) {
 2350:             $Pending{$start}=$section;
 2351:             next;
 2352:         }
 2353:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2354:     }
 2355:     #
 2356:     # Presumedly there will be few matching roles from the above
 2357:     # loop and the sorting time will be negligible.
 2358:     if (scalar(keys(%Pending))) {
 2359:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2360:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2361:     } 
 2362:     if (scalar(keys(%Expired))) {
 2363:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2364:         my $time = pop(@sorted);
 2365:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2366:     }
 2367:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2368: }
 2369: 
 2370: sub save_cache {
 2371:     &purge_remembered();
 2372:     #&Apache::loncommon::validate_page();
 2373:     undef(%env);
 2374:     undef($env_loaded);
 2375: }
 2376: 
 2377: my $to_remember=-1;
 2378: my %remembered;
 2379: my %accessed;
 2380: my $kicks=0;
 2381: my $hits=0;
 2382: sub make_key {
 2383:     my ($name,$id) = @_;
 2384:     if (length($id) > 65 
 2385: 	&& length(&escape($id)) > 200) {
 2386: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2387:     }
 2388:     return &escape($name.':'.$id);
 2389: }
 2390: 
 2391: sub devalidate_cache_new {
 2392:     my ($name,$id,$debug) = @_;
 2393:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2394:     $id=&make_key($name,$id);
 2395:     $memcache->delete($id);
 2396:     delete($remembered{$id});
 2397:     delete($accessed{$id});
 2398: }
 2399: 
 2400: sub is_cached_new {
 2401:     my ($name,$id,$debug) = @_;
 2402:     $id=&make_key($name,$id);
 2403:     if (exists($remembered{$id})) {
 2404: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2405: 	$accessed{$id}=[&gettimeofday()];
 2406: 	$hits++;
 2407: 	return ($remembered{$id},1);
 2408:     }
 2409:     my $value = $memcache->get($id);
 2410:     if (!(defined($value))) {
 2411: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2412: 	return (undef,undef);
 2413:     }
 2414:     if ($value eq '__undef__') {
 2415: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2416: 	$value=undef;
 2417:     }
 2418:     &make_room($id,$value,$debug);
 2419:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2420:     return ($value,1);
 2421: }
 2422: 
 2423: sub do_cache_new {
 2424:     my ($name,$id,$value,$time,$debug) = @_;
 2425:     $id=&make_key($name,$id);
 2426:     my $setvalue=$value;
 2427:     if (!defined($setvalue)) {
 2428: 	$setvalue='__undef__';
 2429:     }
 2430:     if (!defined($time) ) {
 2431: 	$time=600;
 2432:     }
 2433:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2434:     my $result = $memcache->set($id,$setvalue,$time);
 2435:     if (! $result) {
 2436: 	&logthis("caching of id -> $id  failed");
 2437: 	$memcache->disconnect_all();
 2438:     }
 2439:     # need to make a copy of $value
 2440:     &make_room($id,$value,$debug);
 2441:     return $value;
 2442: }
 2443: 
 2444: sub make_room {
 2445:     my ($id,$value,$debug)=@_;
 2446: 
 2447:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2448:                                     : $value;
 2449:     if ($to_remember<0) { return; }
 2450:     $accessed{$id}=[&gettimeofday()];
 2451:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2452:     my $to_kick;
 2453:     my $max_time=0;
 2454:     foreach my $other (keys(%accessed)) {
 2455: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2456: 	    $to_kick=$other;
 2457: 	    $max_time=&tv_interval($accessed{$other});
 2458: 	}
 2459:     }
 2460:     delete($remembered{$to_kick});
 2461:     delete($accessed{$to_kick});
 2462:     $kicks++;
 2463:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2464:     return;
 2465: }
 2466: 
 2467: sub purge_remembered {
 2468:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2469:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2470:     undef(%remembered);
 2471:     undef(%accessed);
 2472: }
 2473: # ------------------------------------- Read an entry from a user's environment
 2474: 
 2475: sub userenvironment {
 2476:     my ($udom,$unam,@what)=@_;
 2477:     my $items;
 2478:     foreach my $item (@what) {
 2479:         $items.=&escape($item).'&';
 2480:     }
 2481:     $items=~s/\&$//;
 2482:     my %returnhash=();
 2483:     my $uhome = &homeserver($unam,$udom);
 2484:     unless ($uhome eq 'no_host') {
 2485:         my @answer=split(/\&/, 
 2486:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2487:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2488:             return %returnhash;
 2489:         }
 2490:         my $i;
 2491:         for ($i=0;$i<=$#what;$i++) {
 2492: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2493:         }
 2494:     }
 2495:     return %returnhash;
 2496: }
 2497: 
 2498: # ---------------------------------------------------------- Get a studentphoto
 2499: sub studentphoto {
 2500:     my ($udom,$unam,$ext) = @_;
 2501:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2502:     if (defined($env{'request.course.id'})) {
 2503:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2504:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2505:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2506:             } else {
 2507:                 my ($result,$perm_reqd)=
 2508: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2509:                 if ($result eq 'ok') {
 2510:                     if (!($perm_reqd eq 'yes')) {
 2511:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2512:                     }
 2513:                 }
 2514:             }
 2515:         }
 2516:     } else {
 2517:         my ($result,$perm_reqd) = 
 2518: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2519:         if ($result eq 'ok') {
 2520:             if (!($perm_reqd eq 'yes')) {
 2521:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2522:             }
 2523:         }
 2524:     }
 2525:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2526: }
 2527: 
 2528: sub retrievestudentphoto {
 2529:     my ($udom,$unam,$ext,$type) = @_;
 2530:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2531:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2532:     if ($ret eq 'ok') {
 2533:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2534:         if ($type eq 'thumbnail') {
 2535:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2536:         }
 2537:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2538:         return $tokenurl;
 2539:     } else {
 2540:         if ($type eq 'thumbnail') {
 2541:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2542:         } else { 
 2543:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2544:         }
 2545:     }
 2546: }
 2547: 
 2548: # -------------------------------------------------------------------- New chat
 2549: 
 2550: sub chatsend {
 2551:     my ($newentry,$anon,$group)=@_;
 2552:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2553:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2554:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2555:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2556: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2557: 		   &escape($newentry)).':'.$group,$chome);
 2558: }
 2559: 
 2560: # ------------------------------------------ Find current version of a resource
 2561: 
 2562: sub getversion {
 2563:     my $fname=&clutter(shift);
 2564:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2565:     return &currentversion(&filelocation('',$fname));
 2566: }
 2567: 
 2568: sub currentversion {
 2569:     my $fname=shift;
 2570:     my $author=$fname;
 2571:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2572:     my ($udom,$uname)=split(/\//,$author);
 2573:     my $home=&homeserver($uname,$udom);
 2574:     if ($home eq 'no_host') { 
 2575:         return -1; 
 2576:     }
 2577:     my $answer=&reply("currentversion:$fname",$home);
 2578:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2579: 	return -1;
 2580:     }
 2581:     return $answer;
 2582: }
 2583: 
 2584: #
 2585: # Return special version number of resource if set by override, empty otherwise
 2586: #
 2587: sub usedversion {
 2588:     my $fname=shift;
 2589:     unless ($fname) { $fname=$env{'request.uri'}; }
 2590:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2591:     if ($urlversion) { return $urlversion; }
 2592:     return '';
 2593: }
 2594: 
 2595: # ----------------------------- Subscribe to a resource, return URL if possible
 2596: 
 2597: sub subscribe {
 2598:     my $fname=shift;
 2599:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2600:     $fname=~s/[\n\r]//g;
 2601:     my $author=$fname;
 2602:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2603:     my ($udom,$uname)=split(/\//,$author);
 2604:     my $home=homeserver($uname,$udom);
 2605:     if ($home eq 'no_host') {
 2606:         return 'not_found';
 2607:     }
 2608:     my $answer=reply("sub:$fname",$home);
 2609:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2610: 	$answer.=' by '.$home;
 2611:     }
 2612:     return $answer;
 2613: }
 2614:     
 2615: # -------------------------------------------------------------- Replicate file
 2616: 
 2617: sub repcopy {
 2618:     my $filename=shift;
 2619:     $filename=~s/\/+/\//g;
 2620:     my $londocroot = $perlvar{'lonDocRoot'};
 2621:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2622:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2623:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2624: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2625: 	return &repcopy_userfile($filename);
 2626:     }
 2627:     $filename=~s/[\n\r]//g;
 2628:     my $transname="$filename.in.transfer";
 2629: # FIXME: this should flock
 2630:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2631:     my $remoteurl=subscribe($filename);
 2632:     if ($remoteurl =~ /^con_lost by/) {
 2633: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2634:            return 'unavailable';
 2635:     } elsif ($remoteurl eq 'not_found') {
 2636: 	   #&logthis("Subscribe returned not_found: $filename");
 2637: 	   return 'not_found';
 2638:     } elsif ($remoteurl =~ /^rejected by/) {
 2639: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2640:            return 'forbidden';
 2641:     } elsif ($remoteurl eq 'directory') {
 2642:            return 'ok';
 2643:     } else {
 2644:         my $author=$filename;
 2645:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2646:         my ($udom,$uname)=split(/\//,$author);
 2647:         my $home=homeserver($uname,$udom);
 2648:         unless ($home eq $perlvar{'lonHostID'}) {
 2649:            my @parts=split(/\//,$filename);
 2650:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2651:            if ($path ne "$londocroot/res") {
 2652:                &logthis("Malconfiguration for replication: $filename");
 2653: 	       return 'bad_request';
 2654:            }
 2655:            my $count;
 2656:            for ($count=5;$count<$#parts;$count++) {
 2657:                $path.="/$parts[$count]";
 2658:                if ((-e $path)!=1) {
 2659: 		   mkdir($path,0777);
 2660:                }
 2661:            }
 2662:            my $ua=new LWP::UserAgent;
 2663:            my $request=new HTTP::Request('GET',"$remoteurl");
 2664:            my $response=$ua->request($request,$transname);
 2665:            if ($response->is_error()) {
 2666: 	       unlink($transname);
 2667:                my $message=$response->status_line;
 2668:                &logthis("<font color=\"blue\">WARNING:"
 2669:                        ." LWP get: $message: $filename</font>");
 2670:                return 'unavailable';
 2671:            } else {
 2672: 	       if ($remoteurl!~/\.meta$/) {
 2673:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2674:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2675:                   if ($mresponse->is_error()) {
 2676: 		      unlink($filename.'.meta');
 2677:                       &logthis(
 2678:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2679:                   }
 2680: 	       }
 2681:                rename($transname,$filename);
 2682:                return 'ok';
 2683:            }
 2684:        }
 2685:     }
 2686: }
 2687: 
 2688: # ------------------------------------------------ Get server side include body
 2689: sub ssi_body {
 2690:     my ($filelink,%form)=@_;
 2691:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2692:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2693:     }
 2694:     my $output='';
 2695:     my $response;
 2696:     if ($filelink=~/^https?\:/) {
 2697:        ($output,$response)=&externalssi($filelink);
 2698:     } else {
 2699:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2700:        $filelink .= 'inhibitmenu=yes';
 2701:        ($output,$response)=&ssi($filelink,%form);
 2702:     }
 2703:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2704:     $output=~s/^.*?\<body[^\>]*\>//si;
 2705:     $output=~s/\<\/body\s*\>.*?$//si;
 2706:     if (wantarray) {
 2707:         return ($output, $response);
 2708:     } else {
 2709:         return $output;
 2710:     }
 2711: }
 2712: 
 2713: # --------------------------------------------------------- Server Side Include
 2714: 
 2715: sub absolute_url {
 2716:     my ($host_name) = @_;
 2717:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2718:     if ($host_name eq '') {
 2719: 	$host_name = $ENV{'SERVER_NAME'};
 2720:     }
 2721:     return $protocol.$host_name;
 2722: }
 2723: 
 2724: #
 2725: #   Server side include.
 2726: # Parameters:
 2727: #  fn     Possibly encrypted resource name/id.
 2728: #  form   Hash that describes how the rendering should be done
 2729: #         and other things.
 2730: # Returns:
 2731: #   Scalar context: The content of the response.
 2732: #   Array context:  2 element list of the content and the full response object.
 2733: #     
 2734: sub ssi {
 2735: 
 2736:     my ($fn,%form)=@_;
 2737:     my $ua=new LWP::UserAgent;
 2738:     my $request;
 2739: 
 2740:     $form{'no_update_last_known'}=1;
 2741:     &Apache::lonenc::check_encrypt(\$fn);
 2742:     if (%form) {
 2743:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2744:       $request->content(join('&',map { 
 2745:             my $name = escape($_);
 2746:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 2747:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 2748:             : &escape($form{$_}) );    
 2749:         } keys(%form)));
 2750:     } else {
 2751:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2752:     }
 2753: 
 2754:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2755:     my $response= $ua->request($request);
 2756:     my $content = $response->content;
 2757: 
 2758: 
 2759:     if (wantarray) {
 2760: 	return ($content, $response);
 2761:     } else {
 2762: 	return $content;
 2763:     }
 2764: }
 2765: 
 2766: sub externalssi {
 2767:     my ($url)=@_;
 2768:     my $ua=new LWP::UserAgent;
 2769:     my $request=new HTTP::Request('GET',$url);
 2770:     my $response=$ua->request($request);
 2771:     if (wantarray) {
 2772:         return ($response->content, $response);
 2773:     } else {
 2774:         return $response->content;
 2775:     }
 2776: }
 2777: 
 2778: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2779: 
 2780: sub allowuploaded {
 2781:     my ($srcurl,$url)=@_;
 2782:     $url=&clutter(&declutter($url));
 2783:     my $dir=$url;
 2784:     $dir=~s/\/[^\/]+$//;
 2785:     my %httpref=();
 2786:     my $httpurl=&hreflocation('',$url);
 2787:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2788:     &Apache::lonnet::appenv(\%httpref);
 2789: }
 2790: 
 2791: #
 2792: # Determine if the current user should be able to edit a particular resource,
 2793: # when viewing in course context.
 2794: # (a) When viewing resource used to determine if "Edit" item is included in 
 2795: #     Functions.
 2796: # (b) When displaying folder contents in course editor, used to determine if
 2797: #     "Edit" link will be displayed alongside resource.
 2798: #
 2799: #  input: six args -- filename (decluttered), course number, course domain,
 2800: #                   url, symb (if registered) and group (if this is a group
 2801: #                   item -- e.g., bulletin board, group page etc.).
 2802: #  output: array of five scalars -- 
 2803: #          $cfile -- url for file editing if editable on current server
 2804: #          $home -- homeserver of resource (i.e., for author if published,
 2805: #                                           or course if uploaded.).
 2806: #          $switchserver --  1 if server switch will be needed.
 2807: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2808: #          $forceview -- 1 if icon/link should be to go to view mode
 2809: #
 2810: 
 2811: sub can_edit_resource {
 2812:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2813:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2814: #
 2815: # For aboutme pages user can only edit his/her own.
 2816: #
 2817:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2818:         my ($sdom,$sname) = ($1,$2);
 2819:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2820:             $home = $env{'user.home'};
 2821:             $cfile = $resurl;
 2822:             if ($env{'form.forceedit'}) {
 2823:                 $forceview = 1;
 2824:             } else {
 2825:                 $forceedit = 1;
 2826:             }
 2827:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2828:         } else {
 2829:             return;
 2830:         }
 2831:     }
 2832: 
 2833:     if ($env{'request.course.id'}) {
 2834:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2835:         if ($group ne '') {
 2836: # if this is a group homepage or group bulletin board, check group privs
 2837:             my $allowed = 0;
 2838:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2839:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2840:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2841:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2842:                     $allowed = 1;
 2843:                 }
 2844:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2845:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2846:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2847:                     $allowed = 1;
 2848:                 }
 2849:             }
 2850:             if ($allowed) {
 2851:                 $home=&homeserver($cnum,$cdom);
 2852:                 if ($env{'form.forceedit'}) {
 2853:                     $forceview = 1;
 2854:                 } else {
 2855:                     $forceedit = 1;
 2856:                 }
 2857:                 $cfile = $resurl;
 2858:             } else {
 2859:                 return;
 2860:             }
 2861:         } else {
 2862:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2863:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2864:                     return;
 2865:                 }
 2866:             } elsif (!$crsedit) {
 2867: #
 2868: # No edit allowed where CC has switched to student role.
 2869: #
 2870:                 return;
 2871:             }
 2872:         }
 2873:     }
 2874: 
 2875:     if ($file ne '') {
 2876:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2877:             if (&is_course_upload($file,$cnum,$cdom)) {
 2878:                 $uploaded = 1;
 2879:                 $incourse = 1;
 2880:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2881:                     $cfile = &hreflocation('',$file);
 2882:                     if ($env{'form.forceedit'}) {
 2883:                         $forceview = 1;
 2884:                     } else {
 2885:                         $forceedit = 1;
 2886:                     }
 2887:                 }
 2888:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2889:                 $incourse = 1;
 2890:                 if ($env{'form.forceedit'}) {
 2891:                     $forceview = 1;
 2892:                 } else {
 2893:                     $forceedit = 1;
 2894:                 }
 2895:                 $cfile = $resurl;
 2896:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2897:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2898:                     $incourse = 1;
 2899:                     if ($env{'form.forceedit'}) {
 2900:                         $forceview = 1;
 2901:                     } else {
 2902:                         $forceedit = 1;
 2903:                     }
 2904:                     $cfile = $resurl;
 2905:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2906:                     $incourse = 1;
 2907:                     $cfile = $resurl.'/smpedit';
 2908:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2909:                     $incourse = 1;
 2910:                     if ($env{'form.forceedit'}) {
 2911:                         $forceview = 1;
 2912:                     } else {
 2913:                         $forceedit = 1;
 2914:                     }
 2915:                     $cfile = $resurl;
 2916:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2917:                     $incourse = 1;
 2918:                     if ($env{'form.forceedit'}) {
 2919:                         $forceview = 1;
 2920:                     } else {
 2921:                         $forceedit = 1;
 2922:                     }
 2923:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2924:                 }
 2925:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2926:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2927:                 if (&is_on_map($template)) { 
 2928:                     $incourse = 1;
 2929:                     $forceview = 1;
 2930:                     $cfile = $template;
 2931:                 }
 2932:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2933:                     $incourse = 1;
 2934:                     if ($env{'form.forceedit'}) {
 2935:                         $forceview = 1;
 2936:                     } else {
 2937:                         $forceedit = 1;
 2938:                     }
 2939:                     $cfile = $resurl;
 2940:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2941:                 $incourse = 1;
 2942:                 $forceview = 1;
 2943:                 if ($symb) {
 2944:                     my ($map,$id,$res)=&decode_symb($symb);
 2945:                     $env{'request.symb'} = $symb;
 2946:                     $cfile = &clutter($res);
 2947:                 } else {
 2948:                     $cfile = $env{'form.suppurl'};
 2949:                     $cfile =~ s{^http://}{};
 2950:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2951:                 }
 2952:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2953:                 if ($env{'form.forceedit'}) {
 2954:                     $forceview = 1;
 2955:                 } else {
 2956:                     $forceedit = 1;
 2957:                 }
 2958:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2959:             }
 2960:         }
 2961:         if ($uploaded || $incourse) {
 2962:             $home=&homeserver($cnum,$cdom);
 2963:         } elsif ($file !~ m{/$}) {
 2964:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2965:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2966:             # Check that the user has permission to edit this resource
 2967:             my $setpriv = 1;
 2968:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2969:             if (defined($cfudom)) {
 2970:                 $home=&homeserver($cfuname,$cfudom);
 2971:                 $cfile=$file;
 2972:             }
 2973:         }
 2974:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2975:             (($home ne '') && ($home ne 'no_host'))) {
 2976:             my @ids=&current_machine_ids();
 2977:             unless (grep(/^\Q$home\E$/,@ids)) {
 2978:                 $switchserver=1;
 2979:             }
 2980:         }
 2981:     }
 2982:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2983: }
 2984: 
 2985: sub is_course_upload {
 2986:     my ($file,$cnum,$cdom) = @_;
 2987:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2988:     $uploadpath =~ s{^\/}{};
 2989:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2990:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2991:         return 1;
 2992:     }
 2993:     return;
 2994: }
 2995: 
 2996: sub in_course {
 2997:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2998:     if ($hideprivileged) {
 2999:         my $skipuser;
 3000:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3001:         my @possdoms = ($cdom);  
 3002:         if ($coursehash{'checkforpriv'}) { 
 3003:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3004:         }
 3005:         if (&privileged($uname,$udom,\@possdoms)) {
 3006:             $skipuser = 1;
 3007:             if ($coursehash{'nothideprivileged'}) {
 3008:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3009:                     my $user;
 3010:                     if ($item =~ /:/) {
 3011:                         $user = $item;
 3012:                     } else {
 3013:                         $user = join(':',split(/[\@]/,$item));
 3014:                     }
 3015:                     if ($user eq $uname.':'.$udom) {
 3016:                         undef($skipuser);
 3017:                         last;
 3018:                     }
 3019:                 }
 3020:             }
 3021:             if ($skipuser) {
 3022:                 return 0;
 3023:             }
 3024:         }
 3025:     }
 3026:     $type ||= 'any';
 3027:     if (!defined($cdom) || !defined($cnum)) {
 3028:         my $cid  = $env{'request.course.id'};
 3029:         $cdom = $env{'course.'.$cid.'.domain'};
 3030:         $cnum = $env{'course.'.$cid.'.num'};
 3031:     }
 3032:     my $typesref;
 3033:     if (($type eq 'any') || ($type eq 'all')) {
 3034:         $typesref = ['active','previous','future'];
 3035:     } elsif ($type eq 'previous' || $type eq 'future') {
 3036:         $typesref = [$type];
 3037:     }
 3038:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3039:                               $typesref,undef,[$cdom]);
 3040:     my ($tmp) = keys(%roles);
 3041:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3042:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3043:     if (@course_roles > 0) {
 3044:         return 1;
 3045:     }
 3046:     return 0;
 3047: }
 3048: 
 3049: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3050: # input: action, courseID, current domain, intended
 3051: #        path to file, source of file, instruction to parse file for objects,
 3052: #        ref to hash for embedded objects,
 3053: #        ref to hash for codebase of java objects.
 3054: #        reference to scalar to accommodate mime type determined
 3055: #          from File::MMagic if $parser = parse.
 3056: #
 3057: # output: url to file (if action was uploaddoc), 
 3058: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3059: #
 3060: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3061: # course.
 3062: #
 3063: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3064: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3065: #          course's home server.
 3066: #
 3067: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3068: #          be copied from $source (current location) to 
 3069: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3070: #         and will then be copied to
 3071: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3072: #         course's home server.
 3073: #
 3074: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3075: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3076: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3077: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3078: #         in course's home server.
 3079: #
 3080: 
 3081: sub process_coursefile {
 3082:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3083:         $mimetype)=@_;
 3084:     my $fetchresult;
 3085:     my $home=&homeserver($docuname,$docudom);
 3086:     if ($action eq 'propagate') {
 3087:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3088: 			     $home);
 3089:     } else {
 3090:         my $fpath = '';
 3091:         my $fname = $file;
 3092:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3093:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3094:         my $filepath = &build_filepath($fpath);
 3095:         if ($action eq 'copy') {
 3096:             if ($source eq '') {
 3097:                 $fetchresult = 'no source file';
 3098:                 return $fetchresult;
 3099:             } else {
 3100:                 my $destination = $filepath.'/'.$fname;
 3101:                 rename($source,$destination);
 3102:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3103:                                  $home);
 3104:             }
 3105:         } elsif ($action eq 'uploaddoc') {
 3106:             open(my $fh,'>'.$filepath.'/'.$fname);
 3107:             print $fh $env{'form.'.$source};
 3108:             close($fh);
 3109:             if ($parser eq 'parse') {
 3110:                 my $mm = new File::MMagic;
 3111:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3112:                 if ($type eq 'text/html') {
 3113:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3114:                     unless ($parse_result eq 'ok') {
 3115:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3116:                     }
 3117:                 }
 3118:                 if (ref($mimetype)) {
 3119:                     $$mimetype = $type;
 3120:                 } 
 3121:             }
 3122:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3123:                                  $home);
 3124:             if ($fetchresult eq 'ok') {
 3125:                 return '/uploaded/'.$fpath.'/'.$fname;
 3126:             } else {
 3127:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3128:                         ' to host '.$home.': '.$fetchresult);
 3129:                 return '/adm/notfound.html';
 3130:             }
 3131:         }
 3132:     }
 3133:     unless ( $fetchresult eq 'ok') {
 3134:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3135:              ' to host '.$home.': '.$fetchresult);
 3136:     }
 3137:     return $fetchresult;
 3138: }
 3139: 
 3140: sub build_filepath {
 3141:     my ($fpath) = @_;
 3142:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3143:     unless ($fpath eq '') {
 3144:         my @parts=split('/',$fpath);
 3145:         foreach my $part (@parts) {
 3146:             $filepath.= '/'.$part;
 3147:             if ((-e $filepath)!=1) {
 3148:                 mkdir($filepath,0777);
 3149:             }
 3150:         }
 3151:     }
 3152:     return $filepath;
 3153: }
 3154: 
 3155: sub store_edited_file {
 3156:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3157:     my $file = $primary_url;
 3158:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3159:     my $fpath = '';
 3160:     my $fname = $file;
 3161:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3162:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3163:     my $filepath = &build_filepath($fpath);
 3164:     open(my $fh,'>'.$filepath.'/'.$fname);
 3165:     print $fh $content;
 3166:     close($fh);
 3167:     my $home=&homeserver($docuname,$docudom);
 3168:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3169: 			  $home);
 3170:     if ($$fetchresult eq 'ok') {
 3171:         return '/uploaded/'.$fpath.'/'.$fname;
 3172:     } else {
 3173:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3174: 		 ' to host '.$home.': '.$$fetchresult);
 3175:         return '/adm/notfound.html';
 3176:     }
 3177: }
 3178: 
 3179: sub clean_filename {
 3180:     my ($fname,$args)=@_;
 3181: # Replace Windows backslashes by forward slashes
 3182:     $fname=~s/\\/\//g;
 3183:     if (!$args->{'keep_path'}) {
 3184:         # Get rid of everything but the actual filename
 3185: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3186:     }
 3187: # Replace spaces by underscores
 3188:     $fname=~s/\s+/\_/g;
 3189: # Replace all other weird characters by nothing
 3190:     $fname=~s{[^/\w\.\-]}{}g;
 3191: # Replace all .\d. sequences with _\d. so they no longer look like version
 3192: # numbers
 3193:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3194:     return $fname;
 3195: }
 3196: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3197: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3198: # image with the same aspect ratio as the original, but with dimensions which do 
 3199: # not exceed $resizewidth and $resizeheight.
 3200:  
 3201: sub resizeImage {
 3202:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3203:     my $ima = Image::Magick->new;
 3204:     my $resized;
 3205:     if (-e $img_path) {
 3206:         $ima->Read($img_path);
 3207:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3208:             my $width = $ima->Get('width');
 3209:             my $height = $ima->Get('height');
 3210:             if ($width > $resizewidth) {
 3211: 	        my $factor = $width/$resizewidth;
 3212:                 my $newheight = $height/$factor;
 3213:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3214:                 $resized = 1;
 3215:             }
 3216:         }
 3217:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3218:             my $width = $ima->Get('width');
 3219:             my $height = $ima->Get('height');
 3220:             if ($height > $resizeheight) {
 3221:                 my $factor = $height/$resizeheight;
 3222:                 my $newwidth = $width/$factor;
 3223:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3224:                 $resized = 1;
 3225:             }
 3226:         }
 3227:         if ($resized) {
 3228:             $ima->Write($img_path);
 3229:         }
 3230:     }
 3231:     return;
 3232: }
 3233: 
 3234: # --------------- Take an uploaded file and put it into the userfiles directory
 3235: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3236: #                    the desired filename is in $env{"form.$formname.filename"}
 3237: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3238: #                                    canceloverwrite, or ''. 
 3239: #                   if 'coursedoc': upload to the current course
 3240: #                   if 'existingfile': write file to tmp/overwrites directory 
 3241: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3242: #                   $context is passed as argument to &finishuserfileupload
 3243: #        $subdir - directory in userfile to store the file into
 3244: #        $parser - instruction to parse file for objects ($parser = parse)    
 3245: #        $allfiles - reference to hash for embedded objects
 3246: #        $codebase - reference to hash for codebase of java objects
 3247: #        $desuname - username for permanent storage of uploaded file
 3248: #        $dsetudom - domain for permanaent storage of uploaded file
 3249: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3250: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3251: #        $resizewidth - width (pixels) to which to resize uploaded image
 3252: #        $resizeheight - height (pixels) to which to resize uploaded image
 3253: #        $mimetype - reference to scalar to accommodate mime type determined
 3254: #                    from File::MMagic.
 3255: # 
 3256: # output: url of file in userspace, or error: <message> 
 3257: #             or /adm/notfound.html if failure to upload occurse
 3258: 
 3259: sub userfileupload {
 3260:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3261:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3262:     if (!defined($subdir)) { $subdir='unknown'; }
 3263:     my $fname=$env{'form.'.$formname.'.filename'};
 3264:     $fname=&clean_filename($fname);
 3265:     # See if there is anything left
 3266:     unless ($fname) { return 'error: no uploaded file'; }
 3267:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3268:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3269:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3270:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3271:         my $now = time;
 3272:         my $filepath;
 3273:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3274:              $filepath = 'tmp/helprequests/'.$now;
 3275:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3276:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3277:                          '_'.$env{'user.domain'}.'/pending';
 3278:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3279:             my ($docuname,$docudom);
 3280:             if ($destudom) {
 3281:                 $docudom = $destudom;
 3282:             } else {
 3283:                 $docudom = $env{'user.domain'};
 3284:             }
 3285:             if ($destuname) {
 3286:                 $docuname = $destuname;
 3287:             } else {
 3288:                 $docuname = $env{'user.name'};
 3289:             }
 3290:             if (exists($env{'form.group'})) {
 3291:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3292:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3293:             }
 3294:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3295:             if ($context eq 'canceloverwrite') {
 3296:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3297:                 if (-e  $tempfile) {
 3298:                     my @info = stat($tempfile);
 3299:                     if ($info[9] eq $env{'form.timestamp'}) {
 3300:                         unlink($tempfile);
 3301:                     }
 3302:                 }
 3303:                 return;
 3304:             }
 3305:         }
 3306:         # Create the directory if not present
 3307:         my @parts=split(/\//,$filepath);
 3308:         my $fullpath = $perlvar{'lonDaemons'};
 3309:         for (my $i=0;$i<@parts;$i++) {
 3310:             $fullpath .= '/'.$parts[$i];
 3311:             if ((-e $fullpath)!=1) {
 3312:                 mkdir($fullpath,0777);
 3313:             }
 3314:         }
 3315:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3316:         print $fh $env{'form.'.$formname};
 3317:         close($fh);
 3318:         if ($context eq 'existingfile') {
 3319:             my @info = stat($fullpath.'/'.$fname);
 3320:             return ($fullpath.'/'.$fname,$info[9]);
 3321:         } else {
 3322:             return $fullpath.'/'.$fname;
 3323:         }
 3324:     }
 3325:     if ($subdir eq 'scantron') {
 3326:         $fname = 'scantron_orig_'.$fname;
 3327:     } else {
 3328:         $fname="$subdir/$fname";
 3329:     }
 3330:     if ($context eq 'coursedoc') {
 3331: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3332: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3333:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3334:             return &finishuserfileupload($docuname,$docudom,
 3335: 					 $formname,$fname,$parser,$allfiles,
 3336: 					 $codebase,$thumbwidth,$thumbheight,
 3337:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3338:         } else {
 3339:             if ($env{'form.folder'}) {
 3340:                 $fname=$env{'form.folder'}.'/'.$fname;
 3341:             }
 3342:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3343: 				       $fname,$formname,$parser,
 3344: 				       $allfiles,$codebase,$mimetype);
 3345:         }
 3346:     } elsif (defined($destuname)) {
 3347:         my $docuname=$destuname;
 3348:         my $docudom=$destudom;
 3349: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3350: 				     $parser,$allfiles,$codebase,
 3351:                                      $thumbwidth,$thumbheight,
 3352:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3353:     } else {
 3354:         my $docuname=$env{'user.name'};
 3355:         my $docudom=$env{'user.domain'};
 3356:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3357:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3358:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3359:         }
 3360: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3361: 				     $parser,$allfiles,$codebase,
 3362:                                      $thumbwidth,$thumbheight,
 3363:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3364:     }
 3365: }
 3366: 
 3367: sub finishuserfileupload {
 3368:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3369:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3370:     my $path=$docudom.'/'.$docuname.'/';
 3371:     my $filepath=$perlvar{'lonDocRoot'};
 3372:   
 3373:     my ($fnamepath,$file,$fetchthumb);
 3374:     $file=$fname;
 3375:     if ($fname=~m|/|) {
 3376:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3377: 	$path.=$fnamepath.'/';
 3378:     }
 3379:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3380:     my $count;
 3381:     for ($count=4;$count<=$#parts;$count++) {
 3382:         $filepath.="/$parts[$count]";
 3383:         if ((-e $filepath)!=1) {
 3384: 	    mkdir($filepath,0777);
 3385:         }
 3386:     }
 3387: 
 3388: # Save the file
 3389:     {
 3390: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3391: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3392: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3393: 	    return '/adm/notfound.html';
 3394: 	}
 3395:         if ($context eq 'overwrite') {
 3396:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3397:             my $target = $filepath.'/'.$file;
 3398:             if (-e $source) {
 3399:                 my @info = stat($source);
 3400:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3401:                     unless (&File::Copy::move($source,$target)) {
 3402:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3403:                         return "Moving from $source failed";
 3404:                     }
 3405:                 } else {
 3406:                     return "Temporary file: $source had unexpected date/time for last modification";
 3407:                 }
 3408:             } else {
 3409:                 return "Temporary file: $source missing";
 3410:             }
 3411:         } elsif (!print FH ($env{'form.'.$formname})) {
 3412: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3413: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3414: 	    return '/adm/notfound.html';
 3415: 	}
 3416: 	close(FH);
 3417:         if ($resizewidth && $resizeheight) {
 3418:             my $mm = new File::MMagic;
 3419:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3420:             if ($mime_type =~ m{^image/}) {
 3421: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3422:             }  
 3423: 	}
 3424:     }
 3425:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3426:         if (ref($mimetype)) {
 3427:             if ($$mimetype eq '') {
 3428:                 my $mm = new File::MMagic;
 3429:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3430:                 $$mimetype = $type;
 3431:             }
 3432:         }
 3433:     }
 3434:     if ($parser eq 'parse') {
 3435:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3436:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3437:                                                        $allfiles,$codebase);
 3438:             unless ($parse_result eq 'ok') {
 3439:                 &logthis('Failed to parse '.$filepath.$file.
 3440: 	   	         ' for embedded media: '.$parse_result); 
 3441:             }
 3442:         }
 3443:     }
 3444:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3445:         my $input = $filepath.'/'.$file;
 3446:         my $output = $filepath.'/'.'tn-'.$file;
 3447:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3448:         system("convert -sample $thumbsize $input $output");
 3449:         if (-e $filepath.'/'.'tn-'.$file) {
 3450:             $fetchthumb  = 1; 
 3451:         }
 3452:     }
 3453:  
 3454: # Notify homeserver to grep it
 3455: #
 3456:     my $docuhome=&homeserver($docuname,$docudom);	
 3457:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3458:     if ($fetchresult eq 'ok') {
 3459:         if ($fetchthumb) {
 3460:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3461:             if ($thumbresult ne 'ok') {
 3462:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3463:                          $docuhome.': '.$thumbresult);
 3464:             }
 3465:         }
 3466: #
 3467: # Return the URL to it
 3468:         return '/uploaded/'.$path.$file;
 3469:     } else {
 3470:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3471: 		 ': '.$fetchresult);
 3472:         return '/adm/notfound.html';
 3473:     }
 3474: }
 3475: 
 3476: sub extract_embedded_items {
 3477:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3478:     my @state = ();
 3479:     my (%lastids,%related,%shockwave,%flashvars);
 3480:     my %javafiles = (
 3481:                       codebase => '',
 3482:                       code => '',
 3483:                       archive => ''
 3484:                     );
 3485:     my %mediafiles = (
 3486:                       src => '',
 3487:                       movie => '',
 3488:                      );
 3489:     my $p;
 3490:     if ($content) {
 3491:         $p = HTML::LCParser->new($content);
 3492:     } else {
 3493:         $p = HTML::LCParser->new($fullpath);
 3494:     }
 3495:     while (my $t=$p->get_token()) {
 3496: 	if ($t->[0] eq 'S') {
 3497: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3498: 	    push(@state, $tagname);
 3499:             if (lc($tagname) eq 'allow') {
 3500:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3501:             }
 3502: 	    if (lc($tagname) eq 'img') {
 3503: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3504: 	    }
 3505: 	    if (lc($tagname) eq 'a') {
 3506:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3507:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3508:                 }
 3509: 	    }
 3510:             if (lc($tagname) eq 'script') {
 3511:                 my $src;
 3512:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3513:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3514:                 } else {
 3515:                     if ($attr->{'src'} ne '') {
 3516:                         $src = $attr->{'src'};
 3517:                         &add_filetype($allfiles,$src,'src');
 3518:                     }
 3519:                 }
 3520:                 my $text = $p->get_trimmed_text();
 3521:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3522:                     my @swfargs = split(/,/,$1);
 3523:                     foreach my $item (@swfargs) {
 3524:                         $item =~ s/["']//g;
 3525:                         $item =~ s/^\s+//;
 3526:                         $item =~ s/\s+$//;
 3527:                     }
 3528:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3529:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3530:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3531:                         } else {
 3532:                             $related{$swfargs[0]} = [$swfargs[2]];
 3533:                         }
 3534:                     }
 3535:                 }
 3536:             }
 3537:             if (lc($tagname) eq 'link') {
 3538:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3539:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3540:                 }
 3541:             }
 3542: 	    if (lc($tagname) eq 'object' ||
 3543: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3544: 		foreach my $item (keys(%javafiles)) {
 3545: 		    $javafiles{$item} = '';
 3546: 		}
 3547:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3548:                     $lastids{lc($tagname)} = $attr->{'id'};
 3549:                 }
 3550: 	    }
 3551: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3552: 		my $name = lc($attr->{'name'});
 3553: 		foreach my $item (keys(%javafiles)) {
 3554: 		    if ($name eq $item) {
 3555: 			$javafiles{$item} = $attr->{'value'};
 3556: 			last;
 3557: 		    }
 3558: 		}
 3559:                 my $pathfrom;
 3560: 		foreach my $item (keys(%mediafiles)) {
 3561: 		    if ($name eq $item) {
 3562:                         $pathfrom = $attr->{'value'};
 3563:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3564: 			&add_filetype($allfiles,$pathfrom,$name);
 3565: 			last;
 3566: 		    }
 3567: 		}
 3568:                 if ($name eq 'flashvars') {
 3569:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3570:                 }
 3571:                 if ($pathfrom ne '') {
 3572:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3573:                                          $pathfrom);
 3574:                 }
 3575: 	    }
 3576: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3577: 		foreach my $item (keys(%javafiles)) {
 3578: 		    if ($attr->{$item}) {
 3579: 			$javafiles{$item} = $attr->{$item};
 3580: 			last;
 3581: 		    }
 3582: 		}
 3583: 		foreach my $item (keys(%mediafiles)) {
 3584: 		    if ($attr->{$item}) {
 3585: 			&add_filetype($allfiles,$attr->{$item},$item);
 3586: 			last;
 3587: 		    }
 3588: 		}
 3589:                 if (lc($tagname) eq 'embed') {
 3590:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3591:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3592:                                              $attr->{'src'});
 3593:                     }
 3594:                 }
 3595: 	    }
 3596:             if (lc($tagname) eq 'iframe') {
 3597:                 my $src = $attr->{'src'} ;
 3598:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3599:                     &add_filetype($allfiles,$src,'src');
 3600:                 } elsif ($src =~ m{^/}) {
 3601:                     if ($env{'request.course.id'}) {
 3602:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3603:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3604:                         my $url = &hreflocation('',$fullpath);
 3605:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3606:                             my $relpath = $1;
 3607:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3608:                                 &add_filetype($allfiles,$1,'src');
 3609:                             }
 3610:                         }
 3611:                     }
 3612:                 }
 3613:             }
 3614:             if ($t->[4] =~ m{/>$}) {
 3615:                 pop(@state);
 3616:             }
 3617: 	} elsif ($t->[0] eq 'E') {
 3618: 	    my ($tagname) = ($t->[1]);
 3619: 	    if ($javafiles{'codebase'} ne '') {
 3620: 		$javafiles{'codebase'} .= '/';
 3621: 	    }  
 3622: 	    if (lc($tagname) eq 'applet' ||
 3623: 		lc($tagname) eq 'object' ||
 3624: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3625: 		) {
 3626: 		foreach my $item (keys(%javafiles)) {
 3627: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3628: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3629: 			&add_filetype($allfiles,$file,$item);
 3630: 		    }
 3631: 		}
 3632: 	    } 
 3633: 	    pop @state;
 3634: 	}
 3635:     }
 3636:     foreach my $id (sort(keys(%flashvars))) {
 3637:         if ($shockwave{$id} ne '') {
 3638:             my @pairs = split(/\&/,$flashvars{$id});
 3639:             foreach my $pair (@pairs) {
 3640:                 my ($key,$value) = split(/\=/,$pair);
 3641:                 if ($key eq 'thumb') {
 3642:                     &add_filetype($allfiles,$value,$key);
 3643:                 } elsif ($key eq 'content') {
 3644:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3645:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3646:                     if ($ext ne '') {
 3647:                         &add_filetype($allfiles,$path.$value,$ext);
 3648:                     }
 3649:                 }
 3650:             }
 3651:         }
 3652:     }
 3653:     return 'ok';
 3654: }
 3655: 
 3656: sub add_filetype {
 3657:     my ($allfiles,$file,$type)=@_;
 3658:     if (exists($allfiles->{$file})) {
 3659: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3660: 	    push(@{$allfiles->{$file}}, &escape($type));
 3661: 	}
 3662:     } else {
 3663: 	@{$allfiles->{$file}} = (&escape($type));
 3664:     }
 3665: }
 3666: 
 3667: sub embedded_dependency {
 3668:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3669:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3670:         if (($identifier ne '') &&
 3671:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3672:             ($pathfrom ne '')) {
 3673:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3674:             foreach my $dep (@{$related->{$identifier}}) {
 3675:                 &add_filetype($allfiles,$path.$dep,'object');
 3676:             }
 3677:         }
 3678:     }
 3679:     return;
 3680: }
 3681: 
 3682: sub removeuploadedurl {
 3683:     my ($url)=@_;	
 3684:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3685:     return &removeuserfile($uname,$udom,$fname);
 3686: }
 3687: 
 3688: sub removeuserfile {
 3689:     my ($docuname,$docudom,$fname)=@_;
 3690:     my $home=&homeserver($docuname,$docudom);    
 3691:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3692:     if ($result eq 'ok') {	
 3693:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3694:             my $metafile = $fname.'.meta';
 3695:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3696: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3697:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3698:             my $sqlresult = 
 3699:                 &update_portfolio_table($docuname,$docudom,$file,
 3700:                                         'portfolio_metadata',$group,
 3701:                                         'delete');
 3702:         }
 3703:     }
 3704:     return $result;
 3705: }
 3706: 
 3707: sub mkdiruserfile {
 3708:     my ($docuname,$docudom,$dir)=@_;
 3709:     my $home=&homeserver($docuname,$docudom);
 3710:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3711: }
 3712: 
 3713: sub renameuserfile {
 3714:     my ($docuname,$docudom,$old,$new)=@_;
 3715:     my $home=&homeserver($docuname,$docudom);
 3716:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3717:                         &escape("$old").':'.&escape("$new"),$home);
 3718:     if ($result eq 'ok') {
 3719:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3720:             my $oldmeta = $old.'.meta';
 3721:             my $newmeta = $new.'.meta';
 3722:             my $metaresult = 
 3723:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3724: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3725:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3726:             my $sqlresult = 
 3727:                 &update_portfolio_table($docuname,$docudom,$file,
 3728:                                         'portfolio_metadata',$group,
 3729:                                         'delete');
 3730:         }
 3731:     }
 3732:     return $result;
 3733: }
 3734: 
 3735: # ------------------------------------------------------------------------- Log
 3736: 
 3737: sub log {
 3738:     my ($dom,$nam,$hom,$what)=@_;
 3739:     return critical("log:$dom:$nam:$what",$hom);
 3740: }
 3741: 
 3742: # ------------------------------------------------------------------ Course Log
 3743: #
 3744: # This routine flushes several buffers of non-mission-critical nature
 3745: #
 3746: 
 3747: sub flushcourselogs {
 3748:     &logthis('Flushing log buffers');
 3749: #
 3750: # course logs
 3751: # This is a log of all transactions in a course, which can be used
 3752: # for data mining purposes
 3753: #
 3754: # It also collects the courseid database, which lists last transaction
 3755: # times and course titles for all courseids
 3756: #
 3757:     my %courseidbuffer=();
 3758:     foreach my $crsid (keys(%courselogs)) {
 3759:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3760: 		          &escape($courselogs{$crsid}),
 3761: 		          $coursehombuf{$crsid}) eq 'ok') {
 3762: 	    delete $courselogs{$crsid};
 3763:         } else {
 3764:             &logthis('Failed to flush log buffer for '.$crsid);
 3765:             if (length($courselogs{$crsid})>40000) {
 3766:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3767:                         " exceeded maximum size, deleting.</font>");
 3768:                delete $courselogs{$crsid};
 3769:             }
 3770:         }
 3771:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3772:             'description' => $coursedescrbuf{$crsid},
 3773:             'inst_code'    => $courseinstcodebuf{$crsid},
 3774:             'type'        => $coursetypebuf{$crsid},
 3775:             'owner'       => $courseownerbuf{$crsid},
 3776:         };
 3777:     }
 3778: #
 3779: # Write course id database (reverse lookup) to homeserver of courses 
 3780: # Is used in pickcourse
 3781: #
 3782:     foreach my $crs_home (keys(%courseidbuffer)) {
 3783:         my $response = &courseidput(&host_domain($crs_home),
 3784:                                     $courseidbuffer{$crs_home},
 3785:                                     $crs_home,'timeonly');
 3786:     }
 3787: #
 3788: # File accesses
 3789: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3790: #
 3791:     foreach my $entry (keys(%accesshash)) {
 3792:         if ($entry =~ /___count$/) {
 3793:             my ($dom,$name);
 3794:             ($dom,$name,undef)=
 3795: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3796:             if (! defined($dom) || $dom eq '' || 
 3797:                 ! defined($name) || $name eq '') {
 3798:                 my $cid = $env{'request.course.id'};
 3799:                 $dom  = $env{'request.'.$cid.'.domain'};
 3800:                 $name = $env{'request.'.$cid.'.num'};
 3801:             }
 3802:             my $value = $accesshash{$entry};
 3803:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3804:             my %temphash=($url => $value);
 3805:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3806:             if ($result eq 'ok') {
 3807:                 delete $accesshash{$entry};
 3808:             }
 3809:         } else {
 3810:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3811:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3812:             my %temphash=($entry => $accesshash{$entry});
 3813:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3814:                 delete $accesshash{$entry};
 3815:             }
 3816:         }
 3817:     }
 3818: #
 3819: # Roles
 3820: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3821: #
 3822:     foreach my $entry (keys(%userrolehash)) {
 3823:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3824: 	    split(/\:/,$entry);
 3825:         if (&Apache::lonnet::put('nohist_userroles',
 3826:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3827:                 $rudom,$runame) eq 'ok') {
 3828: 	    delete $userrolehash{$entry};
 3829:         }
 3830:     }
 3831: #
 3832: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3833: #
 3834:     my %domrolebuffer = ();
 3835:     foreach my $entry (keys(%domainrolehash)) {
 3836:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3837:         if ($domrolebuffer{$rudom}) {
 3838:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3839:                       '='.&escape($domainrolehash{$entry});
 3840:         } else {
 3841:             $domrolebuffer{$rudom}.=&escape($entry).
 3842:                       '='.&escape($domainrolehash{$entry});
 3843:         }
 3844:         delete $domainrolehash{$entry};
 3845:     }
 3846:     foreach my $dom (keys(%domrolebuffer)) {
 3847: 	my %servers = &get_servers($dom,'library');
 3848: 	foreach my $tryserver (keys(%servers)) {
 3849: 	    unless (&reply('domroleput:'.$dom.':'.
 3850: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3851: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3852: 	    }
 3853:         }
 3854:     }
 3855:     $dumpcount++;
 3856: }
 3857: 
 3858: sub courselog {
 3859:     my $what=shift;
 3860:     $what=time.':'.$what;
 3861:     unless ($env{'request.course.id'}) { return ''; }
 3862:     $coursedombuf{$env{'request.course.id'}}=
 3863:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3864:     $coursenumbuf{$env{'request.course.id'}}=
 3865:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3866:     $coursehombuf{$env{'request.course.id'}}=
 3867:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3868:     $coursedescrbuf{$env{'request.course.id'}}=
 3869:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3870:     $courseinstcodebuf{$env{'request.course.id'}}=
 3871:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3872:     $courseownerbuf{$env{'request.course.id'}}=
 3873:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3874:     $coursetypebuf{$env{'request.course.id'}}=
 3875:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3876:     if (defined $courselogs{$env{'request.course.id'}}) {
 3877: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3878:     } else {
 3879: 	$courselogs{$env{'request.course.id'}}.=$what;
 3880:     }
 3881:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3882: 	&flushcourselogs();
 3883:     }
 3884: }
 3885: 
 3886: sub courseacclog {
 3887:     my $fnsymb=shift;
 3888:     unless ($env{'request.course.id'}) { return ''; }
 3889:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3890:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3891:         $what.=':POST';
 3892:         # FIXME: Probably ought to escape things....
 3893: 	foreach my $key (keys(%env)) {
 3894:             if ($key=~/^form\.(.*)/) {
 3895:                 my $formitem = $1;
 3896:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3897:                     $what.=':'.$formitem.'='.$env{$key};
 3898:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3899:                     $what.=':'.$formitem.'='.$env{$key};
 3900:                 }
 3901:             }
 3902:         }
 3903:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3904:         # FIXME: We should not be depending on a form parameter that someone
 3905:         # editing lonsearchcat.pm might change in the future.
 3906:         if ($env{'form.phase'} eq 'course_search') {
 3907:             $what.= ':POST';
 3908:             # FIXME: Probably ought to escape things....
 3909:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3910:                                  'crsdiscuss') {
 3911:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3912:             }
 3913:         }
 3914:     }
 3915:     &courselog($what);
 3916: }
 3917: 
 3918: sub countacc {
 3919:     my $url=&declutter(shift);
 3920:     return if (! defined($url) || $url eq '');
 3921:     unless ($env{'request.course.id'}) { return ''; }
 3922: #
 3923: # Mark that this url was used in this course
 3924: #
 3925:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3926: #
 3927: # Increase the access count for this resource in this child process
 3928: #
 3929:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3930:     $accesshash{$key}++;
 3931: }
 3932: 
 3933: sub linklog {
 3934:     my ($from,$to)=@_;
 3935:     $from=&declutter($from);
 3936:     $to=&declutter($to);
 3937:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3938:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3939: }
 3940: 
 3941: sub statslog {
 3942:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3943:     if ($users<2) { return; }
 3944:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3945:             'course'       => $env{'request.course.id'},
 3946:             'sections'     => '"all"',
 3947:             'num_students' => $users,
 3948:             'part'         => $part,
 3949:             'symb'         => $symb,
 3950:             'mean_tries'   => $av_attempts,
 3951:             'deg_of_diff'  => $degdiff});
 3952:     foreach my $key (keys(%dynstore)) {
 3953:         $accesshash{$key}=$dynstore{$key};
 3954:     }
 3955: }
 3956:   
 3957: sub userrolelog {
 3958:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3959:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3960:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3961:        $userrolehash
 3962:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3963:                     =$tend.':'.$tstart;
 3964:     }
 3965:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3966:        $userrolehash
 3967:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3968:                     =$tend.':'.$tstart;
 3969:     }
 3970:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3971:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3972:        $domainrolehash
 3973:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3974:                     = $tend.':'.$tstart;
 3975:     }
 3976: }
 3977: 
 3978: sub courserolelog {
 3979:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3980:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3981:         my $cdom = $1;
 3982:         my $cnum = $2;
 3983:         my $sec = $3;
 3984:         my $namespace = 'rolelog';
 3985:         my %storehash = (
 3986:                            role    => $trole,
 3987:                            start   => $tstart,
 3988:                            end     => $tend,
 3989:                            selfenroll => $selfenroll,
 3990:                            context    => $context,
 3991:                         );
 3992:         if ($trole eq 'gr') {
 3993:             $namespace = 'groupslog';
 3994:             $storehash{'group'} = $sec;
 3995:         } else {
 3996:             $storehash{'section'} = $sec;
 3997:         }
 3998:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3999:                    $domain,$cnum,$cdom);
 4000:         if (($trole ne 'st') || ($sec ne '')) {
 4001:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4002:         }
 4003:     }
 4004:     return;
 4005: }
 4006: 
 4007: sub domainrolelog {
 4008:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4009:     if ($area =~ m{^/($match_domain)/$}) {
 4010:         my $cdom = $1;
 4011:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4012:         my $namespace = 'rolelog';
 4013:         my %storehash = (
 4014:                            role    => $trole,
 4015:                            start   => $tstart,
 4016:                            end     => $tend,
 4017:                            context => $context,
 4018:                         );
 4019:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4020:                    $domain,$domconfiguser,$cdom);
 4021:     }
 4022:     return;
 4023: 
 4024: }
 4025: 
 4026: sub coauthorrolelog {
 4027:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4028:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4029:         my $audom = $1;
 4030:         my $auname = $2;
 4031:         my $namespace = 'rolelog';
 4032:         my %storehash = (
 4033:                            role    => $trole,
 4034:                            start   => $tstart,
 4035:                            end     => $tend,
 4036:                            context => $context,
 4037:                         );
 4038:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4039:                    $domain,$auname,$audom);
 4040:     }
 4041:     return;
 4042: }
 4043: 
 4044: sub get_course_adv_roles {
 4045:     my ($cid,$codes) = @_;
 4046:     $cid=$env{'request.course.id'} unless (defined($cid));
 4047:     my %coursehash=&coursedescription($cid);
 4048:     my $crstype = &Apache::loncommon::course_type($cid);
 4049:     my %nothide=();
 4050:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4051:         if ($user !~ /:/) {
 4052: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4053:         } else {
 4054:             $nothide{$user}=1;
 4055:         }
 4056:     }
 4057:     my @possdoms = ($coursehash{'domain'});
 4058:     if ($coursehash{'checkforpriv'}) {
 4059:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4060:     }
 4061:     my %returnhash=();
 4062:     my %dumphash=
 4063:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4064:     my $now=time;
 4065:     my %privileged;
 4066:     foreach my $entry (keys(%dumphash)) {
 4067: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4068:         if (($tstart) && ($tstart<0)) { next; }
 4069:         if (($tend) && ($tend<$now)) { next; }
 4070:         if (($tstart) && ($now<$tstart)) { next; }
 4071:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4072: 	if ($username eq '' || $domain eq '') { next; }
 4073:         if ((&privileged($username,$domain,\@possdoms)) &&
 4074:             (!$nothide{$username.':'.$domain})) { next; }
 4075: 	if ($role eq 'cr') { next; }
 4076:         if ($codes) {
 4077:             if ($section) { $role .= ':'.$section; }
 4078:             if ($returnhash{$role}) {
 4079:                 $returnhash{$role}.=','.$username.':'.$domain;
 4080:             } else {
 4081:                 $returnhash{$role}=$username.':'.$domain;
 4082:             }
 4083:         } else {
 4084:             my $key=&plaintext($role,$crstype);
 4085:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4086:             if ($returnhash{$key}) {
 4087: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4088:             } else {
 4089:                 $returnhash{$key}=$username.':'.$domain;
 4090:             }
 4091:         }
 4092:     }
 4093:     return %returnhash;
 4094: }
 4095: 
 4096: sub get_my_roles {
 4097:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4098:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4099:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4100:     my (%dumphash,%nothide);
 4101:     if ($context eq 'userroles') {
 4102:         %dumphash = &dump('roles',$udom,$uname);
 4103:     } else {
 4104:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4105:         if ($hidepriv) {
 4106:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4107:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4108:                 if ($user !~ /:/) {
 4109:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4110:                 } else {
 4111:                     $nothide{$user} = 1;
 4112:                 }
 4113:             }
 4114:         }
 4115:     }
 4116:     my %returnhash=();
 4117:     my $now=time;
 4118:     my %privileged;
 4119:     foreach my $entry (keys(%dumphash)) {
 4120:         my ($role,$tend,$tstart);
 4121:         if ($context eq 'userroles') {
 4122:             next if ($entry =~ /^rolesdef/);
 4123: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4124:         } else {
 4125:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4126:         }
 4127:         if (($tstart) && ($tstart<0)) { next; }
 4128:         my $status = 'active';
 4129:         if (($tend) && ($tend<=$now)) {
 4130:             $status = 'previous';
 4131:         } 
 4132:         if (($tstart) && ($now<$tstart)) {
 4133:             $status = 'future';
 4134:         }
 4135:         if (ref($types) eq 'ARRAY') {
 4136:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4137:                 next;
 4138:             } 
 4139:         } else {
 4140:             if ($status ne 'active') {
 4141:                 next;
 4142:             }
 4143:         }
 4144:         my ($rolecode,$username,$domain,$section,$area);
 4145:         if ($context eq 'userroles') {
 4146:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4147:             (undef,$domain,$username,$section) = split(/\//,$area);
 4148:         } else {
 4149:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4150:         }
 4151:         if (ref($roledoms) eq 'ARRAY') {
 4152:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4153:                 next;
 4154:             }
 4155:         }
 4156:         if (ref($roles) eq 'ARRAY') {
 4157:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4158:                 if ($role =~ /^cr\//) {
 4159:                     if (!grep(/^cr$/,@{$roles})) {
 4160:                         next;
 4161:                     }
 4162:                 } elsif ($role =~ /^gr\//) {
 4163:                     if (!grep(/^gr$/,@{$roles})) {
 4164:                         next;
 4165:                     }
 4166:                 } else {
 4167:                     next;
 4168:                 }
 4169:             }
 4170:         }
 4171:         if ($hidepriv) {
 4172:             my @privroles = ('dc','su');
 4173:             if ($context eq 'userroles') {
 4174:                 next if (grep(/^\Q$role\E$/,@privroles));
 4175:             } else {
 4176:                 my $possdoms = [$domain];
 4177:                 if (ref($roledoms) eq 'ARRAY') {
 4178:                    push(@{$possdoms},@{$roledoms}); 
 4179:                 }
 4180:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4181:                     if (!$nothide{$username.':'.$domain}) {
 4182:                         next;
 4183:                     }
 4184:                 }
 4185:             }
 4186:         }
 4187:         if ($withsec) {
 4188:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4189:                 $tstart.':'.$tend;
 4190:         } else {
 4191:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4192:         }
 4193:     }
 4194:     return %returnhash;
 4195: }
 4196: 
 4197: # ----------------------------------------------------- Frontpage Announcements
 4198: #
 4199: #
 4200: 
 4201: sub postannounce {
 4202:     my ($server,$text)=@_;
 4203:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4204:     unless ($text=~/\w/) { $text=''; }
 4205:     return &reply('setannounce:'.&escape($text),$server);
 4206: }
 4207: 
 4208: sub getannounce {
 4209: 
 4210:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4211: 	my $announcement='';
 4212: 	while (my $line = <$fh>) { $announcement .= $line; }
 4213: 	close($fh);
 4214: 	if ($announcement=~/\w/) { 
 4215: 	    return 
 4216:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4217:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4218: 	} else {
 4219: 	    return '';
 4220: 	}
 4221:     } else {
 4222: 	return '';
 4223:     }
 4224: }
 4225: 
 4226: # ---------------------------------------------------------- Course ID routines
 4227: # Deal with domain's nohist_courseid.db files
 4228: #
 4229: 
 4230: sub courseidput {
 4231:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4232:     return unless (ref($storehash) eq 'HASH');
 4233:     my $outcome;
 4234:     if ($caller eq 'timeonly') {
 4235:         my $cids = '';
 4236:         foreach my $item (keys(%$storehash)) {
 4237:             $cids.=&escape($item).'&';
 4238:         }
 4239:         $cids=~s/\&$//;
 4240:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4241:                           $coursehome);       
 4242:     } else {
 4243:         my $items = '';
 4244:         foreach my $item (keys(%$storehash)) {
 4245:             $items.= &escape($item).'='.
 4246:                      &freeze_escape($$storehash{$item}).'&';
 4247:         }
 4248:         $items=~s/\&$//;
 4249:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4250:                           $coursehome);
 4251:     }
 4252:     if ($outcome eq 'unknown_cmd') {
 4253:         my $what;
 4254:         foreach my $cid (keys(%$storehash)) {
 4255:             $what .= &escape($cid).'=';
 4256:             foreach my $item ('description','inst_code','owner','type') {
 4257:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4258:             }
 4259:             $what =~ s/\:$/&/;
 4260:         }
 4261:         $what =~ s/\&$//;  
 4262:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4263:     } else {
 4264:         return $outcome;
 4265:     }
 4266: }
 4267: 
 4268: sub courseiddump {
 4269:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4270:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4271:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4272:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4273:         $hasuniquecode)=@_;
 4274:     my $as_hash = 1;
 4275:     my %returnhash;
 4276:     if (!$domfilter) { $domfilter=''; }
 4277:     my %libserv = &all_library();
 4278:     foreach my $tryserver (keys(%libserv)) {
 4279:         if ( (  $hostidflag == 1 
 4280: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4281: 	     || (!defined($hostidflag)) ) {
 4282: 
 4283: 	    if (($domfilter eq '') ||
 4284: 		(&host_domain($tryserver) eq $domfilter)) {
 4285:                 my $rep;
 4286:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4287:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4288:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4289:                                 &escape($descfilter), &escape($instcodefilter), 
 4290:                                 &escape($ownerfilter), &escape($coursefilter),
 4291:                                 &escape($typefilter), &escape($regexp_ok), 
 4292:                                 $as_hash, &escape($selfenrollonly), 
 4293:                                 &escape($catfilter), $showhidden, $caller, 
 4294:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4295:                                 &escape($createdbefore), &escape($createdafter), 
 4296:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4297:                 } else {
 4298:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4299:                              $sincefilter.':'.&escape($descfilter).':'.
 4300:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4301:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4302:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4303:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4304:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4305:                              &escape($cc_clone).':'.$cloneonly.':'.
 4306:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4307:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4308:                              $tryserver);
 4309:                 }
 4310:                      
 4311:                 my @pairs=split(/\&/,$rep);
 4312:                 foreach my $item (@pairs) {
 4313:                     my ($key,$value)=split(/\=/,$item,2);
 4314:                     $key = &unescape($key);
 4315:                     next if ($key =~ /^error: 2 /);
 4316:                     my $result = &thaw_unescape($value);
 4317:                     if (ref($result) eq 'HASH') {
 4318:                         $returnhash{$key}=$result;
 4319:                     } else {
 4320:                         my @responses = split(/:/,$value);
 4321:                         my @items = ('description','inst_code','owner','type');
 4322:                         for (my $i=0; $i<@responses; $i++) {
 4323:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4324:                         }
 4325:                     }
 4326:                 }
 4327:             }
 4328:         }
 4329:     }
 4330:     return %returnhash;
 4331: }
 4332: 
 4333: sub courselastaccess {
 4334:     my ($cdom,$cnum,$hostidref) = @_;
 4335:     my %returnhash;
 4336:     if ($cdom && $cnum) {
 4337:         my $chome = &homeserver($cnum,$cdom);
 4338:         if ($chome ne 'no_host') {
 4339:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4340:             &extract_lastaccess(\%returnhash,$rep);
 4341:         }
 4342:     } else {
 4343:         if (!$cdom) { $cdom=''; }
 4344:         my %libserv = &all_library();
 4345:         foreach my $tryserver (keys(%libserv)) {
 4346:             if (ref($hostidref) eq 'ARRAY') {
 4347:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4348:             } 
 4349:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4350:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4351:                 &extract_lastaccess(\%returnhash,$rep);
 4352:             }
 4353:         }
 4354:     }
 4355:     return %returnhash;
 4356: }
 4357: 
 4358: sub extract_lastaccess {
 4359:     my ($returnhash,$rep) = @_;
 4360:     if (ref($returnhash) eq 'HASH') {
 4361:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4362:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4363:                  $rep eq '') {
 4364:             my @pairs=split(/\&/,$rep);
 4365:             foreach my $item (@pairs) {
 4366:                 my ($key,$value)=split(/\=/,$item,2);
 4367:                 $key = &unescape($key);
 4368:                 next if ($key =~ /^error: 2 /);
 4369:                 $returnhash->{$key} = &thaw_unescape($value);
 4370:             }
 4371:         }
 4372:     }
 4373:     return;
 4374: }
 4375: 
 4376: # ---------------------------------------------------------- DC e-mail
 4377: 
 4378: sub dcmailput {
 4379:     my ($domain,$msgid,$message,$server)=@_;
 4380:     my $status = &Apache::lonnet::critical(
 4381:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4382:        &escape($message),$server);
 4383:     return $status;
 4384: }
 4385: 
 4386: sub dcmaildump {
 4387:     my ($dom,$startdate,$enddate,$senders) = @_;
 4388:     my %returnhash=();
 4389: 
 4390:     if (defined(&domain($dom,'primary'))) {
 4391:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4392:                                                          &escape($enddate).':';
 4393: 	my @esc_senders=map { &escape($_)} @$senders;
 4394: 	$cmd.=&escape(join('&',@esc_senders));
 4395: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4396:             my ($key,$value) = split(/\=/,$line,2);
 4397:             if (($key) && ($value)) {
 4398:                 $returnhash{&unescape($key)} = &unescape($value);
 4399:             }
 4400:         }
 4401:     }
 4402:     return %returnhash;
 4403: }
 4404: # ---------------------------------------------------------- Domain roles
 4405: 
 4406: sub get_domain_roles {
 4407:     my ($dom,$roles,$startdate,$enddate)=@_;
 4408:     if ((!defined($startdate)) || ($startdate eq '')) {
 4409:         $startdate = '.';
 4410:     }
 4411:     if ((!defined($enddate)) || ($enddate eq '')) {
 4412:         $enddate = '.';
 4413:     }
 4414:     my $rolelist;
 4415:     if (ref($roles) eq 'ARRAY') {
 4416:         $rolelist = join('&',@{$roles});
 4417:     }
 4418:     my %personnel = ();
 4419: 
 4420:     my %servers = &get_servers($dom,'library');
 4421:     foreach my $tryserver (keys(%servers)) {
 4422: 	%{$personnel{$tryserver}}=();
 4423: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4424: 					    &escape($startdate).':'.
 4425: 					    &escape($enddate).':'.
 4426: 					    &escape($rolelist), $tryserver))) {
 4427: 	    my ($key,$value) = split(/\=/,$line,2);
 4428: 	    if (($key) && ($value)) {
 4429: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4430: 	    }
 4431: 	}
 4432:     }
 4433:     return %personnel;
 4434: }
 4435: 
 4436: # ----------------------------------------------------------- Interval timing 
 4437: 
 4438: {
 4439: # Caches needed for speedup of navmaps
 4440: # We don't want to cache this for very long at all (5 seconds at most)
 4441: # 
 4442: # The user for whom we cache
 4443: my $cachedkey='';
 4444: # The cached times for this user
 4445: my %cachedtimes=();
 4446: # When this was last done
 4447: my $cachedtime='';
 4448: 
 4449: sub load_all_first_access {
 4450:     my ($uname,$udom)=@_;
 4451:     if (($cachedkey eq $uname.':'.$udom) &&
 4452:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4453:         return;
 4454:     }
 4455:     $cachedtime=time;
 4456:     $cachedkey=$uname.':'.$udom;
 4457:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4458: }
 4459: 
 4460: sub get_first_access {
 4461:     my ($type,$argsymb,$argmap)=@_;
 4462:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4463:     if ($argsymb) { $symb=$argsymb; }
 4464:     my ($map,$id,$res)=&decode_symb($symb);
 4465:     if ($argmap) { $map = $argmap; }
 4466:     if ($type eq 'course') {
 4467: 	$res='course';
 4468:     } elsif ($type eq 'map') {
 4469: 	$res=&symbread($map);
 4470:     } else {
 4471: 	$res=$symb;
 4472:     }
 4473:     &load_all_first_access($uname,$udom);
 4474:     return $cachedtimes{"$courseid\0$res"};
 4475: }
 4476: 
 4477: sub set_first_access {
 4478:     my ($type,$interval)=@_;
 4479:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4480:     my ($map,$id,$res)=&decode_symb($symb);
 4481:     if ($type eq 'course') {
 4482: 	$res='course';
 4483:     } elsif ($type eq 'map') {
 4484: 	$res=&symbread($map);
 4485:     } else {
 4486: 	$res=$symb;
 4487:     }
 4488:     $cachedkey='';
 4489:     my $firstaccess=&get_first_access($type,$symb,$map);
 4490:     if (!$firstaccess) {
 4491:         my $start = time;
 4492: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4493:                           $udom,$uname);
 4494:         if ($putres eq 'ok') {
 4495:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4496:                  $udom,$uname); 
 4497:             &appenv(
 4498:                      {
 4499:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4500:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4501:                      }
 4502:                   );
 4503:         }
 4504:         return $putres;
 4505:     }
 4506:     return 'already_set';
 4507: }
 4508: }
 4509: 
 4510: # --------------------------------------------- Set Expire Date for Spreadsheet
 4511: 
 4512: sub expirespread {
 4513:     my ($uname,$udom,$stype,$usymb)=@_;
 4514:     my $cid=$env{'request.course.id'}; 
 4515:     if ($cid) {
 4516:        my $now=time;
 4517:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4518:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4519:                             $env{'course.'.$cid.'.num'}.
 4520: 	        	    ':nohist_expirationdates:'.
 4521:                             &escape($key).'='.$now,
 4522:                             $env{'course.'.$cid.'.home'})
 4523:     }
 4524:     return 'ok';
 4525: }
 4526: 
 4527: # ----------------------------------------------------- Devalidate Spreadsheets
 4528: 
 4529: sub devalidate {
 4530:     my ($symb,$uname,$udom)=@_;
 4531:     my $cid=$env{'request.course.id'}; 
 4532:     if ($cid) {
 4533:         # delete the stored spreadsheets for
 4534:         # - the student level sheet of this user in course's homespace
 4535:         # - the assessment level sheet for this resource 
 4536:         #   for this user in user's homespace
 4537: 	# - current conditional state info
 4538: 	my $key=$uname.':'.$udom.':';
 4539:         my $status=
 4540: 	    &del('nohist_calculatedsheets',
 4541: 		 [$key.'studentcalc:'],
 4542: 		 $env{'course.'.$cid.'.domain'},
 4543: 		 $env{'course.'.$cid.'.num'})
 4544: 		.' '.
 4545: 	    &del('nohist_calculatedsheets_'.$cid,
 4546: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4547:         unless ($status eq 'ok ok') {
 4548:            &logthis('Could not devalidate spreadsheet '.
 4549:                     $uname.' at '.$udom.' for '.
 4550: 		    $symb.': '.$status);
 4551:         }
 4552: 	&delenv('user.state.'.$cid);
 4553:     }
 4554: }
 4555: 
 4556: sub get_scalar {
 4557:     my ($string,$end) = @_;
 4558:     my $value;
 4559:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4560: 	$value = $1;
 4561:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4562: 	$value = $1;
 4563:     }
 4564:     return &unescape($value);
 4565: }
 4566: 
 4567: sub array2str {
 4568:   my (@array) = @_;
 4569:   my $result=&arrayref2str(\@array);
 4570:   $result=~s/^__ARRAY_REF__//;
 4571:   $result=~s/__END_ARRAY_REF__$//;
 4572:   return $result;
 4573: }
 4574: 
 4575: sub arrayref2str {
 4576:   my ($arrayref) = @_;
 4577:   my $result='__ARRAY_REF__';
 4578:   foreach my $elem (@$arrayref) {
 4579:     if(ref($elem) eq 'ARRAY') {
 4580:       $result.=&arrayref2str($elem).'&';
 4581:     } elsif(ref($elem) eq 'HASH') {
 4582:       $result.=&hashref2str($elem).'&';
 4583:     } elsif(ref($elem)) {
 4584:       #print("Got a ref of ".(ref($elem))." skipping.");
 4585:     } else {
 4586:       $result.=&escape($elem).'&';
 4587:     }
 4588:   }
 4589:   $result=~s/\&$//;
 4590:   $result .= '__END_ARRAY_REF__';
 4591:   return $result;
 4592: }
 4593: 
 4594: sub hash2str {
 4595:   my (%hash) = @_;
 4596:   my $result=&hashref2str(\%hash);
 4597:   $result=~s/^__HASH_REF__//;
 4598:   $result=~s/__END_HASH_REF__$//;
 4599:   return $result;
 4600: }
 4601: 
 4602: sub hashref2str {
 4603:   my ($hashref)=@_;
 4604:   my $result='__HASH_REF__';
 4605:   foreach my $key (sort(keys(%$hashref))) {
 4606:     if (ref($key) eq 'ARRAY') {
 4607:       $result.=&arrayref2str($key).'=';
 4608:     } elsif (ref($key) eq 'HASH') {
 4609:       $result.=&hashref2str($key).'=';
 4610:     } elsif (ref($key)) {
 4611:       $result.='=';
 4612:       #print("Got a ref of ".(ref($key))." skipping.");
 4613:     } else {
 4614: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4615:     }
 4616: 
 4617:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4618:       $result.=&arrayref2str($hashref->{$key}).'&';
 4619:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4620:       $result.=&hashref2str($hashref->{$key}).'&';
 4621:     } elsif(ref($hashref->{$key})) {
 4622:        $result.='&';
 4623:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4624:     } else {
 4625:       $result.=&escape($hashref->{$key}).'&';
 4626:     }
 4627:   }
 4628:   $result=~s/\&$//;
 4629:   $result .= '__END_HASH_REF__';
 4630:   return $result;
 4631: }
 4632: 
 4633: sub str2hash {
 4634:     my ($string)=@_;
 4635:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4636:     return %$hash;
 4637: }
 4638: 
 4639: sub str2hashref {
 4640:   my ($string) = @_;
 4641: 
 4642:   my %hash;
 4643: 
 4644:   if($string !~ /^__HASH_REF__/) {
 4645:       if (! ($string eq '' || !defined($string))) {
 4646: 	  $hash{'error'}='Not hash reference';
 4647:       }
 4648:       return (\%hash, $string);
 4649:   }
 4650: 
 4651:   $string =~ s/^__HASH_REF__//;
 4652: 
 4653:   while($string !~ /^__END_HASH_REF__/) {
 4654:       #key
 4655:       my $key='';
 4656:       if($string =~ /^__HASH_REF__/) {
 4657:           ($key, $string)=&str2hashref($string);
 4658:           if(defined($key->{'error'})) {
 4659:               $hash{'error'}='Bad data';
 4660:               return (\%hash, $string);
 4661:           }
 4662:       } elsif($string =~ /^__ARRAY_REF__/) {
 4663:           ($key, $string)=&str2arrayref($string);
 4664:           if($key->[0] eq 'Array reference error') {
 4665:               $hash{'error'}='Bad data';
 4666:               return (\%hash, $string);
 4667:           }
 4668:       } else {
 4669:           $string =~ s/^(.*?)=//;
 4670: 	  $key=&unescape($1);
 4671:       }
 4672:       $string =~ s/^=//;
 4673: 
 4674:       #value
 4675:       my $value='';
 4676:       if($string =~ /^__HASH_REF__/) {
 4677:           ($value, $string)=&str2hashref($string);
 4678:           if(defined($value->{'error'})) {
 4679:               $hash{'error'}='Bad data';
 4680:               return (\%hash, $string);
 4681:           }
 4682:       } elsif($string =~ /^__ARRAY_REF__/) {
 4683:           ($value, $string)=&str2arrayref($string);
 4684:           if($value->[0] eq 'Array reference error') {
 4685:               $hash{'error'}='Bad data';
 4686:               return (\%hash, $string);
 4687:           }
 4688:       } else {
 4689: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4690:       }
 4691:       $string =~ s/^&//;
 4692: 
 4693:       $hash{$key}=$value;
 4694:   }
 4695: 
 4696:   $string =~ s/^__END_HASH_REF__//;
 4697: 
 4698:   return (\%hash, $string);
 4699: }
 4700: 
 4701: sub str2array {
 4702:     my ($string)=@_;
 4703:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4704:     return @$array;
 4705: }
 4706: 
 4707: sub str2arrayref {
 4708:   my ($string) = @_;
 4709:   my @array;
 4710: 
 4711:   if($string !~ /^__ARRAY_REF__/) {
 4712:       if (! ($string eq '' || !defined($string))) {
 4713: 	  $array[0]='Array reference error';
 4714:       }
 4715:       return (\@array, $string);
 4716:   }
 4717: 
 4718:   $string =~ s/^__ARRAY_REF__//;
 4719: 
 4720:   while($string !~ /^__END_ARRAY_REF__/) {
 4721:       my $value='';
 4722:       if($string =~ /^__HASH_REF__/) {
 4723:           ($value, $string)=&str2hashref($string);
 4724:           if(defined($value->{'error'})) {
 4725:               $array[0] ='Array reference error';
 4726:               return (\@array, $string);
 4727:           }
 4728:       } elsif($string =~ /^__ARRAY_REF__/) {
 4729:           ($value, $string)=&str2arrayref($string);
 4730:           if($value->[0] eq 'Array reference error') {
 4731:               $array[0] ='Array reference error';
 4732:               return (\@array, $string);
 4733:           }
 4734:       } else {
 4735: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4736:       }
 4737:       $string =~ s/^&//;
 4738: 
 4739:       push(@array, $value);
 4740:   }
 4741: 
 4742:   $string =~ s/^__END_ARRAY_REF__//;
 4743: 
 4744:   return (\@array, $string);
 4745: }
 4746: 
 4747: # -------------------------------------------------------------------Temp Store
 4748: 
 4749: sub tmpreset {
 4750:   my ($symb,$namespace,$domain,$stuname) = @_;
 4751:   if (!$symb) {
 4752:     $symb=&symbread();
 4753:     if (!$symb) { $symb= $env{'request.url'}; }
 4754:   }
 4755:   $symb=escape($symb);
 4756: 
 4757:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4758:   $namespace=~s/\//\_/g;
 4759:   $namespace=~s/\W//g;
 4760: 
 4761:   if (!$domain) { $domain=$env{'user.domain'}; }
 4762:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4763:   if ($domain eq 'public' && $stuname eq 'public') {
 4764:       $stuname=$ENV{'REMOTE_ADDR'};
 4765:   }
 4766:   my $path=LONCAPA::tempdir();
 4767:   my %hash;
 4768:   if (tie(%hash,'GDBM_File',
 4769: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4770: 	  &GDBM_WRCREAT(),0640)) {
 4771:     foreach my $key (keys(%hash)) {
 4772:       if ($key=~ /:$symb/) {
 4773: 	delete($hash{$key});
 4774:       }
 4775:     }
 4776:   }
 4777: }
 4778: 
 4779: sub tmpstore {
 4780:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4781: 
 4782:   if (!$symb) {
 4783:     $symb=&symbread();
 4784:     if (!$symb) { $symb= $env{'request.url'}; }
 4785:   }
 4786:   $symb=escape($symb);
 4787: 
 4788:   if (!$namespace) {
 4789:     # I don't think we would ever want to store this for a course.
 4790:     # it seems this will only be used if we don't have a course.
 4791:     #$namespace=$env{'request.course.id'};
 4792:     #if (!$namespace) {
 4793:       $namespace=$env{'request.state'};
 4794:     #}
 4795:   }
 4796:   $namespace=~s/\//\_/g;
 4797:   $namespace=~s/\W//g;
 4798:   if (!$domain) { $domain=$env{'user.domain'}; }
 4799:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4800:   if ($domain eq 'public' && $stuname eq 'public') {
 4801:       $stuname=$ENV{'REMOTE_ADDR'};
 4802:   }
 4803:   my $now=time;
 4804:   my %hash;
 4805:   my $path=LONCAPA::tempdir();
 4806:   if (tie(%hash,'GDBM_File',
 4807: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4808: 	  &GDBM_WRCREAT(),0640)) {
 4809:     $hash{"version:$symb"}++;
 4810:     my $version=$hash{"version:$symb"};
 4811:     my $allkeys=''; 
 4812:     foreach my $key (keys(%$storehash)) {
 4813:       $allkeys.=$key.':';
 4814:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4815:     }
 4816:     $hash{"$version:$symb:timestamp"}=$now;
 4817:     $allkeys.='timestamp';
 4818:     $hash{"$version:keys:$symb"}=$allkeys;
 4819:     if (untie(%hash)) {
 4820:       return 'ok';
 4821:     } else {
 4822:       return "error:$!";
 4823:     }
 4824:   } else {
 4825:     return "error:$!";
 4826:   }
 4827: }
 4828: 
 4829: # -----------------------------------------------------------------Temp Restore
 4830: 
 4831: sub tmprestore {
 4832:   my ($symb,$namespace,$domain,$stuname) = @_;
 4833: 
 4834:   if (!$symb) {
 4835:     $symb=&symbread();
 4836:     if (!$symb) { $symb= $env{'request.url'}; }
 4837:   }
 4838:   $symb=escape($symb);
 4839: 
 4840:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4841: 
 4842:   if (!$domain) { $domain=$env{'user.domain'}; }
 4843:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4844:   if ($domain eq 'public' && $stuname eq 'public') {
 4845:       $stuname=$ENV{'REMOTE_ADDR'};
 4846:   }
 4847:   my %returnhash;
 4848:   $namespace=~s/\//\_/g;
 4849:   $namespace=~s/\W//g;
 4850:   my %hash;
 4851:   my $path=LONCAPA::tempdir();
 4852:   if (tie(%hash,'GDBM_File',
 4853: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4854: 	  &GDBM_READER(),0640)) {
 4855:     my $version=$hash{"version:$symb"};
 4856:     $returnhash{'version'}=$version;
 4857:     my $scope;
 4858:     for ($scope=1;$scope<=$version;$scope++) {
 4859:       my $vkeys=$hash{"$scope:keys:$symb"};
 4860:       my @keys=split(/:/,$vkeys);
 4861:       my $key;
 4862:       $returnhash{"$scope:keys"}=$vkeys;
 4863:       foreach $key (@keys) {
 4864: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4865: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4866:       }
 4867:     }
 4868:     if (!(untie(%hash))) {
 4869:       return "error:$!";
 4870:     }
 4871:   } else {
 4872:     return "error:$!";
 4873:   }
 4874:   return %returnhash;
 4875: }
 4876: 
 4877: # ----------------------------------------------------------------------- Store
 4878: 
 4879: sub store {
 4880:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4881:     my $home='';
 4882: 
 4883:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4884: 
 4885:     $symb=&symbclean($symb);
 4886:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4887: 
 4888:     if (!$domain) { $domain=$env{'user.domain'}; }
 4889:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4890: 
 4891:     &devalidate($symb,$stuname,$domain);
 4892: 
 4893:     $symb=escape($symb);
 4894:     if (!$namespace) { 
 4895:        unless ($namespace=$env{'request.course.id'}) { 
 4896:           return ''; 
 4897:        } 
 4898:     }
 4899:     if (!$home) { $home=$env{'user.home'}; }
 4900: 
 4901:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4902:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4903: 
 4904:     my $namevalue='';
 4905:     foreach my $key (keys(%$storehash)) {
 4906:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4907:     }
 4908:     $namevalue=~s/\&$//;
 4909:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4910:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4911: }
 4912: 
 4913: # -------------------------------------------------------------- Critical Store
 4914: 
 4915: sub cstore {
 4916:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4917:     my $home='';
 4918: 
 4919:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4920: 
 4921:     $symb=&symbclean($symb);
 4922:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4923: 
 4924:     if (!$domain) { $domain=$env{'user.domain'}; }
 4925:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4926: 
 4927:     &devalidate($symb,$stuname,$domain);
 4928: 
 4929:     $symb=escape($symb);
 4930:     if (!$namespace) { 
 4931:        unless ($namespace=$env{'request.course.id'}) { 
 4932:           return ''; 
 4933:        } 
 4934:     }
 4935:     if (!$home) { $home=$env{'user.home'}; }
 4936: 
 4937:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4938:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4939: 
 4940:     my $namevalue='';
 4941:     foreach my $key (keys(%$storehash)) {
 4942:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4943:     }
 4944:     $namevalue=~s/\&$//;
 4945:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4946:     return critical
 4947:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4948: }
 4949: 
 4950: # --------------------------------------------------------------------- Restore
 4951: 
 4952: sub restore {
 4953:     my ($symb,$namespace,$domain,$stuname) = @_;
 4954:     my $home='';
 4955: 
 4956:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4957: 
 4958:     if (!$symb) {
 4959:         return if ($namespace eq 'courserequests');
 4960:         unless ($symb=escape(&symbread())) { return ''; }
 4961:     } else {
 4962:         unless ($namespace eq 'courserequests') {
 4963:             $symb=&escape(&symbclean($symb));
 4964:         }
 4965:     }
 4966:     if (!$namespace) { 
 4967:        unless ($namespace=$env{'request.course.id'}) { 
 4968:           return ''; 
 4969:        } 
 4970:     }
 4971:     if (!$domain) { $domain=$env{'user.domain'}; }
 4972:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4973:     if (!$home) { $home=$env{'user.home'}; }
 4974:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4975: 
 4976:     my %returnhash=();
 4977:     foreach my $line (split(/\&/,$answer)) {
 4978: 	my ($name,$value)=split(/\=/,$line);
 4979:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4980:     }
 4981:     my $version;
 4982:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4983:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4984:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4985:        }
 4986:     }
 4987:     return %returnhash;
 4988: }
 4989: 
 4990: # ---------------------------------------------------------- Course Description
 4991: #
 4992: #  
 4993: 
 4994: sub coursedescription {
 4995:     my ($courseid,$args)=@_;
 4996:     $courseid=~s/^\///;
 4997:     $courseid=~s/\_/\//g;
 4998:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4999:     my $chome=&homeserver($cnum,$cdomain);
 5000:     my $normalid=$cdomain.'_'.$cnum;
 5001:     # need to always cache even if we get errors otherwise we keep 
 5002:     # trying and trying and trying to get the course description.
 5003:     my %envhash=();
 5004:     my %returnhash=();
 5005:     
 5006:     my $expiretime=600;
 5007:     if ($env{'request.course.id'} eq $normalid) {
 5008: 	$expiretime=120;
 5009:     }
 5010: 
 5011:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5012:     if (!$args->{'freshen_cache'}
 5013: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5014: 	foreach my $key (keys(%env)) {
 5015: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5016: 	    my ($setting) = $1;
 5017: 	    $returnhash{$setting} = $env{$key};
 5018: 	}
 5019: 	return %returnhash;
 5020:     }
 5021: 
 5022:     # get the data again
 5023: 
 5024:     if (!$args->{'one_time'}) {
 5025: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5026:     }
 5027: 
 5028:     if ($chome ne 'no_host') {
 5029:        %returnhash=&dump('environment',$cdomain,$cnum);
 5030:        if (!exists($returnhash{'con_lost'})) {
 5031: 	   my $username = $env{'user.name'}; # Defult username
 5032: 	   if(defined $args->{'user'}) {
 5033: 	       $username = $args->{'user'};
 5034: 	   }
 5035:            $returnhash{'home'}= $chome;
 5036: 	   $returnhash{'domain'} = $cdomain;
 5037: 	   $returnhash{'num'} = $cnum;
 5038:            if (!defined($returnhash{'type'})) {
 5039:                $returnhash{'type'} = 'Course';
 5040:            }
 5041:            while (my ($name,$value) = each %returnhash) {
 5042:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5043:            }
 5044:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5045:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5046: 	       $username.'_'.$cdomain.'_'.$cnum;
 5047:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5048:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5049:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5050:        }
 5051:     }
 5052:     if (!$args->{'one_time'}) {
 5053: 	&appenv(\%envhash);
 5054:     }
 5055:     return %returnhash;
 5056: }
 5057: 
 5058: sub update_released_required {
 5059:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5060:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5061:         $cid = $env{'request.course.id'};
 5062:         $cdom = $env{'course.'.$cid.'.domain'};
 5063:         $cnum = $env{'course.'.$cid.'.num'};
 5064:         $chome = $env{'course.'.$cid.'.home'};
 5065:     }
 5066:     if ($needsrelease) {
 5067:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5068:         my $needsupdate;
 5069:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5070:             $needsupdate = 1;
 5071:         } else {
 5072:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5073:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5074:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5075:                 $needsupdate = 1;
 5076:             }
 5077:         }
 5078:         if ($needsupdate) {
 5079:             my %needshash = (
 5080:                              'internal.releaserequired' => $needsrelease,
 5081:                             );
 5082:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5083:             if ($putresult eq 'ok') {
 5084:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5085:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5086:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5087:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5088:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5089:                 }
 5090:             }
 5091:         }
 5092:     }
 5093:     return;
 5094: }
 5095: 
 5096: # -------------------------------------------------See if a user is privileged
 5097: 
 5098: sub privileged {
 5099:     my ($username,$domain,$possdomains,$possroles)=@_;
 5100:     my $now = time;
 5101:     my $roles;
 5102:     if (ref($possroles) eq 'ARRAY') {
 5103:         $roles = $possroles; 
 5104:     } else {
 5105:         $roles = ['dc','su'];
 5106:     }
 5107:     if (ref($possdomains) eq 'ARRAY') {
 5108:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5109:         foreach my $dom (@{$possdomains}) {
 5110:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5111:                 (ref($privileged{$dom}) eq 'HASH')) {
 5112:                 foreach my $role (@{$roles}) {
 5113:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5114:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5115:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5116:                             return 1 unless (($end && $end < $now) ||
 5117:                                              ($start && $start > $now));
 5118:                         }
 5119:                     }
 5120:                 }
 5121:             }
 5122:         }
 5123:     } else {
 5124:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5125:         my $now = time;
 5126: 
 5127:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5128:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5129:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5130:                 return 1 unless ($tend && $tend < $now) 
 5131:                         or ($tstart && $tstart > $now);
 5132:             }
 5133:         }
 5134:     }
 5135:     return 0;
 5136: }
 5137: 
 5138: sub privileged_by_domain {
 5139:     my ($domains,$roles) = @_;
 5140:     my %privileged = ();
 5141:     my $cachetime = 60*60*24;
 5142:     my $now = time;
 5143:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5144:         return %privileged;
 5145:     }
 5146:     foreach my $dom (@{$domains}) {
 5147:         next if (ref($privileged{$dom}) eq 'HASH');
 5148:         my $needroles;
 5149:         foreach my $role (@{$roles}) {
 5150:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5151:             if (defined($cached)) {
 5152:                 if (ref($result) eq 'HASH') {
 5153:                     $privileged{$dom}{$role} = $result;
 5154:                 }
 5155:             } else {
 5156:                 $needroles = 1;
 5157:             }
 5158:         }
 5159:         if ($needroles) {
 5160:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5161:             $privileged{$dom} = {};
 5162:             foreach my $server (keys(%dompersonnel)) {
 5163:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5164:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5165:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5166:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5167:                         next if ($end && $end < $now);
 5168:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5169:                             $dompersonnel{$server}{$item};
 5170:                     }
 5171:                 }
 5172:             }
 5173:             if (ref($privileged{$dom}) eq 'HASH') {
 5174:                 foreach my $role (@{$roles}) {
 5175:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5176:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5177:                     } else {
 5178:                         my %hash = ();
 5179:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5180:                     }
 5181:                 }
 5182:             }
 5183:         }
 5184:     }
 5185:     return %privileged;
 5186: }
 5187: 
 5188: # -------------------------------------------------------- Get user privileges
 5189: 
 5190: sub rolesinit {
 5191:     my ($domain, $username) = @_;
 5192:     my %userroles = ('user.login.time' => time);
 5193:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5194: 
 5195:     # firstaccess and timerinterval are related to timed maps/resources. 
 5196:     # also, blocking can be triggered by an activating timer
 5197:     # it's saved in the user's %env.
 5198:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5199:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5200:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5201:         %timerintchk, %timerintenv);
 5202: 
 5203:     foreach my $key (keys(%firstaccess)) {
 5204:         my ($cid, $rest) = split(/\0/, $key);
 5205:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5206:     }
 5207: 
 5208:     foreach my $key (keys(%timerinterval)) {
 5209:         my ($cid,$rest) = split(/\0/,$key);
 5210:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5211:     }
 5212: 
 5213:     my %allroles=();
 5214:     my %allgroups=();
 5215: 
 5216:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5217:         my $role = $rolesdump{$area};
 5218:         $area =~ s/\_\w\w$//;
 5219: 
 5220:         my ($trole, $tend, $tstart, $group_privs);
 5221: 
 5222:         if ($role =~ /^cr/) {
 5223:         # Custom role, defined by a user 
 5224:         # e.g., user.role.cr/msu/smith/mynewrole
 5225:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5226:                 $trole = $1;
 5227:                 ($tend, $tstart) = split('_', $2);
 5228:             } else {
 5229:                 $trole = $role;
 5230:             }
 5231:         } elsif ($role =~ m|^gr/|) {
 5232:         # Role of member in a group, defined within a course/community
 5233:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5234:             ($trole, $tend, $tstart) = split(/_/, $role);
 5235:             next if $tstart eq '-1';
 5236:             ($trole, $group_privs) = split(/\//, $trole);
 5237:             $group_privs = &unescape($group_privs);
 5238:         } else {
 5239:         # Just a normal role, defined in roles.tab
 5240:             ($trole, $tend, $tstart) = split(/_/,$role);
 5241:         }
 5242: 
 5243:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5244:                  $username);
 5245:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5246: 
 5247:         # role expired or not available yet?
 5248:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5249:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5250: 
 5251:         next if $area eq '' or $trole eq '';
 5252: 
 5253:         my $spec = "$trole.$area";
 5254:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5255: 
 5256:         if ($trole =~ /^cr\//) {
 5257:         # Custom role, defined by a user
 5258:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5259:         } elsif ($trole eq 'gr') {
 5260:         # Role of a member in a group, defined within a course/community
 5261:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5262:             next;
 5263:         } else {
 5264:         # Normal role, defined in roles.tab
 5265:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5266:         }
 5267: 
 5268:         my $cid = $tdomain.'_'.$trest;
 5269:         unless ($firstaccchk{$cid}) {
 5270:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5271:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5272:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5273:                         $coursetimerstarts{$cid}{$item}; 
 5274:                 }
 5275:             }
 5276:             $firstaccchk{$cid} = 1;
 5277:         }
 5278:         unless ($timerintchk{$cid}) {
 5279:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5280:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5281:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5282:                        $coursetimerintervals{$cid}{$item};
 5283:                 }
 5284:             }
 5285:             $timerintchk{$cid} = 1;
 5286:         }
 5287:     }
 5288: 
 5289:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5290:         \%allroles, \%allgroups);
 5291:     $env{'user.adv'} = $userroles{'user.adv'};
 5292: 
 5293:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5294: }
 5295: 
 5296: sub set_arearole {
 5297:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5298:     unless ($nolog) {
 5299: # log the associated role with the area
 5300:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5301:     }
 5302:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5303: }
 5304: 
 5305: sub custom_roleprivs {
 5306:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5307:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5308:     my $homsvr = &homeserver($rauthor,$rdomain);
 5309:     if (&hostname($homsvr) ne '') {
 5310:         my ($rdummy,$roledef)=
 5311:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5312:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5313:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5314:             if (defined($syspriv)) {
 5315:                 if ($trest =~ /^$match_community$/) {
 5316:                     $syspriv =~ s/bre\&S//; 
 5317:                 }
 5318:                 $$allroles{'cm./'}.=':'.$syspriv;
 5319:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5320:             }
 5321:             if ($tdomain ne '') {
 5322:                 if (defined($dompriv)) {
 5323:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5324:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5325:                 }
 5326:                 if (($trest ne '') && (defined($coursepriv))) {
 5327:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5328:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5329:                 }
 5330:             }
 5331:         }
 5332:     }
 5333: }
 5334: 
 5335: sub group_roleprivs {
 5336:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5337:     my $access = 1;
 5338:     my $now = time;
 5339:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5340:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5341:     if ($access) {
 5342:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5343:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5344:     }
 5345: }
 5346: 
 5347: sub standard_roleprivs {
 5348:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5349:     if (defined($pr{$trole.':s'})) {
 5350:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5351:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5352:     }
 5353:     if ($tdomain ne '') {
 5354:         if (defined($pr{$trole.':d'})) {
 5355:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5356:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5357:         }
 5358:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5359:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5360:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5361:         }
 5362:     }
 5363: }
 5364: 
 5365: sub set_userprivs {
 5366:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5367:     my $author=0;
 5368:     my $adv=0;
 5369:     my %grouproles = ();
 5370:     if (keys(%{$allgroups}) > 0) {
 5371:         my @groupkeys; 
 5372:         foreach my $role (keys(%{$allroles})) {
 5373:             push(@groupkeys,$role);
 5374:         }
 5375:         if (ref($groups_roles) eq 'HASH') {
 5376:             foreach my $key (keys(%{$groups_roles})) {
 5377:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5378:                     push(@groupkeys,$key);
 5379:                 }
 5380:             }
 5381:         }
 5382:         if (@groupkeys > 0) {
 5383:             foreach my $role (@groupkeys) {
 5384:                 my ($trole,$area,$sec,$extendedarea);
 5385:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5386:                     $trole = $1;
 5387:                     $area = $2;
 5388:                     $sec = $3;
 5389:                     $extendedarea = $area.$sec;
 5390:                     if (exists($$allgroups{$area})) {
 5391:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5392:                             my $spec = $trole.'.'.$extendedarea;
 5393:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5394:                                                 $$allgroups{$area}{$group};
 5395:                         }
 5396:                     }
 5397:                 }
 5398:             }
 5399:         }
 5400:     }
 5401:     foreach my $group (keys(%grouproles)) {
 5402:         $$allroles{$group} = $grouproles{$group};
 5403:     }
 5404:     foreach my $role (keys(%{$allroles})) {
 5405:         my %thesepriv;
 5406:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5407:         foreach my $item (split(/:/,$$allroles{$role})) {
 5408:             if ($item ne '') {
 5409:                 my ($privilege,$restrictions)=split(/&/,$item);
 5410:                 if ($restrictions eq '') {
 5411:                     $thesepriv{$privilege}='F';
 5412:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5413:                     $thesepriv{$privilege}.=$restrictions;
 5414:                 }
 5415:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5416:             }
 5417:         }
 5418:         my $thesestr='';
 5419:         foreach my $priv (sort(keys(%thesepriv))) {
 5420: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5421: 	}
 5422:         $userroles->{'user.priv.'.$role} = $thesestr;
 5423:     }
 5424:     return ($author,$adv);
 5425: }
 5426: 
 5427: sub role_status {
 5428:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5429:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5430:         my ($one,$two) = split(m{\./},$rolekey,2);
 5431:         (undef,undef,$$role) = split(/\./,$one,3);
 5432:         unless (!defined($$role) || $$role eq '') {
 5433:             $$where = '/'.$two;
 5434:             $$trolecode=$$role.'.'.$$where;
 5435:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5436:             $$tstatus='is';
 5437:             if ($$tstart && $$tstart>$update) {
 5438:                 $$tstatus='future';
 5439:                 if ($$tstart<$now) {
 5440:                     if ($$tstart && $$tstart>$refresh) {
 5441:                         if (($$where ne '') && ($$role ne '')) {
 5442:                             my (%allroles,%allgroups,$group_privs,
 5443:                                 %groups_roles,@rolecodes);
 5444:                             my %userroles = (
 5445:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5446:                             );
 5447:                             @rolecodes = ('cm'); 
 5448:                             my $spec=$$role.'.'.$$where;
 5449:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5450:                             if ($$role =~ /^cr\//) {
 5451:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5452:                                 push(@rolecodes,'cr');
 5453:                             } elsif ($$role eq 'gr') {
 5454:                                 push(@rolecodes,$$role);
 5455:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5456:                                                     $env{'user.name'});
 5457:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5458:                                 (undef,my $group_privs) = split(/\//,$trole);
 5459:                                 $group_privs = &unescape($group_privs);
 5460:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5461:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5462:                                 &get_groups_roles($tdomain,$trest,
 5463:                                                   \%course_roles,\@rolecodes,
 5464:                                                   \%groups_roles);
 5465:                             } else {
 5466:                                 push(@rolecodes,$$role);
 5467:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5468:                             }
 5469:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5470:                             &appenv(\%userroles,\@rolecodes);
 5471:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5472:                         }
 5473:                     }
 5474:                     $$tstatus = 'is';
 5475:                 }
 5476:             }
 5477:             if ($$tend) {
 5478:                 if ($$tend<$update) {
 5479:                     $$tstatus='expired';
 5480:                 } elsif ($$tend<$now) {
 5481:                     $$tstatus='will_not';
 5482:                 }
 5483:             }
 5484:         }
 5485:     }
 5486: }
 5487: 
 5488: sub get_groups_roles {
 5489:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5490:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5491:                   (ref($rolecodes) eq 'ARRAY') && 
 5492:                   (ref($groups_roles) eq 'HASH')); 
 5493:     if (keys(%{$cdom_courseroles}) > 0) {
 5494:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5495:         if ($cdom ne '' && $cnum ne '') {
 5496:             foreach my $key (keys(%{$cdom_courseroles})) {
 5497:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5498:                     my $crsrole = $1;
 5499:                     my $crssec = $2;
 5500:                     if ($crsrole =~ /^cr/) {
 5501:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5502:                             push(@{$rolecodes},'cr');
 5503:                         }
 5504:                     } else {
 5505:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5506:                             push(@{$rolecodes},$crsrole);
 5507:                         }
 5508:                     }
 5509:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5510:                     if ($crssec ne '') {
 5511:                         $rolekey .= "/$crssec";
 5512:                     }
 5513:                     $rolekey .= './';
 5514:                     $groups_roles->{$rolekey} = $rolecodes;
 5515:                 }
 5516:             }
 5517:         }
 5518:     }
 5519:     return;
 5520: }
 5521: 
 5522: sub delete_env_groupprivs {
 5523:     my ($where,$courseroles,$possroles) = @_;
 5524:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5525:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5526:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5527:         %{$courseroles->{$udom}} =
 5528:             &get_my_roles('','','userroles',['active'],
 5529:                           $possroles,[$udom],1);
 5530:     }
 5531:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5532:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5533:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5534:             my $area = '/'.$cdom.'/'.$cnum;
 5535:             my $privkey = "user.priv.$crsrole.$area";
 5536:             if ($crssec ne '') {
 5537:                 $privkey .= '/'.$crssec;
 5538:             }
 5539:             $privkey .= ".$area/$group";
 5540:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5541:         }
 5542:     }
 5543:     return;
 5544: }
 5545: 
 5546: sub check_adhoc_privs {
 5547:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5548:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5549:     my $setprivs;
 5550:     if ($env{$cckey}) {
 5551:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5552:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5553:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5554:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5555:             $setprivs = 1;
 5556:         }
 5557:     } else {
 5558:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5559:         $setprivs = 1;
 5560:     }
 5561:     return $setprivs;
 5562: }
 5563: 
 5564: sub set_adhoc_privileges {
 5565: # role can be cc or ca
 5566:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5567:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5568:     my $spec = $role.'.'.$area;
 5569:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5570:                                   $env{'user.name'},1);
 5571:     my %ccrole = ();
 5572:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5573:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5574:     &appenv(\%userroles,[$role,'cm']);
 5575:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5576:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5577:         &appenv( {'request.role'        => $spec,
 5578:                   'request.role.domain' => $dcdom,
 5579:                   'request.course.sec'  => ''
 5580:                  }
 5581:                );
 5582:         my $tadv=0;
 5583:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5584:         &appenv({'request.role.adv'    => $tadv});
 5585:     }
 5586: }
 5587: 
 5588: # --------------------------------------------------------------- get interface
 5589: 
 5590: sub get {
 5591:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5592:    my $items='';
 5593:    foreach my $item (@$storearr) {
 5594:        $items.=&escape($item).'&';
 5595:    }
 5596:    $items=~s/\&$//;
 5597:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5598:    if (!$uname) { $uname=$env{'user.name'}; }
 5599:    my $uhome=&homeserver($uname,$udomain);
 5600: 
 5601:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5602:    my @pairs=split(/\&/,$rep);
 5603:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5604:      return @pairs;
 5605:    }
 5606:    my %returnhash=();
 5607:    my $i=0;
 5608:    foreach my $item (@$storearr) {
 5609:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5610:       $i++;
 5611:    }
 5612:    return %returnhash;
 5613: }
 5614: 
 5615: # --------------------------------------------------------------- del interface
 5616: 
 5617: sub del {
 5618:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5619:    my $items='';
 5620:    foreach my $item (@$storearr) {
 5621:        $items.=&escape($item).'&';
 5622:    }
 5623: 
 5624:    $items=~s/\&$//;
 5625:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5626:    if (!$uname) { $uname=$env{'user.name'}; }
 5627:    my $uhome=&homeserver($uname,$udomain);
 5628:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5629: }
 5630: 
 5631: # -------------------------------------------------------------- dump interface
 5632: 
 5633: sub unserialize {
 5634:     my ($rep, $escapedkeys) = @_;
 5635: 
 5636:     return {} if $rep =~ /^error/;
 5637: 
 5638:     my %returnhash=();
 5639: 	foreach my $item (split(/\&/,$rep)) {
 5640: 	    my ($key, $value) = split(/=/, $item, 2);
 5641: 	    $key = unescape($key) unless $escapedkeys;
 5642: 	    next if $key =~ /^error: 2 /;
 5643: 	    $returnhash{$key} = &thaw_unescape($value);
 5644: 	}
 5645:     #return %returnhash;
 5646:     return \%returnhash;
 5647: }        
 5648: 
 5649: # see Lond::dump_with_regexp
 5650: # if $escapedkeys hash keys won't get unescaped.
 5651: sub dump {
 5652:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5653:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5654:     if (!$uname) { $uname=$env{'user.name'}; }
 5655:     my $uhome=&homeserver($uname,$udomain);
 5656: 
 5657:     if ($regexp) {
 5658:         $regexp=&escape($regexp);
 5659:     } else {
 5660:         $regexp='.';
 5661:     }
 5662:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5663:         # user is hosted on this machine
 5664:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5665:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5666:         return %{unserialize($reply, $escapedkeys)};
 5667:     }
 5668:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5669:     my @pairs=split(/\&/,$rep);
 5670:     my %returnhash=();
 5671:     if (!($rep =~ /^error/ )) {
 5672: 	foreach my $item (@pairs) {
 5673: 	    my ($key,$value)=split(/=/,$item,2);
 5674:         $key = unescape($key) unless $escapedkeys;
 5675:         #$key = &unescape($key);
 5676: 	    next if ($key =~ /^error: 2 /);
 5677: 	    $returnhash{$key}=&thaw_unescape($value);
 5678: 	}
 5679:     }
 5680:     return %returnhash;
 5681: }
 5682: 
 5683: 
 5684: # --------------------------------------------------------- dumpstore interface
 5685: 
 5686: sub dumpstore {
 5687:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5688:    # same as dump but keys must be escaped. They may contain colon separated
 5689:    # lists of values that may themself contain colons (e.g. symbs).
 5690:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5691: }
 5692: 
 5693: # -------------------------------------------------------------- keys interface
 5694: 
 5695: sub getkeys {
 5696:    my ($namespace,$udomain,$uname)=@_;
 5697:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5698:    if (!$uname) { $uname=$env{'user.name'}; }
 5699:    my $uhome=&homeserver($uname,$udomain);
 5700:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5701:    my @keyarray=();
 5702:    foreach my $key (split(/\&/,$rep)) {
 5703:       next if ($key =~ /^error: 2 /);
 5704:       push(@keyarray,&unescape($key));
 5705:    }
 5706:    return @keyarray;
 5707: }
 5708: 
 5709: # --------------------------------------------------------------- currentdump
 5710: sub currentdump {
 5711:    my ($courseid,$sdom,$sname)=@_;
 5712:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5713:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5714:    $sname    = $env{'user.name'}         if (! defined($sname));
 5715:    my $uhome = &homeserver($sname,$sdom);
 5716:    my $rep;
 5717: 
 5718:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5719:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5720:                    $courseid)));
 5721:    } else {
 5722:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5723:    }
 5724: 
 5725:    return if ($rep =~ /^(error:|no_such_host)/);
 5726:    #
 5727:    my %returnhash=();
 5728:    #
 5729:    if ($rep eq "unknown_cmd") { 
 5730:        # an old lond will not know currentdump
 5731:        # Do a dump and make it look like a currentdump
 5732:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5733:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5734:        my %hash = @tmp;
 5735:        @tmp=();
 5736:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5737:    } else {
 5738:        my @pairs=split(/\&/,$rep);
 5739:        foreach my $pair (@pairs) {
 5740:            my ($key,$value)=split(/=/,$pair,2);
 5741:            my ($symb,$param) = split(/:/,$key);
 5742:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5743:                                                         &thaw_unescape($value);
 5744:        }
 5745:    }
 5746:    return %returnhash;
 5747: }
 5748: 
 5749: sub convert_dump_to_currentdump{
 5750:     my %hash = %{shift()};
 5751:     my %returnhash;
 5752:     # Code ripped from lond, essentially.  The only difference
 5753:     # here is the unescaping done by lonnet::dump().  Conceivably
 5754:     # we might run in to problems with parameter names =~ /^v\./
 5755:     while (my ($key,$value) = each(%hash)) {
 5756:         my ($v,$symb,$param) = split(/:/,$key);
 5757: 	$symb  = &unescape($symb);
 5758: 	$param = &unescape($param);
 5759:         next if ($v eq 'version' || $symb eq 'keys');
 5760:         next if (exists($returnhash{$symb}) &&
 5761:                  exists($returnhash{$symb}->{$param}) &&
 5762:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5763:         $returnhash{$symb}->{$param}=$value;
 5764:         $returnhash{$symb}->{'v.'.$param}=$v;
 5765:     }
 5766:     #
 5767:     # Remove all of the keys in the hashes which keep track of
 5768:     # the version of the parameter.
 5769:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5770:         # use a foreach because we are going to delete from the hash.
 5771:         foreach my $key (keys(%$param_hash)) {
 5772:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5773:         }
 5774:     }
 5775:     return \%returnhash;
 5776: }
 5777: 
 5778: # ------------------------------------------------------ critical inc interface
 5779: 
 5780: sub cinc {
 5781:     return &inc(@_,'critical');
 5782: }
 5783: 
 5784: # --------------------------------------------------------------- inc interface
 5785: 
 5786: sub inc {
 5787:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5788:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5789:     if (!$uname) { $uname=$env{'user.name'}; }
 5790:     my $uhome=&homeserver($uname,$udomain);
 5791:     my $items='';
 5792:     if (! ref($store)) {
 5793:         # got a single value, so use that instead
 5794:         $items = &escape($store).'=&';
 5795:     } elsif (ref($store) eq 'SCALAR') {
 5796:         $items = &escape($$store).'=&';        
 5797:     } elsif (ref($store) eq 'ARRAY') {
 5798:         $items = join('=&',map {&escape($_);} @{$store});
 5799:     } elsif (ref($store) eq 'HASH') {
 5800:         while (my($key,$value) = each(%{$store})) {
 5801:             $items.= &escape($key).'='.&escape($value).'&';
 5802:         }
 5803:     }
 5804:     $items=~s/\&$//;
 5805:     if ($critical) {
 5806: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5807:     } else {
 5808: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5809:     }
 5810: }
 5811: 
 5812: # --------------------------------------------------------------- put interface
 5813: 
 5814: sub put {
 5815:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5816:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5817:    if (!$uname) { $uname=$env{'user.name'}; }
 5818:    my $uhome=&homeserver($uname,$udomain);
 5819:    my $items='';
 5820:    foreach my $item (keys(%$storehash)) {
 5821:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5822:    }
 5823:    $items=~s/\&$//;
 5824:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5825: }
 5826: 
 5827: # ------------------------------------------------------------ newput interface
 5828: 
 5829: sub newput {
 5830:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5831:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5832:    if (!$uname) { $uname=$env{'user.name'}; }
 5833:    my $uhome=&homeserver($uname,$udomain);
 5834:    my $items='';
 5835:    foreach my $key (keys(%$storehash)) {
 5836:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5837:    }
 5838:    $items=~s/\&$//;
 5839:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5840: }
 5841: 
 5842: # ---------------------------------------------------------  putstore interface
 5843: 
 5844: sub putstore {
 5845:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 5846:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5847:    if (!$uname) { $uname=$env{'user.name'}; }
 5848:    my $uhome=&homeserver($uname,$udomain);
 5849:    my $items='';
 5850:    foreach my $key (keys(%$storehash)) {
 5851:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5852:    }
 5853:    $items=~s/\&$//;
 5854:    my $esc_symb=&escape($symb);
 5855:    my $esc_v=&escape($version);
 5856:    my $reply =
 5857:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5858: 	      $uhome);
 5859:    if (($tolog) && ($reply eq 'ok')) {
 5860:        my $namevalue='';
 5861:        foreach my $key (keys(%{$storehash})) {
 5862:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5863:        }
 5864:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5865:                      '&host='.&escape($perlvar{'lonHostID'}).
 5866:                      '&version='.$esc_v.
 5867:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5868:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5869:    }
 5870:    if ($reply eq 'unknown_cmd') {
 5871:        # gfall back to way things use to be done
 5872:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5873: 			    $uname);
 5874:    }
 5875:    return $reply;
 5876: }
 5877: 
 5878: sub old_putstore {
 5879:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5880:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5881:     if (!$uname) { $uname=$env{'user.name'}; }
 5882:     my $uhome=&homeserver($uname,$udomain);
 5883:     my %newstorehash;
 5884:     foreach my $item (keys(%$storehash)) {
 5885: 	my $key = $version.':'.&escape($symb).':'.$item;
 5886: 	$newstorehash{$key} = $storehash->{$item};
 5887:     }
 5888:     my $items='';
 5889:     my %allitems = ();
 5890:     foreach my $item (keys(%newstorehash)) {
 5891: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5892: 	    my $key = $1.':keys:'.$2;
 5893: 	    $allitems{$key} .= $3.':';
 5894: 	}
 5895: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5896:     }
 5897:     foreach my $item (keys(%allitems)) {
 5898: 	$allitems{$item} =~ s/\:$//;
 5899: 	$items.= $item.'='.$allitems{$item}.'&';
 5900:     }
 5901:     $items=~s/\&$//;
 5902:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5903: }
 5904: 
 5905: # ------------------------------------------------------ critical put interface
 5906: 
 5907: sub cput {
 5908:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5909:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5910:    if (!$uname) { $uname=$env{'user.name'}; }
 5911:    my $uhome=&homeserver($uname,$udomain);
 5912:    my $items='';
 5913:    foreach my $item (keys(%$storehash)) {
 5914:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5915:    }
 5916:    $items=~s/\&$//;
 5917:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5918: }
 5919: 
 5920: # -------------------------------------------------------------- eget interface
 5921: 
 5922: sub eget {
 5923:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5924:    my $items='';
 5925:    foreach my $item (@$storearr) {
 5926:        $items.=&escape($item).'&';
 5927:    }
 5928:    $items=~s/\&$//;
 5929:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5930:    if (!$uname) { $uname=$env{'user.name'}; }
 5931:    my $uhome=&homeserver($uname,$udomain);
 5932:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5933:    my @pairs=split(/\&/,$rep);
 5934:    my %returnhash=();
 5935:    my $i=0;
 5936:    foreach my $item (@$storearr) {
 5937:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5938:       $i++;
 5939:    }
 5940:    return %returnhash;
 5941: }
 5942: 
 5943: # ------------------------------------------------------------ tmpput interface
 5944: sub tmpput {
 5945:     my ($storehash,$server,$context)=@_;
 5946:     my $items='';
 5947:     foreach my $item (keys(%$storehash)) {
 5948: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5949:     }
 5950:     $items=~s/\&$//;
 5951:     if (defined($context)) {
 5952:         $items .= ':'.&escape($context);
 5953:     }
 5954:     return &reply("tmpput:$items",$server);
 5955: }
 5956: 
 5957: # ------------------------------------------------------------ tmpget interface
 5958: sub tmpget {
 5959:     my ($token,$server)=@_;
 5960:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5961:     my $rep=&reply("tmpget:$token",$server);
 5962:     my %returnhash;
 5963:     foreach my $item (split(/\&/,$rep)) {
 5964: 	my ($key,$value)=split(/=/,$item);
 5965:         next if ($key =~ /^error: 2 /);
 5966: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5967:     }
 5968:     return %returnhash;
 5969: }
 5970: 
 5971: # ------------------------------------------------------------ tmpdel interface
 5972: sub tmpdel {
 5973:     my ($token,$server)=@_;
 5974:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5975:     return &reply("tmpdel:$token",$server);
 5976: }
 5977: 
 5978: # ------------------------------------------------------------ get_timebased_id 
 5979: 
 5980: sub get_timebased_id {
 5981:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5982:         $maxtries) = @_;
 5983:     my ($newid,$error,$dellock);
 5984:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5985:         return ('','ok','invalid call to get suffix');
 5986:     }
 5987: 
 5988: # set defaults for any optional args for which values were not supplied
 5989:     if ($who eq '') {
 5990:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5991:     }
 5992:     if (!$locktries) {
 5993:         $locktries = 3;
 5994:     }
 5995:     if (!$maxtries) {
 5996:         $maxtries = 10;
 5997:     }
 5998:     
 5999:     if (($cdom eq '') || ($cnum eq '')) {
 6000:         if ($env{'request.course.id'}) {
 6001:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6002:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6003:         }
 6004:         if (($cdom eq '') || ($cnum eq '')) {
 6005:             return ('','ok','call to get suffix not in course context');
 6006:         }
 6007:     }
 6008: 
 6009: # construct locking item
 6010:     my $lockhash = {
 6011:                       $prefix."\0".'locked_'.$keyid => $who,
 6012:                    };
 6013:     my $tries = 0;
 6014: 
 6015: # attempt to get lock on nohist_$namespace file
 6016:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6017:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6018:         $tries ++;
 6019:         sleep 1;
 6020:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6021:     }
 6022: 
 6023: # attempt to get unique identifier, based on current timestamp
 6024:     if ($gotlock eq 'ok') {
 6025:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6026:         my $id = time;
 6027:         $newid = $id;
 6028:         if ($idtype eq 'addcode') {
 6029:             $newid .= &sixnum_code();
 6030:         }
 6031:         my $idtries = 0;
 6032:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6033:             if ($idtype eq 'concat') {
 6034:                 $newid = $id.$idtries;
 6035:             } elsif ($idtype eq 'addcode') {
 6036:                 $newid = $newid.&sixnum_code();
 6037:             } else {
 6038:                 $newid ++;
 6039:             }
 6040:             $idtries ++;
 6041:         }
 6042:         if (!exists($inuse{$prefix."\0".$newid})) {
 6043:             my %new_item =  (
 6044:                               $prefix."\0".$newid => $who,
 6045:                             );
 6046:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6047:                                                  $cdom,$cnum);
 6048:             if ($putresult ne 'ok') {
 6049:                 undef($newid);
 6050:                 $error = 'error saving new item: '.$putresult;
 6051:             }
 6052:         } else {
 6053:              undef($newid);
 6054:              $error = ('error: no unique suffix available for the new item ');
 6055:         }
 6056: #  remove lock
 6057:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6058:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6059:     } else {
 6060:         $error = "error: could not obtain lockfile\n";
 6061:         $dellock = 'ok';
 6062:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6063:             $dellock = 'nolock';
 6064:         }
 6065:     }
 6066:     return ($newid,$dellock,$error);
 6067: }
 6068: 
 6069: sub sixnum_code {
 6070:     my $code;
 6071:     for (0..6) {
 6072:         $code .= int( rand(9) );
 6073:     }
 6074:     return $code;
 6075: }
 6076: 
 6077: # -------------------------------------------------- portfolio access checking
 6078: 
 6079: sub portfolio_access {
 6080:     my ($requrl,$clientip) = @_;
 6081:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6082:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6083:     if ($result) {
 6084:         my %setters;
 6085:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6086:             my ($startblock,$endblock) =
 6087:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6088:             if ($startblock && $endblock) {
 6089:                 return 'B';
 6090:             }
 6091:         } else {
 6092:             my ($startblock,$endblock) =
 6093:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6094:             if ($startblock && $endblock) {
 6095:                 return 'B';
 6096:             }
 6097:         }
 6098:     }
 6099:     if ($result eq 'ok') {
 6100:        return 'F';
 6101:     } elsif ($result =~ /^[^:]+:guest_/) {
 6102:        return 'A';
 6103:     }
 6104:     return '';
 6105: }
 6106: 
 6107: sub get_portfolio_access {
 6108:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6109: 
 6110:     if (!ref($access_hash)) {
 6111: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6112: 	my %access_controls = &get_access_controls($current_perms,$group,
 6113: 						   $file_name);
 6114: 	$access_hash = $access_controls{$file_name};
 6115:     }
 6116: 
 6117:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6118:     my $now = time;
 6119:     if (ref($access_hash) eq 'HASH') {
 6120:         foreach my $key (keys(%{$access_hash})) {
 6121:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6122:             if ($start > $now) {
 6123:                 next;
 6124:             }
 6125:             if ($end && $end<$now) {
 6126:                 next;
 6127:             }
 6128:             if ($scope eq 'public') {
 6129:                 $public = $key;
 6130:                 last;
 6131:             } elsif ($scope eq 'guest') {
 6132:                 $guest = $key;
 6133:             } elsif ($scope eq 'domains') {
 6134:                 push(@domains,$key);
 6135:             } elsif ($scope eq 'users') {
 6136:                 push(@users,$key);
 6137:             } elsif ($scope eq 'course') {
 6138:                 push(@courses,$key);
 6139:             } elsif ($scope eq 'group') {
 6140:                 push(@groups,$key);
 6141:             } elsif ($scope eq 'ip') {
 6142:                 push(@ips,$key);
 6143:             }
 6144:         }
 6145:         if ($public) {
 6146:             return 'ok';
 6147:         } elsif (@ips > 0) {
 6148:             my $allowed;
 6149:             foreach my $ipkey (@ips) {
 6150:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6151:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6152:                         $allowed = 1;
 6153:                         last; 
 6154:                     }
 6155:                 }
 6156:             }
 6157:             if ($allowed) {
 6158:                 return 'ok';
 6159:             }
 6160:         }
 6161:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6162:             if ($guest) {
 6163:                 return $guest;
 6164:             }
 6165:         } else {
 6166:             if (@domains > 0) {
 6167:                 foreach my $domkey (@domains) {
 6168:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6169:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6170:                             return 'ok';
 6171:                         }
 6172:                     }
 6173:                 }
 6174:             }
 6175:             if (@users > 0) {
 6176:                 foreach my $userkey (@users) {
 6177:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6178:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6179:                             if (ref($item) eq 'HASH') {
 6180:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6181:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6182:                                     return 'ok';
 6183:                                 }
 6184:                             }
 6185:                         }
 6186:                     } 
 6187:                 }
 6188:             }
 6189:             my %roleshash;
 6190:             my @courses_and_groups = @courses;
 6191:             push(@courses_and_groups,@groups); 
 6192:             if (@courses_and_groups > 0) {
 6193:                 my (%allgroups,%allroles); 
 6194:                 my ($start,$end,$role,$sec,$group);
 6195:                 foreach my $envkey (%env) {
 6196:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6197:                         my $cid = $2.'_'.$3; 
 6198:                         if ($1 eq 'gr') {
 6199:                             $group = $4;
 6200:                             $allgroups{$cid}{$group} = $env{$envkey};
 6201:                         } else {
 6202:                             if ($4 eq '') {
 6203:                                 $sec = 'none';
 6204:                             } else {
 6205:                                 $sec = $4;
 6206:                             }
 6207:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6208:                         }
 6209:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6210:                         my $cid = $2.'_'.$3;
 6211:                         if ($4 eq '') {
 6212:                             $sec = 'none';
 6213:                         } else {
 6214:                             $sec = $4;
 6215:                         }
 6216:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6217:                     }
 6218:                 }
 6219:                 if (keys(%allroles) == 0) {
 6220:                     return;
 6221:                 }
 6222:                 foreach my $key (@courses_and_groups) {
 6223:                     my %content = %{$$access_hash{$key}};
 6224:                     my $cnum = $content{'number'};
 6225:                     my $cdom = $content{'domain'};
 6226:                     my $cid = $cdom.'_'.$cnum;
 6227:                     if (!exists($allroles{$cid})) {
 6228:                         next;
 6229:                     }    
 6230:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6231:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6232:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6233:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6234:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6235:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6236:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6237:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6238:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6239:                                         if (grep/^all$/,@sections) {
 6240:                                             return 'ok';
 6241:                                         } else {
 6242:                                             if (grep/^$sec$/,@sections) {
 6243:                                                 return 'ok';
 6244:                                             }
 6245:                                         }
 6246:                                     }
 6247:                                 }
 6248:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6249:                                     if (grep/^none$/,@groups) {
 6250:                                         return 'ok';
 6251:                                     }
 6252:                                 } else {
 6253:                                     if (grep/^all$/,@groups) {
 6254:                                         return 'ok';
 6255:                                     } 
 6256:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6257:                                         if (grep/^$group$/,@groups) {
 6258:                                             return 'ok';
 6259:                                         }
 6260:                                     }
 6261:                                 } 
 6262:                             }
 6263:                         }
 6264:                     }
 6265:                 }
 6266:             }
 6267:             if ($guest) {
 6268:                 return $guest;
 6269:             }
 6270:         }
 6271:     }
 6272:     return;
 6273: }
 6274: 
 6275: sub course_group_datechecker {
 6276:     my ($dates,$now,$status) = @_;
 6277:     my ($start,$end) = split(/\./,$dates);
 6278:     if (!$start && !$end) {
 6279:         return 'ok';
 6280:     }
 6281:     if (grep/^active$/,@{$status}) {
 6282:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6283:             return 'ok';
 6284:         }
 6285:     }
 6286:     if (grep/^previous$/,@{$status}) {
 6287:         if ($end > $now ) {
 6288:             return 'ok';
 6289:         }
 6290:     }
 6291:     if (grep/^future$/,@{$status}) {
 6292:         if ($start > $now) {
 6293:             return 'ok';
 6294:         }
 6295:     }
 6296:     return; 
 6297: }
 6298: 
 6299: sub parse_portfolio_url {
 6300:     my ($url) = @_;
 6301: 
 6302:     my ($type,$udom,$unum,$group,$file_name);
 6303:     
 6304:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6305: 	$type = 1;
 6306:         $udom = $1;
 6307:         $unum = $2;
 6308:         $file_name = $3;
 6309:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6310: 	$type = 2;
 6311:         $udom = $1;
 6312:         $unum = $2;
 6313:         $group = $3;
 6314:         $file_name = $3.'/'.$4;
 6315:     }
 6316:     if (wantarray) {
 6317: 	return ($type,$udom,$unum,$file_name,$group);
 6318:     }
 6319:     return $type;
 6320: }
 6321: 
 6322: sub is_portfolio_url {
 6323:     my ($url) = @_;
 6324:     return scalar(&parse_portfolio_url($url));
 6325: }
 6326: 
 6327: sub is_portfolio_file {
 6328:     my ($file) = @_;
 6329:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6330:         return 1;
 6331:     }
 6332:     return;
 6333: }
 6334: 
 6335: sub usertools_access {
 6336:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6337:     my ($access,%tools);
 6338:     if ($context eq '') {
 6339:         $context = 'tools';
 6340:     }
 6341:     if ($context eq 'requestcourses') {
 6342:         %tools = (
 6343:                       official   => 1,
 6344:                       unofficial => 1,
 6345:                       community  => 1,
 6346:                       textbook   => 1,
 6347:                  );
 6348:     } elsif ($context eq 'requestauthor') {
 6349:         %tools = (
 6350:                       requestauthor => 1,
 6351:                  );
 6352:     } else {
 6353:         %tools = (
 6354:                       aboutme   => 1,
 6355:                       blog      => 1,
 6356:                       webdav    => 1,
 6357:                       portfolio => 1,
 6358:                  );
 6359:     }
 6360:     return if (!defined($tools{$tool}));
 6361: 
 6362:     if (($udom eq '') || ($uname eq '')) {
 6363:         $udom = $env{'user.domain'};
 6364:         $uname = $env{'user.name'};
 6365:     }
 6366: 
 6367:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6368:         if ($action ne 'reload') {
 6369:             if ($context eq 'requestcourses') {
 6370:                 return $env{'environment.canrequest.'.$tool};
 6371:             } elsif ($context eq 'requestauthor') {
 6372:                 return $env{'environment.canrequest.author'};
 6373:             } else {
 6374:                 return $env{'environment.availabletools.'.$tool};
 6375:             }
 6376:         }
 6377:     }
 6378: 
 6379:     my ($toolstatus,$inststatus,$envkey);
 6380:     if ($context eq 'requestauthor') {
 6381:         $envkey = $context; 
 6382:     } else {
 6383:         $envkey = $context.'.'.$tool;
 6384:     }
 6385: 
 6386:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6387:          ($action ne 'reload')) {
 6388:         $toolstatus = $env{'environment.'.$envkey};
 6389:         $inststatus = $env{'environment.inststatus'};
 6390:     } else {
 6391:         if (ref($userenvref) eq 'HASH') {
 6392:             $toolstatus = $userenvref->{$envkey};
 6393:             $inststatus = $userenvref->{'inststatus'};
 6394:         } else {
 6395:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6396:             $toolstatus = $userenv{$envkey};
 6397:             $inststatus = $userenv{'inststatus'};
 6398:         }
 6399:     }
 6400: 
 6401:     if ($toolstatus ne '') {
 6402:         if ($toolstatus) {
 6403:             $access = 1;
 6404:         } else {
 6405:             $access = 0;
 6406:         }
 6407:         return $access;
 6408:     }
 6409: 
 6410:     my ($is_adv,%domdef);
 6411:     if (ref($is_advref) eq 'HASH') {
 6412:         $is_adv = $is_advref->{'is_adv'};
 6413:     } else {
 6414:         $is_adv = &is_advanced_user($udom,$uname);
 6415:     }
 6416:     if (ref($domdefref) eq 'HASH') {
 6417:         %domdef = %{$domdefref};
 6418:     } else {
 6419:         %domdef = &get_domain_defaults($udom);
 6420:     }
 6421:     if (ref($domdef{$tool}) eq 'HASH') {
 6422:         if ($is_adv) {
 6423:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6424:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6425:                     $access = 1;
 6426:                 } else {
 6427:                     $access = 0;
 6428:                 }
 6429:                 return $access;
 6430:             }
 6431:         }
 6432:         if ($inststatus ne '') {
 6433:             my ($hasaccess,$hasnoaccess);
 6434:             foreach my $affiliation (split(/:/,$inststatus)) {
 6435:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6436:                     if ($domdef{$tool}{$affiliation}) {
 6437:                         $hasaccess = 1;
 6438:                     } else {
 6439:                         $hasnoaccess = 1;
 6440:                     }
 6441:                 }
 6442:             }
 6443:             if ($hasaccess || $hasnoaccess) {
 6444:                 if ($hasaccess) {
 6445:                     $access = 1;
 6446:                 } elsif ($hasnoaccess) {
 6447:                     $access = 0; 
 6448:                 }
 6449:                 return $access;
 6450:             }
 6451:         } else {
 6452:             if ($domdef{$tool}{'default'} ne '') {
 6453:                 if ($domdef{$tool}{'default'}) {
 6454:                     $access = 1;
 6455:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6456:                     $access = 0;
 6457:                 }
 6458:                 return $access;
 6459:             }
 6460:         }
 6461:     } else {
 6462:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6463:             $access = 1;
 6464:         } else {
 6465:             $access = 0;
 6466:         }
 6467:         return $access;
 6468:     }
 6469: }
 6470: 
 6471: sub is_course_owner {
 6472:     my ($cdom,$cnum,$udom,$uname) = @_;
 6473:     if (($udom eq '') || ($uname eq '')) {
 6474:         $udom = $env{'user.domain'};
 6475:         $uname = $env{'user.name'};
 6476:     }
 6477:     unless (($udom eq '') || ($uname eq '')) {
 6478:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6479:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6480:                 return 1;
 6481:             } else {
 6482:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6483:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6484:                     return 1;
 6485:                 }
 6486:             }
 6487:         }
 6488:     }
 6489:     return;
 6490: }
 6491: 
 6492: sub is_advanced_user {
 6493:     my ($udom,$uname) = @_;
 6494:     if ($udom ne '' && $uname ne '') {
 6495:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6496:             if (wantarray) {
 6497:                 return ($env{'user.adv'},$env{'user.author'});
 6498:             } else {
 6499:                 return $env{'user.adv'};
 6500:             }
 6501:         }
 6502:     }
 6503:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6504:     my %allroles;
 6505:     my ($is_adv,$is_author);
 6506:     foreach my $role (keys(%roleshash)) {
 6507:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6508:         my $area = '/'.$tdomain.'/'.$trest;
 6509:         if ($sec ne '') {
 6510:             $area .= '/'.$sec;
 6511:         }
 6512:         if (($area ne '') && ($trole ne '')) {
 6513:             my $spec=$trole.'.'.$area;
 6514:             if ($trole =~ /^cr\//) {
 6515:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6516:             } elsif ($trole ne 'gr') {
 6517:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6518:             }
 6519:             if ($trole eq 'au') {
 6520:                 $is_author = 1;
 6521:             }
 6522:         }
 6523:     }
 6524:     foreach my $role (keys(%allroles)) {
 6525:         last if ($is_adv);
 6526:         foreach my $item (split(/:/,$allroles{$role})) {
 6527:             if ($item ne '') {
 6528:                 my ($privilege,$restrictions)=split(/&/,$item);
 6529:                 if ($privilege eq 'adv') {
 6530:                     $is_adv = 1;
 6531:                     last;
 6532:                 }
 6533:             }
 6534:         }
 6535:     }
 6536:     if (wantarray) {
 6537:         return ($is_adv,$is_author);
 6538:     }
 6539:     return $is_adv;
 6540: }
 6541: 
 6542: sub check_can_request {
 6543:     my ($dom,$can_request,$request_domains) = @_;
 6544:     my $canreq = 0;
 6545:     my ($types,$typename) = &Apache::loncommon::course_types();
 6546:     my @options = ('approval','validate','autolimit');
 6547:     my $optregex = join('|',@options);
 6548:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6549:         foreach my $type (@{$types}) {
 6550:             if (&usertools_access($env{'user.name'},
 6551:                                   $env{'user.domain'},
 6552:                                   $type,undef,'requestcourses')) {
 6553:                 $canreq ++;
 6554:                 if (ref($request_domains) eq 'HASH') {
 6555:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6556:                 }
 6557:                 if ($dom eq $env{'user.domain'}) {
 6558:                     $can_request->{$type} = 1;
 6559:                 }
 6560:             }
 6561:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6562:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6563:                 if (@curr > 0) {
 6564:                     foreach my $item (@curr) {
 6565:                         if (ref($request_domains) eq 'HASH') {
 6566:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6567:                             if ($otherdom ne '') {
 6568:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6569:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6570:                                         push(@{$request_domains->{$type}},$otherdom);
 6571:                                     }
 6572:                                 } else {
 6573:                                     push(@{$request_domains->{$type}},$otherdom);
 6574:                                 }
 6575:                             }
 6576:                         }
 6577:                     }
 6578:                     unless($dom eq $env{'user.domain'}) {
 6579:                         $canreq ++;
 6580:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6581:                             $can_request->{$type} = 1;
 6582:                         }
 6583:                     }
 6584:                 }
 6585:             }
 6586:         }
 6587:     }
 6588:     return $canreq;
 6589: }
 6590: 
 6591: # ---------------------------------------------- Custom access rule evaluation
 6592: 
 6593: sub customaccess {
 6594:     my ($priv,$uri)=@_;
 6595:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6596:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6597:     $udom = &LONCAPA::clean_domain($udom);
 6598:     $ucrs = &LONCAPA::clean_username($ucrs);
 6599:     my $access=0;
 6600:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6601: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6602: 	if ($type eq 'user') {
 6603: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6604: 		my ($tdom,$tuname)=split(m{/},$scope);
 6605: 		if ($tdom) {
 6606: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6607: 		}
 6608: 		if ($tuname) {
 6609: 		    if ($tuname ne $env{'user.name'}) { next; }
 6610: 		}
 6611: 		$access=($effect eq 'allow');
 6612: 		last;
 6613: 	    }
 6614: 	} else {
 6615: 	    if ($role) {
 6616: 		if ($role ne $urole) { next; }
 6617: 	    }
 6618: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6619: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6620: 		if ($tdom) {
 6621: 		    if ($tdom ne $udom) { next; }
 6622: 		}
 6623: 		if ($tcrs) {
 6624: 		    if ($tcrs ne $ucrs) { next; }
 6625: 		}
 6626: 		if ($tsec) {
 6627: 		    if ($tsec ne $usec) { next; }
 6628: 		}
 6629: 		$access=($effect eq 'allow');
 6630: 		last;
 6631: 	    }
 6632: 	    if ($realm eq '' && $role eq '') {
 6633: 		$access=($effect eq 'allow');
 6634: 	    }
 6635: 	}
 6636:     }
 6637:     return $access;
 6638: }
 6639: 
 6640: # ------------------------------------------------- Check for a user privilege
 6641: 
 6642: sub allowed {
 6643:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 6644:     my $ver_orguri=$uri;
 6645:     $uri=&deversion($uri);
 6646:     my $orguri=$uri;
 6647:     $uri=&declutter($uri);
 6648: 
 6649:     if ($priv eq 'evb') {
 6650: # Evade communication block restrictions for specified role in a course
 6651:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6652:             return $1;
 6653:         } else {
 6654:             return;
 6655:         }
 6656:     }
 6657: 
 6658:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6659: # Free bre access to adm and meta resources
 6660:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6661: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6662: 	&& ($priv eq 'bre')) {
 6663: 	return 'F';
 6664:     }
 6665: 
 6666: # Free bre access to user's own portfolio contents
 6667:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6668:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6669: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6670:         my %setters;
 6671:         my ($startblock,$endblock) = 
 6672:             &Apache::loncommon::blockcheck(\%setters,'port');
 6673:         if ($startblock && $endblock) {
 6674:             return 'B';
 6675:         } else {
 6676:             return 'F';
 6677:         }
 6678:     }
 6679: 
 6680: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6681:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6682:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6683:         if (exists($env{'request.course.id'})) {
 6684:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6685:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6686:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6687:                 my $courseprivid=$env{'request.course.id'};
 6688:                 $courseprivid=~s/\_/\//;
 6689:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6690:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6691:                     return $1; 
 6692:                 } else {
 6693:                     if ($env{'request.course.sec'}) {
 6694:                         $courseprivid.='/'.$env{'request.course.sec'};
 6695:                     }
 6696:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6697:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6698:                         return $2;
 6699:                     }
 6700:                 }
 6701:             }
 6702:         }
 6703:     }
 6704: 
 6705: # Free bre to public access
 6706: 
 6707:     if ($priv eq 'bre') {
 6708:         my $copyright=&metadata($uri,'copyright');
 6709: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6710:            return 'F'; 
 6711:         }
 6712:         if ($copyright eq 'priv') {
 6713:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6714: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6715: 		return '';
 6716:             }
 6717:         }
 6718:         if ($copyright eq 'domain') {
 6719:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6720: 	    unless (($env{'user.domain'} eq $1) ||
 6721:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6722: 		return '';
 6723:             }
 6724:         }
 6725:         if ($env{'request.role'}=~ /li\.\//) {
 6726:             # Library role, so allow browsing of resources in this domain.
 6727:             return 'F';
 6728:         }
 6729:         if ($copyright eq 'custom') {
 6730: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6731:         }
 6732:     }
 6733:     # Domain coordinator is trying to create a course
 6734:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6735:         # uri is the requested domain in this case.
 6736:         # comparison to 'request.role.domain' shows if the user has selected
 6737:         # a role of dc for the domain in question.
 6738:         return 'F' if ($uri eq $env{'request.role.domain'});
 6739:     }
 6740: 
 6741:     my $thisallowed='';
 6742:     my $statecond=0;
 6743:     my $courseprivid='';
 6744: 
 6745:     my $ownaccess;
 6746:     # Community Coordinator or Assistant Co-author browsing resource space.
 6747:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6748:         if ($uri eq '') {
 6749:             $ownaccess = 1;
 6750:         } else {
 6751:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6752:                 my $udom = $env{'user.domain'};
 6753:                 my $uname = $env{'user.name'};
 6754:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6755:                     $ownaccess = 1;
 6756:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6757:                     unless ($uri =~ m{\.\./}) {
 6758:                         $ownaccess = 1;
 6759:                     }
 6760:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6761:                     my $now = time;
 6762:                     if ($uri =~ m{^([^/]+)/?$}) {
 6763:                         my $adom = $1;
 6764:                         foreach my $key (keys(%env)) {
 6765:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6766:                                 my ($start,$end) = split('.',$env{$key});
 6767:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6768:                                     $ownaccess = 1;
 6769:                                     last;
 6770:                                 }
 6771:                             }
 6772:                         }
 6773:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6774:                         my $adom = $1;
 6775:                         my $aname = $2;
 6776:                         foreach my $role ('ca','aa') { 
 6777:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6778:                                 my ($start,$end) =
 6779:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6780:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6781:                                     $ownaccess = 1;
 6782:                                     last;
 6783:                                 }
 6784:                             }
 6785:                         }
 6786:                     }
 6787:                 }
 6788:             }
 6789:         }
 6790:     }
 6791: 
 6792: # Course
 6793: 
 6794:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6795:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6796:             $thisallowed.=$1;
 6797:         }
 6798:     }
 6799: 
 6800: # Domain
 6801: 
 6802:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6803:        =~/\Q$priv\E\&([^\:]*)/) {
 6804:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6805:             $thisallowed.=$1;
 6806:         }
 6807:     }
 6808: 
 6809: # User who is not author or co-author might still be able to edit
 6810: # resource of an author in the domain (e.g., if Domain Coordinator).
 6811:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6812:         (&allowed('mdc',$env{'request.course.id'}))) {
 6813:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6814:             $thisallowed.=$1;
 6815:         }
 6816:     }
 6817: 
 6818: # Course: uri itself is a course
 6819:     my $courseuri=$uri;
 6820:     $courseuri=~s/\_(\d)/\/$1/;
 6821:     $courseuri=~s/^([^\/])/\/$1/;
 6822: 
 6823:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6824:        =~/\Q$priv\E\&([^\:]*)/) {
 6825:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6826:             $thisallowed.=$1;
 6827:         }
 6828:     }
 6829: 
 6830: # URI is an uploaded document for this course, default permissions don't matter
 6831: # not allowing 'edit' access (editupload) to uploaded course docs
 6832:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6833: 	$thisallowed='';
 6834:         my ($match)=&is_on_map($uri);
 6835:         if ($match) {
 6836:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6837:                   =~/\Q$priv\E\&([^\:]*)/) {
 6838:                 my $value = $1;
 6839:                 if ($noblockcheck) {
 6840:                     $thisallowed.=$value;
 6841:                 } else {
 6842:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6843:                     if (@blockers > 0) {
 6844:                         $thisallowed = 'B';
 6845:                     } else {
 6846:                         $thisallowed.=$value;
 6847:                     }
 6848:                 }
 6849:             }
 6850:         } else {
 6851:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6852:             if ($refuri) {
 6853:                 if ($refuri =~ m|^/adm/|) {
 6854:                     $thisallowed='F';
 6855:                 } else {
 6856:                     $refuri=&declutter($refuri);
 6857:                     my ($match) = &is_on_map($refuri);
 6858:                     if ($match) {
 6859:                         if ($noblockcheck) {
 6860:                             $thisallowed='F';
 6861:                         } else {
 6862:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6863:                             if (@blockers > 0) {
 6864:                                 $thisallowed = 'B';
 6865:                             } else {
 6866:                                 $thisallowed='F';
 6867:                             }
 6868:                         }
 6869:                     }
 6870:                 }
 6871:             }
 6872:         }
 6873:     }
 6874: 
 6875:     if ($priv eq 'bre'
 6876: 	&& $thisallowed ne 'F' 
 6877: 	&& $thisallowed ne '2'
 6878: 	&& &is_portfolio_url($uri)) {
 6879: 	$thisallowed = &portfolio_access($uri,$clientip);
 6880:     }
 6881: 
 6882: # Full access at system, domain or course-wide level? Exit.
 6883:     if ($thisallowed=~/F/) {
 6884: 	return 'F';
 6885:     }
 6886: 
 6887: # If this is generating or modifying users, exit with special codes
 6888: 
 6889:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6890: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6891: 	    my ($audom,$auname)=split('/',$uri);
 6892: # no author name given, so this just checks on the general right to make a co-author in this domain
 6893: 	    unless ($auname) { return $thisallowed; }
 6894: # an author name is given, so we are about to actually make a co-author for a certain account
 6895: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6896: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6897: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6898: 	}
 6899: 	return $thisallowed;
 6900:     }
 6901: #
 6902: # Gathered so far: system, domain and course wide privileges
 6903: #
 6904: # Course: See if uri or referer is an individual resource that is part of 
 6905: # the course
 6906: 
 6907:     if ($env{'request.course.id'}) {
 6908: 
 6909:        $courseprivid=$env{'request.course.id'};
 6910:        if ($env{'request.course.sec'}) {
 6911:           $courseprivid.='/'.$env{'request.course.sec'};
 6912:        }
 6913:        $courseprivid=~s/\_/\//;
 6914:        my $checkreferer=1;
 6915:        my ($match,$cond)=&is_on_map($uri);
 6916:        if ($match) {
 6917:            $statecond=$cond;
 6918:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6919:                =~/\Q$priv\E\&([^\:]*)/) {
 6920:                my $value = $1;
 6921:                if ($priv eq 'bre') {
 6922:                    if ($noblockcheck) {
 6923:                        $thisallowed.=$value;
 6924:                    } else {
 6925:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6926:                        if (@blockers > 0) {
 6927:                            $thisallowed = 'B';
 6928:                        } else {
 6929:                            $thisallowed.=$value;
 6930:                        }
 6931:                    }
 6932:                } else {
 6933:                    $thisallowed.=$value;
 6934:                }
 6935:                $checkreferer=0;
 6936:            }
 6937:        }
 6938:        
 6939:        if ($checkreferer) {
 6940: 	  my $refuri=$env{'httpref.'.$orguri};
 6941:             unless ($refuri) {
 6942:                 foreach my $key (keys(%env)) {
 6943: 		    if ($key=~/^httpref\..*\*/) {
 6944: 			my $pattern=$key;
 6945:                         $pattern=~s/^httpref\.\/res\///;
 6946:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6947:                         $pattern=~s/\//\\\//g;
 6948:                         if ($orguri=~/$pattern/) {
 6949: 			    $refuri=$env{$key};
 6950:                         }
 6951:                     }
 6952:                 }
 6953:             }
 6954: 
 6955:          if ($refuri) { 
 6956: 	  $refuri=&declutter($refuri);
 6957:           my ($match,$cond)=&is_on_map($refuri);
 6958:             if ($match) {
 6959:               my $refstatecond=$cond;
 6960:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6961:                   =~/\Q$priv\E\&([^\:]*)/) {
 6962:                   my $value = $1;
 6963:                   if ($priv eq 'bre') {
 6964:                       if ($noblockcheck) {
 6965:                           $thisallowed.=$value;
 6966:                       } else {
 6967:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6968:                           if (@blockers > 0) {
 6969:                               $thisallowed = 'B';
 6970:                           } else {
 6971:                               $thisallowed.=$value;
 6972:                           }
 6973:                       }
 6974:                   } else {
 6975:                       $thisallowed.=$value;
 6976:                   }
 6977:                   $uri=$refuri;
 6978:                   $statecond=$refstatecond;
 6979:               }
 6980:           }
 6981:         }
 6982:        }
 6983:    }
 6984: 
 6985: #
 6986: # Gathered now: all privileges that could apply, and condition number
 6987: # 
 6988: #
 6989: # Full or no access?
 6990: #
 6991: 
 6992:     if ($thisallowed=~/F/) {
 6993: 	return 'F';
 6994:     }
 6995: 
 6996:     unless ($thisallowed) {
 6997:         return '';
 6998:     }
 6999: 
 7000: # Restrictions exist, deal with them
 7001: #
 7002: #   C:according to course preferences
 7003: #   R:according to resource settings
 7004: #   L:unless locked
 7005: #   X:according to user session state
 7006: #
 7007: 
 7008: # Possibly locked functionality, check all courses
 7009: # Locks might take effect only after 10 minutes cache expiration for other
 7010: # courses, and 2 minutes for current course
 7011: 
 7012:     my $envkey;
 7013:     if ($thisallowed=~/L/) {
 7014:         foreach $envkey (keys(%env)) {
 7015:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7016:                my $courseid=$2;
 7017:                my $roleid=$1.'.'.$2;
 7018:                $courseid=~s/^\///;
 7019:                my $expiretime=600;
 7020:                if ($env{'request.role'} eq $roleid) {
 7021: 		  $expiretime=120;
 7022:                }
 7023: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7024:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7025:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7026: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7027:                }
 7028:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7029:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7030: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7031:                        &log($env{'user.domain'},$env{'user.name'},
 7032:                             $env{'user.home'},
 7033:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7034:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7035:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7036: 		       return '';
 7037:                    }
 7038:                }
 7039:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7040:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7041: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7042:                        &log($env{'user.domain'},$env{'user.name'},
 7043:                             $env{'user.home'},
 7044:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7045:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7046:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7047: 		       return '';
 7048:                    }
 7049:                }
 7050: 	   }
 7051:        }
 7052:     }
 7053:    
 7054: #
 7055: # Rest of the restrictions depend on selected course
 7056: #
 7057: 
 7058:     unless ($env{'request.course.id'}) {
 7059: 	if ($thisallowed eq 'A') {
 7060: 	    return 'A';
 7061:         } elsif ($thisallowed eq 'B') {
 7062:             return 'B';
 7063: 	} else {
 7064: 	    return '1';
 7065: 	}
 7066:     }
 7067: 
 7068: #
 7069: # Now user is definitely in a course
 7070: #
 7071: 
 7072: 
 7073: # Course preferences
 7074: 
 7075:    if ($thisallowed=~/C/) {
 7076:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7077:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7078:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7079: 	   =~/\Q$rolecode\E/) {
 7080: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7081: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7082: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7083: 			$env{'request.course.id'});
 7084: 	   }
 7085:            return '';
 7086:        }
 7087: 
 7088:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7089: 	   =~/\Q$unamedom\E/) {
 7090: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7091: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7092: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7093: 			$env{'request.course.id'});
 7094: 	   }
 7095:            return '';
 7096:        }
 7097:    }
 7098: 
 7099: # Resource preferences
 7100: 
 7101:    if ($thisallowed=~/R/) {
 7102:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7103:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7104: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7105: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7106: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7107: 	   }
 7108: 	   return '';
 7109:        }
 7110:    }
 7111: 
 7112: # Restricted by state or randomout?
 7113: 
 7114:    if ($thisallowed=~/X/) {
 7115:       if ($env{'acc.randomout'}) {
 7116: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7117:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7118:             return ''; 
 7119:          }
 7120:       }
 7121:       if (&condval($statecond)) {
 7122: 	 return '2';
 7123:       } else {
 7124:          return '';
 7125:       }
 7126:    }
 7127: 
 7128:     if ($thisallowed eq 'A') {
 7129: 	return 'A';
 7130:     } elsif ($thisallowed eq 'B') {
 7131:         return 'B';
 7132:     }
 7133:    return 'F';
 7134: }
 7135: 
 7136: # ------------------------------------------- Check construction space access
 7137: 
 7138: sub constructaccess {
 7139:     my ($url,$setpriv)=@_;
 7140: 
 7141: # We do not allow editing of previous versions of files
 7142:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7143: 
 7144: # Get username and domain from URL
 7145:     my ($ownername,$ownerdomain,$ownerhome);
 7146: 
 7147:     ($ownerdomain,$ownername) =
 7148:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7149: 
 7150: # The URL does not really point to any authorspace, forget it
 7151:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7152: 
 7153: # Now we need to see if the user has access to the authorspace of
 7154: # $ownername at $ownerdomain
 7155: 
 7156:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7157: # Real author for this?
 7158:        $ownerhome = $env{'user.home'};
 7159:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7160:           return ($ownername,$ownerdomain,$ownerhome);
 7161:        }
 7162:     } else {
 7163: # Co-author for this?
 7164:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7165:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7166:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7167:             return ($ownername,$ownerdomain,$ownerhome);
 7168:         }
 7169:     }
 7170: 
 7171: # We don't have any access right now. If we are not possibly going to do anything about this,
 7172: # we might as well leave
 7173:    unless ($setpriv) { return ''; }
 7174: 
 7175: # Backdoor access?
 7176:     my $allowed=&allowed('eco',$ownerdomain);
 7177: # Nope
 7178:     unless ($allowed) { return ''; }
 7179: # Looks like we may have access, but could be locked by the owner of the construction space
 7180:     if ($allowed eq 'U') {
 7181:         my %blocked=&get('environment',['domcoord.author'],
 7182:                          $ownerdomain,$ownername);
 7183: # Is blocked by owner
 7184:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7185:     }
 7186:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7187: # Grant temporary access
 7188:         my $then=$env{'user.login.time'};
 7189:         my $update=$env{'user.update.time'};
 7190:         if (!$update) { $update = $then; }
 7191:         my $refresh=$env{'user.refresh.time'};
 7192:         if (!$refresh) { $refresh = $update; }
 7193:         my $now = time;
 7194:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7195:                            $now,'ca','constructaccess');
 7196:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7197:         return($ownername,$ownerdomain,$ownerhome);
 7198:     }
 7199: # No business here
 7200:     return '';
 7201: }
 7202: 
 7203: # ----------------------------------------------------------- Content Blocking
 7204: 
 7205: {
 7206: # Caches for faster Course Contents display where content blocking
 7207: # is in operation (i.e., interval param set) for timed quiz.
 7208: #
 7209: # User for whom data are being temporarily cached.
 7210: my $cacheduser='';
 7211: # Cached blockers for this user (a hash of blocking items). 
 7212: my %cachedblockers=();
 7213: # When the data were last cached.
 7214: my $cachedlast='';
 7215: 
 7216: sub load_all_blockers {
 7217:     my ($uname,$udom,$blocks)=@_;
 7218:     if (($uname ne '') && ($udom ne '')) { 
 7219:         if (($cacheduser eq $uname.':'.$udom) &&
 7220:             (abs($cachedlast-time)<5)) {
 7221:             return;
 7222:         }
 7223:     }
 7224:     $cachedlast=time;
 7225:     $cacheduser=$uname.':'.$udom;
 7226:     %cachedblockers = &get_commblock_resources($blocks);
 7227: }
 7228: 
 7229: sub get_comm_blocks {
 7230:     my ($cdom,$cnum) = @_;
 7231:     if ($cdom eq '' || $cnum eq '') {
 7232:         return unless ($env{'request.course.id'});
 7233:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7234:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7235:     }
 7236:     my %commblocks;
 7237:     my $hashid=$cdom.'_'.$cnum;
 7238:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7239:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7240:         %commblocks = %{$blocksref};
 7241:     } else {
 7242:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7243:         my $cachetime = 600;
 7244:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7245:     }
 7246:     return %commblocks;
 7247: }
 7248: 
 7249: sub get_commblock_resources {
 7250:     my ($blocks) = @_;
 7251:     my %blockers = ();
 7252:     return %blockers unless ($env{'request.course.id'});
 7253:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7254:     my %commblocks;
 7255:     if (ref($blocks) eq 'HASH') {
 7256:         %commblocks = %{$blocks};
 7257:     } else {
 7258:         %commblocks = &get_comm_blocks();
 7259:     }
 7260:     return %blockers unless (keys(%commblocks) > 0); 
 7261:     my $navmap = Apache::lonnavmaps::navmap->new();
 7262:     return %blockers unless (ref($navmap));
 7263:     my $now = time;
 7264:     foreach my $block (keys(%commblocks)) {
 7265:         if ($block =~ /^(\d+)____(\d+)$/) {
 7266:             my ($start,$end) = ($1,$2);
 7267:             if ($start <= $now && $end >= $now) {
 7268:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7269:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7270:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7271:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7272:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 7273:                             }
 7274:                         }
 7275:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7276:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7277:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7278:                             }
 7279:                         }
 7280:                     }
 7281:                 }
 7282:             }
 7283:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7284:             my $item = $1;
 7285:             my @to_test;
 7286:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7287:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7288:                     my @interval;
 7289:                     my $type = 'map';
 7290:                     if ($item eq 'course') {
 7291:                         $type = 'course';
 7292:                         @interval=&EXT("resource.0.interval");
 7293:                     } else {
 7294:                         if ($item =~ /___\d+___/) {
 7295:                             $type = 'resource';
 7296:                             @interval=&EXT("resource.0.interval",$item);
 7297:                             if (ref($navmap)) {                        
 7298:                                 my $res = $navmap->getBySymb($item); 
 7299:                                 push(@to_test,$res);
 7300:                             }
 7301:                         } else {
 7302:                             my $mapsymb = &symbread($item,1);
 7303:                             if ($mapsymb) {
 7304:                                 if (ref($navmap)) {
 7305:                                     my $mapres = $navmap->getBySymb($mapsymb);
 7306:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 7307:                                     foreach my $res (@to_test) {
 7308:                                         my $symb = $res->symb();
 7309:                                         next if ($symb eq $mapsymb);
 7310:                                         if ($symb ne '') {
 7311:                                             @interval=&EXT("resource.0.interval",$symb);
 7312:                                             if ($interval[1] eq 'map') {
 7313:                                                 last;
 7314:                                             }
 7315:                                         }
 7316:                                     }
 7317:                                 }
 7318:                             }
 7319:                         }
 7320:                     }
 7321:                     if ($interval[0] =~ /^\d+$/) {
 7322:                         my $first_access;
 7323:                         if ($type eq 'resource') {
 7324:                             $first_access=&get_first_access($interval[1],$item);
 7325:                         } elsif ($type eq 'map') {
 7326:                             $first_access=&get_first_access($interval[1],undef,$item);
 7327:                         } else {
 7328:                             $first_access=&get_first_access($interval[1]);
 7329:                         }
 7330:                         if ($first_access) {
 7331:                             my $timesup = $first_access+$interval[0];
 7332:                             if ($timesup > $now) {
 7333:                                 my $activeblock;
 7334:                                 foreach my $res (@to_test) {
 7335:                                     if ($res->answerable()) {
 7336:                                         $activeblock = 1;
 7337:                                         last;
 7338:                                     }
 7339:                                 }
 7340:                                 if ($activeblock) {
 7341:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7342:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7343:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 7344:                                          }
 7345:                                     }
 7346:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7347:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7348:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7349:                                         }
 7350:                                     }
 7351:                                 }
 7352:                             }
 7353:                         }
 7354:                     }
 7355:                 }
 7356:             }
 7357:         }
 7358:     }
 7359:     return %blockers;
 7360: }
 7361: 
 7362: sub has_comm_blocking {
 7363:     my ($priv,$symb,$uri,$blocks) = @_;
 7364:     my @blockers;
 7365:     return unless ($env{'request.course.id'});
 7366:     return unless ($priv eq 'bre');
 7367:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7368:     return if ($env{'request.state'} eq 'construct');
 7369:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 7370:     return unless (keys(%cachedblockers) > 0);
 7371:     my (%possibles,@symbs);
 7372:     if (!$symb) {
 7373:         $symb = &symbread($uri,1,1,1,\%possibles);
 7374:     }
 7375:     if ($symb) {
 7376:         @symbs = ($symb);
 7377:     } elsif (keys(%possibles)) { 
 7378:         @symbs = keys(%possibles);
 7379:     }
 7380:     my $noblock;
 7381:     foreach my $symb (@symbs) {
 7382:         last if ($noblock);
 7383:         my ($map,$resid,$resurl)=&decode_symb($symb);
 7384:         foreach my $block (keys(%cachedblockers)) {
 7385:             if ($block =~ /^firstaccess____(.+)$/) {
 7386:                 my $item = $1;
 7387:                 if (($item eq $map) || ($item eq $symb)) {
 7388:                     $noblock = 1;
 7389:                     last;
 7390:                 }
 7391:             }
 7392:             if (ref($cachedblockers{$block}) eq 'HASH') {
 7393:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 7394:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 7395:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 7396:                             push(@blockers,$block);
 7397:                         }
 7398:                     }
 7399:                 }
 7400:             }
 7401:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 7402:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 7403:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 7404:                         push(@blockers,$block);
 7405:                     }
 7406:                 }
 7407:             }
 7408:         }
 7409:     }
 7410:     return if ($noblock);
 7411:     return @blockers;
 7412: }
 7413: }
 7414: 
 7415: # -------------------------------- Deversion and split uri into path an filename   
 7416: 
 7417: #
 7418: #   Removes the version from a URI and
 7419: #   splits it in to its filename and path to the filename.
 7420: #   Seems like File::Basename could have done this more clearly.
 7421: #   Parameters:
 7422: #      $uri   - input URI
 7423: #   Returns:
 7424: #     Two element list consisting of 
 7425: #     $pathname  - the URI up to and excluding the trailing /
 7426: #     $filename  - The part of the URI following the last /
 7427: #  NOTE:
 7428: #    Another realization of this is simply:
 7429: #    use File::Basename;
 7430: #    ...
 7431: #    $uri = shift;
 7432: #    $filename = basename($uri);
 7433: #    $path     = dirname($uri);
 7434: #    return ($filename, $path);
 7435: #
 7436: #     The implementation below is probably faster however.
 7437: #
 7438: sub split_uri_for_cond {
 7439:     my $uri=&deversion(&declutter(shift));
 7440:     my @uriparts=split(/\//,$uri);
 7441:     my $filename=pop(@uriparts);
 7442:     my $pathname=join('/',@uriparts);
 7443:     return ($pathname,$filename);
 7444: }
 7445: # --------------------------------------------------- Is a resource on the map?
 7446: 
 7447: sub is_on_map {
 7448:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7449:     #Trying to find the conditional for the file
 7450:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7451: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7452:     if ($match) {
 7453: 	return (1,$1);
 7454:     } else {
 7455: 	return (0,0);
 7456:     }
 7457: }
 7458: 
 7459: # --------------------------------------------------------- Get symb from alias
 7460: 
 7461: sub get_symb_from_alias {
 7462:     my $symb=shift;
 7463:     my ($map,$resid,$url)=&decode_symb($symb);
 7464: # Already is a symb
 7465:     if ($url) { return $symb; }
 7466: # Must be an alias
 7467:     my $aliassymb='';
 7468:     my %bighash;
 7469:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7470:                             &GDBM_READER(),0640)) {
 7471:         my $rid=$bighash{'mapalias_'.$symb};
 7472: 	if ($rid) {
 7473: 	    my ($mapid,$resid)=split(/\./,$rid);
 7474: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7475: 				    $resid,$bighash{'src_'.$rid});
 7476: 	}
 7477:         untie %bighash;
 7478:     }
 7479:     return $aliassymb;
 7480: }
 7481: 
 7482: # ----------------------------------------------------------------- Define Role
 7483: 
 7484: sub definerole {
 7485:   if (allowed('mcr','/')) {
 7486:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7487:     foreach my $role (split(':',$sysrole)) {
 7488: 	my ($crole,$cqual)=split(/\&/,$role);
 7489:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7490:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7491: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7492:                return "refused:s:$crole&$cqual"; 
 7493:             }
 7494:         }
 7495:     }
 7496:     foreach my $role (split(':',$domrole)) {
 7497: 	my ($crole,$cqual)=split(/\&/,$role);
 7498:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7499:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7500: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7501:                return "refused:d:$crole&$cqual"; 
 7502:             }
 7503:         }
 7504:     }
 7505:     foreach my $role (split(':',$courole)) {
 7506: 	my ($crole,$cqual)=split(/\&/,$role);
 7507:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7508:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7509: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7510:                return "refused:c:$crole&$cqual"; 
 7511:             }
 7512:         }
 7513:     }
 7514:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7515:                 "$env{'user.domain'}:$env{'user.name'}:".
 7516: 	        "rolesdef_$rolename=".
 7517:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7518:     return reply($command,$env{'user.home'});
 7519:   } else {
 7520:     return 'refused';
 7521:   }
 7522: }
 7523: 
 7524: # ---------------- Make a metadata query against the network of library servers
 7525: 
 7526: sub metadata_query {
 7527:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7528:     my %rhash;
 7529:     my %libserv = &all_library();
 7530:     my @server_list = (defined($server_array) ? @$server_array
 7531:                                               : keys(%libserv) );
 7532:     for my $server (@server_list) {
 7533:         my $domains = ''; 
 7534:         if (ref($domains_hash) eq 'HASH') {
 7535:             $domains = $domains_hash->{$server}; 
 7536:         }
 7537: 	unless ($custom or $customshow) {
 7538: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7539: 	    $rhash{$server}=$reply;
 7540: 	}
 7541: 	else {
 7542: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7543: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7544: 			     $server);
 7545: 	    $rhash{$server}=$reply;
 7546: 	}
 7547:     }
 7548:     return \%rhash;
 7549: }
 7550: 
 7551: # ----------------------------------------- Send log queries and wait for reply
 7552: 
 7553: sub log_query {
 7554:     my ($uname,$udom,$query,%filters)=@_;
 7555:     my $uhome=&homeserver($uname,$udom);
 7556:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7557:     my $uhost=&hostname($uhome);
 7558:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7559:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7560:                        $uhome);
 7561:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7562:     return get_query_reply($queryid);
 7563: }
 7564: 
 7565: # -------------------------- Update MySQL table for portfolio file
 7566: 
 7567: sub update_portfolio_table {
 7568:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7569:     if ($group ne '') {
 7570:         $file_name =~s /^\Q$group\E//;
 7571:     }
 7572:     my $homeserver = &homeserver($uname,$udom);
 7573:     my $queryid=
 7574:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7575:                ':'.&escape($file_name).':'.$action,$homeserver);
 7576:     my $reply = &get_query_reply($queryid);
 7577:     return $reply;
 7578: }
 7579: 
 7580: # -------------------------- Update MySQL allusers table
 7581: 
 7582: sub update_allusers_table {
 7583:     my ($uname,$udom,$names) = @_;
 7584:     my $homeserver = &homeserver($uname,$udom);
 7585:     my $queryid=
 7586:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7587:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7588:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7589:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7590:                'generation='.&escape($names->{'generation'}).'%%'.
 7591:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7592:                'id='.&escape($names->{'id'}),$homeserver);
 7593:     return;
 7594: }
 7595: 
 7596: # ------- Request retrieval of institutional classlists for course(s)
 7597: 
 7598: sub fetch_enrollment_query {
 7599:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7600:     my $homeserver;
 7601:     my $maxtries = 1;
 7602:     if ($context eq 'automated') {
 7603:         $homeserver = $perlvar{'lonHostID'};
 7604:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7605:     } else {
 7606:         $homeserver = &homeserver($cnum,$dom);
 7607:     }
 7608:     my $host=&hostname($homeserver);
 7609:     my $cmd = '';
 7610:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7611:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7612:     }
 7613:     $cmd =~ s/%%$//;
 7614:     $cmd = &escape($cmd);
 7615:     my $query = 'fetchenrollment';
 7616:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7617:     unless ($queryid=~/^\Q$host\E\_/) { 
 7618:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7619:         return 'error: '.$queryid;
 7620:     }
 7621:     my $reply = &get_query_reply($queryid);
 7622:     my $tries = 1;
 7623:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7624:         $reply = &get_query_reply($queryid);
 7625:         $tries ++;
 7626:     }
 7627:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7628:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7629:     } else {
 7630:         my @responses = split(/:/,$reply);
 7631:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7632:             foreach my $line (@responses) {
 7633:                 my ($key,$value) = split(/=/,$line,2);
 7634:                 $$replyref{$key} = $value;
 7635:             }
 7636:         } else {
 7637:             my $pathname = LONCAPA::tempdir();
 7638:             foreach my $line (@responses) {
 7639:                 my ($key,$value) = split(/=/,$line);
 7640:                 $$replyref{$key} = $value;
 7641:                 if ($value > 0) {
 7642:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7643:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7644:                         my $destname = $pathname.'/'.$filename;
 7645:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7646:                         if ($xml_classlist =~ /^error/) {
 7647:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7648:                         } else {
 7649:                             if ( open(FILE,">$destname") ) {
 7650:                                 print FILE &unescape($xml_classlist);
 7651:                                 close(FILE);
 7652:                             } else {
 7653:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7654:                             }
 7655:                         }
 7656:                     }
 7657:                 }
 7658:             }
 7659:         }
 7660:         return 'ok';
 7661:     }
 7662:     return 'error';
 7663: }
 7664: 
 7665: sub get_query_reply {
 7666:     my $queryid=shift;
 7667:     my $replyfile=LONCAPA::tempdir().$queryid;
 7668:     my $reply='';
 7669:     for (1..100) {
 7670: 	sleep 2;
 7671:         if (-e $replyfile.'.end') {
 7672: 	    if (open(my $fh,$replyfile)) {
 7673: 		$reply = join('',<$fh>);
 7674: 		close($fh);
 7675: 	   } else { return 'error: reply_file_error'; }
 7676:            return &unescape($reply);
 7677: 	}
 7678:     }
 7679:     return 'timeout:'.$queryid;
 7680: }
 7681: 
 7682: sub courselog_query {
 7683: #
 7684: # possible filters:
 7685: # url: url or symb
 7686: # username
 7687: # domain
 7688: # action: view, submit, grade
 7689: # start: timestamp
 7690: # end: timestamp
 7691: #
 7692:     my (%filters)=@_;
 7693:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7694:     if ($filters{'url'}) {
 7695: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7696:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7697:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7698:     }
 7699:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7700:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7701:     return &log_query($cname,$cdom,'courselog',%filters);
 7702: }
 7703: 
 7704: sub userlog_query {
 7705: #
 7706: # possible filters:
 7707: # action: log check role
 7708: # start: timestamp
 7709: # end: timestamp
 7710: #
 7711:     my ($uname,$udom,%filters)=@_;
 7712:     return &log_query($uname,$udom,'userlog',%filters);
 7713: }
 7714: 
 7715: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7716: 
 7717: sub auto_run {
 7718:     my ($cnum,$cdom) = @_;
 7719:     my $response = 0;
 7720:     my $settings;
 7721:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7722:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7723:         $settings = $domconfig{'autoenroll'};
 7724:         if ($settings->{'run'} eq '1') {
 7725:             $response = 1;
 7726:         }
 7727:     } else {
 7728:         my $homeserver;
 7729:         if (&is_course($cdom,$cnum)) {
 7730:             $homeserver = &homeserver($cnum,$cdom);
 7731:         } else {
 7732:             $homeserver = &domain($cdom,'primary');
 7733:         }
 7734:         if ($homeserver ne 'no_host') {
 7735:             $response = &reply('autorun:'.$cdom,$homeserver);
 7736:         }
 7737:     }
 7738:     return $response;
 7739: }
 7740: 
 7741: sub auto_get_sections {
 7742:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7743:     my $homeserver;
 7744:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7745:         $homeserver = &homeserver($cnum,$cdom);
 7746:     }
 7747:     if (!defined($homeserver)) { 
 7748:         if ($cdom =~ /^$match_domain$/) {
 7749:             $homeserver = &domain($cdom,'primary');
 7750:         }
 7751:     }
 7752:     my @secs;
 7753:     if (defined($homeserver)) {
 7754:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7755:         unless ($response eq 'refused') {
 7756:             @secs = split(/:/,$response);
 7757:         }
 7758:     }
 7759:     return @secs;
 7760: }
 7761: 
 7762: sub auto_new_course {
 7763:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7764:     my $homeserver = &homeserver($cnum,$cdom);
 7765:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7766:     return $response;
 7767: }
 7768: 
 7769: sub auto_validate_courseID {
 7770:     my ($cnum,$cdom,$inst_course_id) = @_;
 7771:     my $homeserver = &homeserver($cnum,$cdom);
 7772:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7773:     return $response;
 7774: }
 7775: 
 7776: sub auto_validate_instcode {
 7777:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7778:     my ($homeserver,$response);
 7779:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7780:         $homeserver = &homeserver($cnum,$cdom);
 7781:     }
 7782:     if (!defined($homeserver)) {
 7783:         if ($cdom =~ /^$match_domain$/) {
 7784:             $homeserver = &domain($cdom,'primary');
 7785:         }
 7786:     }
 7787:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7788:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7789:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7790:     return ($outcome,$description,$defaultcredits);
 7791: }
 7792: 
 7793: sub auto_create_password {
 7794:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7795:     my ($homeserver,$response);
 7796:     my $create_passwd = 0;
 7797:     my $authchk = '';
 7798:     if ($udom =~ /^$match_domain$/) {
 7799:         $homeserver = &domain($udom,'primary');
 7800:     }
 7801:     if ($homeserver eq '') {
 7802:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7803:             $homeserver = &homeserver($cnum,$cdom);
 7804:         }
 7805:     }
 7806:     if ($homeserver eq '') {
 7807:         $authchk = 'nodomain';
 7808:     } else {
 7809:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7810:         if ($response eq 'refused') {
 7811:             $authchk = 'refused';
 7812:         } else {
 7813:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7814:         }
 7815:     }
 7816:     return ($authparam,$create_passwd,$authchk);
 7817: }
 7818: 
 7819: sub auto_photo_permission {
 7820:     my ($cnum,$cdom,$students) = @_;
 7821:     my $homeserver = &homeserver($cnum,$cdom);
 7822:     my ($outcome,$perm_reqd,$conditions) = 
 7823: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7824:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7825: 	return (undef,undef);
 7826:     }
 7827:     return ($outcome,$perm_reqd,$conditions);
 7828: }
 7829: 
 7830: sub auto_checkphotos {
 7831:     my ($uname,$udom,$pid) = @_;
 7832:     my $homeserver = &homeserver($uname,$udom);
 7833:     my ($result,$resulttype);
 7834:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7835: 				   &escape($uname).':'.&escape($pid),
 7836: 				   $homeserver));
 7837:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7838: 	return (undef,undef);
 7839:     }
 7840:     if ($outcome) {
 7841:         ($result,$resulttype) = split(/:/,$outcome);
 7842:     } 
 7843:     return ($result,$resulttype);
 7844: }
 7845: 
 7846: sub auto_photochoice {
 7847:     my ($cnum,$cdom) = @_;
 7848:     my $homeserver = &homeserver($cnum,$cdom);
 7849:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7850: 						       &escape($cdom),
 7851: 						       $homeserver)));
 7852:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7853: 	return (undef,undef);
 7854:     }
 7855:     return ($update,$comment);
 7856: }
 7857: 
 7858: sub auto_photoupdate {
 7859:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7860:     my $homeserver = &homeserver($cnum,$dom);
 7861:     my $host=&hostname($homeserver);
 7862:     my $cmd = '';
 7863:     my $maxtries = 1;
 7864:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7865:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7866:     }
 7867:     $cmd =~ s/%%$//;
 7868:     $cmd = &escape($cmd);
 7869:     my $query = 'institutionalphotos';
 7870:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7871:     unless ($queryid=~/^\Q$host\E\_/) {
 7872:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7873:         return 'error: '.$queryid;
 7874:     }
 7875:     my $reply = &get_query_reply($queryid);
 7876:     my $tries = 1;
 7877:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7878:         $reply = &get_query_reply($queryid);
 7879:         $tries ++;
 7880:     }
 7881:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7882:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7883:     } else {
 7884:         my @responses = split(/:/,$reply);
 7885:         my $outcome = shift(@responses); 
 7886:         foreach my $item (@responses) {
 7887:             my ($key,$value) = split(/=/,$item);
 7888:             $$photo{$key} = $value;
 7889:         }
 7890:         return $outcome;
 7891:     }
 7892:     return 'error';
 7893: }
 7894: 
 7895: sub auto_instcode_format {
 7896:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7897: 	$cat_order) = @_;
 7898:     my $courses = '';
 7899:     my @homeservers;
 7900:     if ($caller eq 'global') {
 7901: 	my %servers = &get_servers($codedom,'library');
 7902: 	foreach my $tryserver (keys(%servers)) {
 7903: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7904: 		push(@homeservers,$tryserver);
 7905: 	    }
 7906:         }
 7907:     } elsif ($caller eq 'requests') {
 7908:         if ($codedom =~ /^$match_domain$/) {
 7909:             my $chome = &domain($codedom,'primary');
 7910:             unless ($chome eq 'no_host') {
 7911:                 push(@homeservers,$chome);
 7912:             }
 7913:         }
 7914:     } else {
 7915:         push(@homeservers,&homeserver($caller,$codedom));
 7916:     }
 7917:     foreach my $code (keys(%{$instcodes})) {
 7918:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7919:     }
 7920:     chop($courses);
 7921:     my $ok_response = 0;
 7922:     my $response;
 7923:     while (@homeservers > 0 && $ok_response == 0) {
 7924:         my $server = shift(@homeservers); 
 7925:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7926:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7927:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7928: 		split(/:/,$response);
 7929:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7930:             push(@{$codetitles},&str2array($codetitles_str));
 7931:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7932:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7933:             $ok_response = 1;
 7934:         }
 7935:     }
 7936:     if ($ok_response) {
 7937:         return 'ok';
 7938:     } else {
 7939:         return $response;
 7940:     }
 7941: }
 7942: 
 7943: sub auto_instcode_defaults {
 7944:     my ($domain,$returnhash,$code_order) = @_;
 7945:     my @homeservers;
 7946: 
 7947:     my %servers = &get_servers($domain,'library');
 7948:     foreach my $tryserver (keys(%servers)) {
 7949: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7950: 	    push(@homeservers,$tryserver);
 7951: 	}
 7952:     }
 7953: 
 7954:     my $response;
 7955:     foreach my $server (@homeservers) {
 7956:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7957:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7958: 	
 7959: 	foreach my $pair (split(/\&/,$response)) {
 7960: 	    my ($name,$value)=split(/\=/,$pair);
 7961: 	    if ($name eq 'code_order') {
 7962: 		@{$code_order} = split(/\&/,&unescape($value));
 7963: 	    } else {
 7964: 		$returnhash->{&unescape($name)}=&unescape($value);
 7965: 	    }
 7966: 	}
 7967: 	return 'ok';
 7968:     }
 7969: 
 7970:     return $response;
 7971: }
 7972: 
 7973: sub auto_possible_instcodes {
 7974:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7975:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7976:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7977:         return;
 7978:     }
 7979:     my (@homeservers,$uhome);
 7980:     if (defined(&domain($domain,'primary'))) {
 7981:         $uhome=&domain($domain,'primary');
 7982:         push(@homeservers,&domain($domain,'primary'));
 7983:     } else {
 7984:         my %servers = &get_servers($domain,'library');
 7985:         foreach my $tryserver (keys(%servers)) {
 7986:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7987:                 push(@homeservers,$tryserver);
 7988:             }
 7989:         }
 7990:     }
 7991:     my $response;
 7992:     foreach my $server (@homeservers) {
 7993:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7994:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7995:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7996:             split(':',$response);
 7997:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7998:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7999:         foreach my $item (split('&',$cat_title)) {   
 8000:             my ($name,$value)=split('=',$item);
 8001:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8002:         }
 8003:         foreach my $item (split('&',$cat_order)) {
 8004:             my ($name,$value)=split('=',$item);
 8005:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8006:         }
 8007:         return 'ok';
 8008:     }
 8009:     return $response;
 8010: }
 8011: 
 8012: sub auto_courserequest_checks {
 8013:     my ($dom) = @_;
 8014:     my ($homeserver,%validations);
 8015:     if ($dom =~ /^$match_domain$/) {
 8016:         $homeserver = &domain($dom,'primary');
 8017:     }
 8018:     unless ($homeserver eq 'no_host') {
 8019:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8020:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8021:             my @items = split(/&/,$response);
 8022:             foreach my $item (@items) {
 8023:                 my ($key,$value) = split('=',$item);
 8024:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8025:             }
 8026:         }
 8027:     }
 8028:     return %validations; 
 8029: }
 8030: 
 8031: sub auto_courserequest_validation {
 8032:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8033:     my ($homeserver,$response);
 8034:     if ($dom =~ /^$match_domain$/) {
 8035:         $homeserver = &domain($dom,'primary');
 8036:     }
 8037:     unless ($homeserver eq 'no_host') {
 8038:         my $customdata;
 8039:         if (ref($custominfo) eq 'HASH') {
 8040:             $customdata = &freeze_escape($custominfo);
 8041:         }
 8042:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8043:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8044:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8045:                                     $customdata,$homeserver));
 8046:     }
 8047:     return $response;
 8048: }
 8049: 
 8050: sub auto_validate_class_sec {
 8051:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8052:     my $homeserver = &homeserver($cnum,$cdom);
 8053:     my $ownerlist;
 8054:     if (ref($owners) eq 'ARRAY') {
 8055:         $ownerlist = join(',',@{$owners});
 8056:     } else {
 8057:         $ownerlist = $owners;
 8058:     }
 8059:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8060:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8061:     return $response;
 8062: }
 8063: 
 8064: sub auto_crsreq_update {
 8065:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8066:         $code,$accessstart,$accessend,$inbound) = @_;
 8067:     my ($homeserver,%crsreqresponse);
 8068:     if ($cdom =~ /^$match_domain$/) {
 8069:         $homeserver = &domain($cdom,'primary');
 8070:     }
 8071:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8072:         my $info;
 8073:         if (ref($inbound) eq 'HASH') {
 8074:             $info = &freeze_escape($inbound);
 8075:         }
 8076:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8077:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8078:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8079:                             &escape($title).':'.&escape($code).':'.
 8080:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8081:                             $homeserver);
 8082:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8083:             my @items = split(/&/,$response);
 8084:             foreach my $item (@items) {
 8085:                 my ($key,$value) = split('=',$item);
 8086:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8087:             }
 8088:         }
 8089:     }
 8090:     return \%crsreqresponse;
 8091: }
 8092: 
 8093: # ------------------------------------------------------- Course Group routines
 8094: 
 8095: sub get_coursegroups {
 8096:     my ($cdom,$cnum,$group,$namespace) = @_;
 8097:     return(&dump($namespace,$cdom,$cnum,$group));
 8098: }
 8099: 
 8100: sub modify_coursegroup {
 8101:     my ($cdom,$cnum,$groupsettings) = @_;
 8102:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8103: }
 8104: 
 8105: sub toggle_coursegroup_status {
 8106:     my ($cdom,$cnum,$group,$action) = @_;
 8107:     my ($from_namespace,$to_namespace);
 8108:     if ($action eq 'delete') {
 8109:         $from_namespace = 'coursegroups';
 8110:         $to_namespace = 'deleted_groups';
 8111:     } else {
 8112:         $from_namespace = 'deleted_groups';
 8113:         $to_namespace = 'coursegroups';
 8114:     }
 8115:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8116:     if (my $tmp = &error(%curr_group)) {
 8117:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8118:         return ('read error',$tmp);
 8119:     } else {
 8120:         my %savedsettings = %curr_group; 
 8121:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8122:         my $deloutcome;
 8123:         if ($result eq 'ok') {
 8124:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8125:         } else {
 8126:             return ('write error',$result);
 8127:         }
 8128:         if ($deloutcome eq 'ok') {
 8129:             return 'ok';
 8130:         } else {
 8131:             return ('delete error',$deloutcome);
 8132:         }
 8133:     }
 8134: }
 8135: 
 8136: sub modify_group_roles {
 8137:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8138:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8139:     my $role = 'gr/'.&escape($userprivs);
 8140:     my ($uname,$udom) = split(/:/,$user);
 8141:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8142:     if ($result eq 'ok') {
 8143:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8144:     }
 8145:     return $result;
 8146: }
 8147: 
 8148: sub modify_coursegroup_membership {
 8149:     my ($cdom,$cnum,$membership) = @_;
 8150:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8151:     return $result;
 8152: }
 8153: 
 8154: sub get_active_groups {
 8155:     my ($udom,$uname,$cdom,$cnum) = @_;
 8156:     my $now = time;
 8157:     my %groups = ();
 8158:     foreach my $key (keys(%env)) {
 8159:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8160:             my ($start,$end) = split(/\./,$env{$key});
 8161:             if (($end!=0) && ($end<$now)) { next; }
 8162:             if (($start!=0) && ($start>$now)) { next; }
 8163:             if ($1 eq $cdom && $2 eq $cnum) {
 8164:                 $groups{$3} = $env{$key} ;
 8165:             }
 8166:         }
 8167:     }
 8168:     return %groups;
 8169: }
 8170: 
 8171: sub get_group_membership {
 8172:     my ($cdom,$cnum,$group) = @_;
 8173:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8174: }
 8175: 
 8176: sub get_users_groups {
 8177:     my ($udom,$uname,$courseid) = @_;
 8178:     my @usersgroups;
 8179:     my $cachetime=1800;
 8180: 
 8181:     my $hashid="$udom:$uname:$courseid";
 8182:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8183:     if (defined($cached)) {
 8184:         @usersgroups = split(/:/,$grouplist);
 8185:     } else {  
 8186:         $grouplist = '';
 8187:         my $courseurl = &courseid_to_courseurl($courseid);
 8188:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8189:         my $access_end = $env{'course.'.$courseid.
 8190:                               '.default_enrollment_end_date'};
 8191:         my $now = time;
 8192:         foreach my $key (keys(%roleshash)) {
 8193:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8194:                 my $group = $1;
 8195:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8196:                     my $start = $2;
 8197:                     my $end = $1;
 8198:                     if ($start == -1) { next; } # deleted from group
 8199:                     if (($start!=0) && ($start>$now)) { next; }
 8200:                     if (($end!=0) && ($end<$now)) {
 8201:                         if ($access_end && $access_end < $now) {
 8202:                             if ($access_end - $end < 86400) {
 8203:                                 push(@usersgroups,$group);
 8204:                             }
 8205:                         }
 8206:                         next;
 8207:                     }
 8208:                     push(@usersgroups,$group);
 8209:                 }
 8210:             }
 8211:         }
 8212:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8213:         $grouplist = join(':',@usersgroups);
 8214:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8215:     }
 8216:     return @usersgroups;
 8217: }
 8218: 
 8219: sub devalidate_getgroups_cache {
 8220:     my ($udom,$uname,$cdom,$cnum)=@_;
 8221:     my $courseid = $cdom.'_'.$cnum;
 8222: 
 8223:     my $hashid="$udom:$uname:$courseid";
 8224:     &devalidate_cache_new('getgroups',$hashid);
 8225: }
 8226: 
 8227: # ------------------------------------------------------------------ Plain Text
 8228: 
 8229: sub plaintext {
 8230:     my ($short,$type,$cid,$forcedefault) = @_;
 8231:     if ($short =~ m{^cr/}) {
 8232: 	return (split('/',$short))[-1];
 8233:     }
 8234:     if (!defined($cid)) {
 8235:         $cid = $env{'request.course.id'};
 8236:     }
 8237:     my %rolenames = (
 8238:                       Course    => 'std',
 8239:                       Community => 'alt1',
 8240:                     );
 8241:     if ($cid ne '') {
 8242:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8243:             unless ($forcedefault) {
 8244:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8245:                 &Apache::lonlocal::mt_escape(\$roletext);
 8246:                 return &Apache::lonlocal::mt($roletext);
 8247:             }
 8248:         }
 8249:     }
 8250:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8251:         (defined($rolenames{$type})) && 
 8252:         (defined($prp{$short}{$rolenames{$type}}))) {
 8253:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8254:     } elsif ($cid ne '') {
 8255:         my $crstype = $env{'course.'.$cid.'.type'};
 8256:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8257:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8258:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8259:         }
 8260:     }
 8261:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8262: }
 8263: 
 8264: # ----------------------------------------------------------------- Assign Role
 8265: 
 8266: sub assignrole {
 8267:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8268:         $context)=@_;
 8269:     my $mrole;
 8270:     if ($role =~ /^cr\//) {
 8271:         my $cwosec=$url;
 8272:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8273: 	unless (&allowed('ccr',$cwosec)) {
 8274:            my $refused = 1;
 8275:            if ($context eq 'requestcourses') {
 8276:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8277:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8278:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8279:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8280:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8281:                            if ($crsenv{'internal.courseowner'} eq
 8282:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8283:                                $refused = '';
 8284:                            }
 8285:                        }
 8286:                    }
 8287:                }
 8288:            }
 8289:            if ($refused) {
 8290:                &logthis('Refused custom assignrole: '.
 8291:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8292:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8293:                return 'refused';
 8294:            }
 8295:         }
 8296:         $mrole='cr';
 8297:     } elsif ($role =~ /^gr\//) {
 8298:         my $cwogrp=$url;
 8299:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8300:         unless (&allowed('mdg',$cwogrp)) {
 8301:             &logthis('Refused group assignrole: '.
 8302:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8303:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8304:             return 'refused';
 8305:         }
 8306:         $mrole='gr';
 8307:     } else {
 8308:         my $cwosec=$url;
 8309:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8310:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8311:             my $refused;
 8312:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8313:                 if (!(&allowed('c'.$role,$url))) {
 8314:                     $refused = 1;
 8315:                 }
 8316:             } else {
 8317:                 $refused = 1;
 8318:             }
 8319:             if ($refused) {
 8320:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8321:                 if (!$selfenroll && $context eq 'course') {
 8322:                     my %crsenv;
 8323:                     if ($role eq 'cc' || $role eq 'co') {
 8324:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8325:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8326:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8327:                                 if ($crsenv{'internal.courseowner'} eq 
 8328:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8329:                                     $refused = '';
 8330:                                 }
 8331:                             }
 8332:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8333:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8334:                                 if ($crsenv{'internal.courseowner'} eq 
 8335:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8336:                                     $refused = '';
 8337:                                 }
 8338:                             }
 8339:                         }
 8340:                     }
 8341:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8342:                     $refused = '';
 8343:                 } elsif ($context eq 'requestcourses') {
 8344:                     my @possroles = ('st','ta','ep','in','cc','co');
 8345:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8346:                         my $wrongcc;
 8347:                         if ($cnum =~ /^$match_community$/) {
 8348:                             $wrongcc = 1 if ($role eq 'cc');
 8349:                         } else {
 8350:                             $wrongcc = 1 if ($role eq 'co');
 8351:                         }
 8352:                         unless ($wrongcc) {
 8353:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8354:                             if ($crsenv{'internal.courseowner'} eq 
 8355:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8356:                                 $refused = '';
 8357:                             }
 8358:                         }
 8359:                     }
 8360:                 } elsif ($context eq 'requestauthor') {
 8361:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8362:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8363:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8364:                             $refused = '';
 8365:                         } else {
 8366:                             my %domdefaults = &get_domain_defaults($udom);
 8367:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8368:                                 my $checkbystatus;
 8369:                                 if ($env{'user.adv'}) { 
 8370:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8371:                                     if ($disposition eq 'automatic') {
 8372:                                         $refused = '';
 8373:                                     } elsif ($disposition eq '') {
 8374:                                         $checkbystatus = 1;
 8375:                                     } 
 8376:                                 } else {
 8377:                                     $checkbystatus = 1;
 8378:                                 }
 8379:                                 if ($checkbystatus) {
 8380:                                     if ($env{'environment.inststatus'}) {
 8381:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8382:                                         foreach my $type (@inststatuses) {
 8383:                                             if (($type ne '') &&
 8384:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8385:                                                 $refused = '';
 8386:                                             }
 8387:                                         }
 8388:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8389:                                         $refused = '';
 8390:                                     }
 8391:                                 }
 8392:                             }
 8393:                         }
 8394:                     }
 8395:                 }
 8396:                 if ($refused) {
 8397:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8398:                              ' '.$role.' '.$end.' '.$start.' by '.
 8399: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8400:                     return 'refused';
 8401:                 }
 8402:             }
 8403:         } elsif ($role eq 'au') {
 8404:             if ($url ne '/'.$udom.'/') {
 8405:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8406:                          ' to assign author role for '.$uname.':'.$udom.
 8407:                          ' in domain: '.$url.' refused (wrong domain).');
 8408:                 return 'refused';
 8409:             }
 8410:         }
 8411:         $mrole=$role;
 8412:     }
 8413:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8414:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8415:     if ($end) { $command.='_'.$end; }
 8416:     if ($start) {
 8417: 	if ($end) { 
 8418:            $command.='_'.$start; 
 8419:         } else {
 8420:            $command.='_0_'.$start;
 8421:         }
 8422:     }
 8423:     my $origstart = $start;
 8424:     my $origend = $end;
 8425:     my $delflag;
 8426: # actually delete
 8427:     if ($deleteflag) {
 8428: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8429: # modify command to delete the role
 8430:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8431:                 "$udom:$uname:$url".'_'."$mrole";
 8432: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8433: # set start and finish to negative values for userrolelog
 8434:            $start=-1;
 8435:            $end=-1;
 8436:            $delflag = 1;
 8437:         }
 8438:     }
 8439: # send command
 8440:     my $answer=&reply($command,&homeserver($uname,$udom));
 8441: # log new user role if status is ok
 8442:     if ($answer eq 'ok') {
 8443: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8444:         if (($role eq 'cc') || ($role eq 'in') ||
 8445:             ($role eq 'ep') || ($role eq 'ad') ||
 8446:             ($role eq 'ta') || ($role eq 'st') ||
 8447:             ($role=~/^cr/) || ($role eq 'gr') ||
 8448:             ($role eq 'co')) {
 8449: # for course roles, perform group memberships changes triggered by role change.
 8450:             unless ($role =~ /^gr/) {
 8451:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8452:                                                  $origstart,$selfenroll,$context);
 8453:             }
 8454:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8455:                            $selfenroll,$context);
 8456:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8457:                  ($role eq 'au') || ($role eq 'dc')) {
 8458:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8459:                            $context);
 8460:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8461:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8462:                              $context); 
 8463:         }
 8464:         if ($role eq 'cc') {
 8465:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8466:         }
 8467:     }
 8468:     return $answer;
 8469: }
 8470: 
 8471: sub autoupdate_coowners {
 8472:     my ($url,$end,$start,$uname,$udom) = @_;
 8473:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8474:     if (($cdom ne '') && ($cnum ne '')) {
 8475:         my $now = time;
 8476:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8477:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8478:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8479:             my $instcode = $coursehash{'internal.coursecode'};
 8480:             if ($instcode ne '') {
 8481:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8482:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8483:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8484:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8485:                         if ($result eq 'valid') {
 8486:                             if ($coursehash{'internal.co-owners'}) {
 8487:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8488:                                     push(@newcoowners,$coowner);
 8489:                                 }
 8490:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8491:                                     push(@newcoowners,$uname.':'.$udom);
 8492:                                 }
 8493:                                 @newcoowners = sort(@newcoowners);
 8494:                             } else {
 8495:                                 push(@newcoowners,$uname.':'.$udom);
 8496:                             }
 8497:                         } else {
 8498:                             if ($coursehash{'internal.co-owners'}) {
 8499:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8500:                                     unless ($coowner eq $uname.':'.$udom) {
 8501:                                         push(@newcoowners,$coowner);
 8502:                                     }
 8503:                                 }
 8504:                                 unless (@newcoowners > 0) {
 8505:                                     $delcoowners = 1;
 8506:                                     $coowners = '';
 8507:                                 }
 8508:                             }
 8509:                         }
 8510:                         if (@newcoowners || $delcoowners) {
 8511:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8512:                                             $delcoowners,@newcoowners);
 8513:                         }
 8514:                     }
 8515:                 }
 8516:             }
 8517:         }
 8518:     }
 8519: }
 8520: 
 8521: sub store_coowners {
 8522:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8523:     my $cid = $cdom.'_'.$cnum;
 8524:     my ($coowners,$delresult,$putresult);
 8525:     if (@newcoowners) {
 8526:         $coowners = join(',',@newcoowners);
 8527:         my %coownershash = (
 8528:                             'internal.co-owners' => $coowners,
 8529:                            );
 8530:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8531:         if ($putresult eq 'ok') {
 8532:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8533:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8534:             }
 8535:         }
 8536:     }
 8537:     if ($delcoowners) {
 8538:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8539:         if ($delresult eq 'ok') {
 8540:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8541:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8542:             }
 8543:         }
 8544:     }
 8545:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8546:         my %crsinfo =
 8547:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8548:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8549:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8550:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8551:         }
 8552:     }
 8553: }
 8554: 
 8555: # -------------------------------------------------- Modify user authentication
 8556: # Overrides without validation
 8557: 
 8558: sub modifyuserauth {
 8559:     my ($udom,$uname,$umode,$upass)=@_;
 8560:     my $uhome=&homeserver($uname,$udom);
 8561:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8562:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8563:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8564:              ' in domain '.$env{'request.role.domain'});  
 8565:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8566: 		     &escape($upass),$uhome);
 8567:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8568:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8569:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8570:     &log($udom,,$uname,$uhome,
 8571:         'Authentication changed by '.$env{'user.domain'}.', '.
 8572:                                      $env{'user.name'}.', '.$umode.
 8573:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8574:     unless ($reply eq 'ok') {
 8575:         &logthis('Authentication mode error: '.$reply);
 8576: 	return 'error: '.$reply;
 8577:     }   
 8578:     return 'ok';
 8579: }
 8580: 
 8581: # --------------------------------------------------------------- Modify a user
 8582: 
 8583: sub modifyuser {
 8584:     my ($udom,    $uname, $uid,
 8585:         $umode,   $upass, $first,
 8586:         $middle,  $last,  $gene,
 8587:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8588:     $udom= &LONCAPA::clean_domain($udom);
 8589:     $uname=&LONCAPA::clean_username($uname);
 8590:     my $showcandelete = 'none';
 8591:     if (ref($candelete) eq 'ARRAY') {
 8592:         if (@{$candelete} > 0) {
 8593:             $showcandelete = join(', ',@{$candelete});
 8594:         }
 8595:     }
 8596:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8597:              $umode.', '.$first.', '.$middle.', '.
 8598: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8599:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8600:                                      ' desiredhome not specified'). 
 8601:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8602:              ' in domain '.$env{'request.role.domain'});
 8603:     my $uhome=&homeserver($uname,$udom,'true');
 8604:     my $newuser;
 8605:     if ($uhome eq 'no_host') {
 8606:         $newuser = 1;
 8607:     }
 8608: # ----------------------------------------------------------------- Create User
 8609:     if (($uhome eq 'no_host') && 
 8610: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8611:         my $unhome='';
 8612:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8613:             $unhome = $desiredhome;
 8614: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8615: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8616:         } else { # load balancing routine for determining $unhome
 8617:             my $loadm=10000000;
 8618: 	    my %servers = &get_servers($udom,'library');
 8619: 	    foreach my $tryserver (keys(%servers)) {
 8620: 		my $answer=reply('load',$tryserver);
 8621: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8622: 		    $loadm=$answer;
 8623: 		    $unhome=$tryserver;
 8624: 		}
 8625: 	    }
 8626:         }
 8627:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8628: 	    return 'error: unable to find a home server for '.$uname.
 8629:                    ' in domain '.$udom;
 8630:         }
 8631:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8632:                          &escape($upass),$unhome);
 8633: 	unless ($reply eq 'ok') {
 8634:             return 'error: '.$reply;
 8635:         }   
 8636:         $uhome=&homeserver($uname,$udom,'true');
 8637:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8638: 	    return 'error: unable verify users home machine.';
 8639:         }
 8640:     }   # End of creation of new user
 8641: # ---------------------------------------------------------------------- Add ID
 8642:     if ($uid) {
 8643:        $uid=~tr/A-Z/a-z/;
 8644:        my %uidhash=&idrget($udom,$uname);
 8645:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8646:          && (!$forceid)) {
 8647: 	  unless ($uid eq $uidhash{$uname}) {
 8648: 	      return 'error: user id "'.$uid.'" does not match '.
 8649:                   'current user id "'.$uidhash{$uname}.'".';
 8650:           }
 8651:        } else {
 8652: 	  &idput($udom,($uname => $uid));
 8653:        }
 8654:     }
 8655: # -------------------------------------------------------------- Add names, etc
 8656:     my @tmp=&get('environment',
 8657: 		   ['firstname','middlename','lastname','generation','id',
 8658:                     'permanentemail','inststatus'],
 8659: 		   $udom,$uname);
 8660:     my (%names,%oldnames);
 8661:     if ($tmp[0] =~ m/^error:.*/) { 
 8662:         %names=(); 
 8663:     } else {
 8664:         %names = @tmp;
 8665:         %oldnames = %names;
 8666:     }
 8667: #
 8668: # If name, email and/or uid are blank (e.g., because an uploaded file
 8669: # of users did not contain them), do not overwrite existing values
 8670: # unless field is in $candelete array ref.  
 8671: #
 8672: 
 8673:     my @fields = ('firstname','middlename','lastname','generation',
 8674:                   'permanentemail','id');
 8675:     my %newvalues;
 8676:     if (ref($candelete) eq 'ARRAY') {
 8677:         foreach my $field (@fields) {
 8678:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8679:                 if ($field eq 'firstname') {
 8680:                     $names{$field} = $first;
 8681:                 } elsif ($field eq 'middlename') {
 8682:                     $names{$field} = $middle;
 8683:                 } elsif ($field eq 'lastname') {
 8684:                     $names{$field} = $last;
 8685:                 } elsif ($field eq 'generation') { 
 8686:                     $names{$field} = $gene;
 8687:                 } elsif ($field eq 'permanentemail') {
 8688:                     $names{$field} = $email;
 8689:                 } elsif ($field eq 'id') {
 8690:                     $names{$field}  = $uid;
 8691:                 }
 8692:             }
 8693:         }
 8694:     }
 8695:     if ($first)  { $names{'firstname'}  = $first; }
 8696:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8697:     if ($last)   { $names{'lastname'}   = $last; }
 8698:     if (defined($gene))   { $names{'generation'} = $gene; }
 8699:     if ($email) {
 8700:        $email=~s/[^\w\@\.\-\,]//gs;
 8701:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8702:     }
 8703:     if ($uid) { $names{'id'}  = $uid; }
 8704:     if (defined($inststatus)) {
 8705:         $names{'inststatus'} = '';
 8706:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8707:         if (ref($usertypes) eq 'HASH') {
 8708:             my @okstatuses; 
 8709:             foreach my $item (split(/:/,$inststatus)) {
 8710:                 if (defined($usertypes->{$item})) {
 8711:                     push(@okstatuses,$item);  
 8712:                 }
 8713:             }
 8714:             if (@okstatuses) {
 8715:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8716:             }
 8717:         }
 8718:     }
 8719:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8720:                  $umode.', '.$first.', '.$middle.', '.
 8721:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8722:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8723:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8724:     } else {
 8725:         $logmsg .= ' during self creation';
 8726:     }
 8727:     my $changed;
 8728:     if ($newuser) {
 8729:         $changed = 1;
 8730:     } else {
 8731:         foreach my $field (@fields) {
 8732:             if ($names{$field} ne $oldnames{$field}) {
 8733:                 $changed = 1;
 8734:                 last;
 8735:             }
 8736:         }
 8737:     }
 8738:     unless ($changed) {
 8739:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8740:         &logthis($logmsg);
 8741:         return 'ok';
 8742:     }
 8743:     my $reply = &put('environment', \%names, $udom,$uname);
 8744:     if ($reply ne 'ok') { 
 8745:         return 'error: '.$reply;
 8746:     }
 8747:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8748:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8749:     }
 8750:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8751:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8752:     $logmsg = 'Success modifying user '.$logmsg;
 8753:     &logthis($logmsg);
 8754:     return 'ok';
 8755: }
 8756: 
 8757: # -------------------------------------------------------------- Modify student
 8758: 
 8759: sub modifystudent {
 8760:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8761:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8762:         $selfenroll,$context,$inststatus,$credits)=@_;
 8763:     if (!$cid) {
 8764: 	unless ($cid=$env{'request.course.id'}) {
 8765: 	    return 'not_in_class';
 8766: 	}
 8767:     }
 8768: # --------------------------------------------------------------- Make the user
 8769:     my $reply=&modifyuser
 8770: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8771:          $desiredhome,$email,$inststatus);
 8772:     unless ($reply eq 'ok') { return $reply; }
 8773:     # This will cause &modify_student_enrollment to get the uid from the
 8774:     # student's environment
 8775:     $uid = undef if (!$forceid);
 8776:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8777:                                         $gene,$usec,$end,$start,$type,$locktype,
 8778:                                         $cid,$selfenroll,$context,$credits);
 8779:     return $reply;
 8780: }
 8781: 
 8782: sub modify_student_enrollment {
 8783:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8784:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8785:     my ($cdom,$cnum,$chome);
 8786:     if (!$cid) {
 8787: 	unless ($cid=$env{'request.course.id'}) {
 8788: 	    return 'not_in_class';
 8789: 	}
 8790: 	$cdom=$env{'course.'.$cid.'.domain'};
 8791: 	$cnum=$env{'course.'.$cid.'.num'};
 8792:     } else {
 8793: 	($cdom,$cnum)=split(/_/,$cid);
 8794:     }
 8795:     $chome=$env{'course.'.$cid.'.home'};
 8796:     if (!$chome) {
 8797: 	$chome=&homeserver($cnum,$cdom);
 8798:     }
 8799:     if (!$chome) { return 'unknown_course'; }
 8800:     # Make sure the user exists
 8801:     my $uhome=&homeserver($uname,$udom);
 8802:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8803: 	return 'error: no such user';
 8804:     }
 8805:     # Get student data if we were not given enough information
 8806:     if (!defined($first)  || $first  eq '' || 
 8807:         !defined($last)   || $last   eq '' || 
 8808:         !defined($uid)    || $uid    eq '' || 
 8809:         !defined($middle) || $middle eq '' || 
 8810:         !defined($gene)   || $gene   eq '') {
 8811:         # They did not supply us with enough data to enroll the student, so
 8812:         # we need to pick up more information.
 8813:         my %tmp = &get('environment',
 8814:                        ['firstname','middlename','lastname', 'generation','id']
 8815:                        ,$udom,$uname);
 8816: 
 8817:         #foreach my $key (keys(%tmp)) {
 8818:         #    &logthis("key $key = ".$tmp{$key});
 8819:         #}
 8820:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8821:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8822:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8823:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8824:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8825:     }
 8826:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8827:     my $user = "$uname:$udom";
 8828:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8829:     my $reply=cput('classlist',
 8830: 		   {$user => 
 8831: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8832: 		   $cdom,$cnum);
 8833:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8834:         &devalidate_getsection_cache($udom,$uname,$cid);
 8835:     } else { 
 8836: 	return 'error: '.$reply;
 8837:     }
 8838:     # Add student role to user
 8839:     my $uurl='/'.$cid;
 8840:     $uurl=~s/\_/\//g;
 8841:     if ($usec) {
 8842: 	$uurl.='/'.$usec;
 8843:     }
 8844:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8845:                              $selfenroll,$context);
 8846:     if ($result ne 'ok') {
 8847:         if ($old_entry{$user} ne '') {
 8848:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8849:         } else {
 8850:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8851:         }
 8852:     }
 8853:     return $result; 
 8854: }
 8855: 
 8856: sub format_name {
 8857:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8858:     my $name;
 8859:     if ($first ne 'lastname') {
 8860: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8861:     } else {
 8862: 	if ($lastname=~/\S/) {
 8863: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8864: 	    $name=~s/\s+,/,/;
 8865: 	} else {
 8866: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8867: 	}
 8868:     }
 8869:     $name=~s/^\s+//;
 8870:     $name=~s/\s+$//;
 8871:     $name=~s/\s+/ /g;
 8872:     return $name;
 8873: }
 8874: 
 8875: # ------------------------------------------------- Write to course preferences
 8876: 
 8877: sub writecoursepref {
 8878:     my ($courseid,%prefs)=@_;
 8879:     $courseid=~s/^\///;
 8880:     $courseid=~s/\_/\//g;
 8881:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8882:     my $chome=homeserver($cnum,$cdomain);
 8883:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8884: 	return 'error: no such course';
 8885:     }
 8886:     my $cstring='';
 8887:     foreach my $pref (keys(%prefs)) {
 8888: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8889:     }
 8890:     $cstring=~s/\&$//;
 8891:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8892: }
 8893: 
 8894: # ---------------------------------------------------------- Make/modify course
 8895: 
 8896: sub createcourse {
 8897:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8898:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8899:     $url=&declutter($url);
 8900:     my $cid='';
 8901:     if ($context eq 'requestcourses') {
 8902:         my $can_create = 0;
 8903:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8904:         if ($udom eq $ownerdom) {
 8905:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8906:                                   $context)) {
 8907:                 $can_create = 1;
 8908:             }
 8909:         } else {
 8910:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8911:                                            $category);
 8912:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8913:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8914:                 if (@curr > 0) {
 8915:                     my @options = qw(approval validate autolimit);
 8916:                     my $optregex = join('|',@options);
 8917:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8918:                         $can_create = 1;
 8919:                     }
 8920:                 }
 8921:             }
 8922:         }
 8923:         if ($can_create) {
 8924:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8925:                 unless (&allowed('ccc',$udom)) {
 8926:                     return 'refused'; 
 8927:                 }
 8928:             }
 8929:         } else {
 8930:             return 'refused';
 8931:         }
 8932:     } elsif (!&allowed('ccc',$udom)) {
 8933:         return 'refused';
 8934:     }
 8935: # --------------------------------------------------------------- Get Unique ID
 8936:     my $uname;
 8937:     if ($cnum =~ /^$match_courseid$/) {
 8938:         my $chome=&homeserver($cnum,$udom,'true');
 8939:         if (($chome eq '') || ($chome eq 'no_host')) {
 8940:             $uname = $cnum;
 8941:         } else {
 8942:             $uname = &generate_coursenum($udom,$crstype);
 8943:         }
 8944:     } else {
 8945:         $uname = &generate_coursenum($udom,$crstype);
 8946:     }
 8947:     return $uname if ($uname =~ /^error/);
 8948: # -------------------------------------------------- Check supplied server name
 8949:     if (!defined($course_server)) {
 8950:         if (defined(&domain($udom,'primary'))) {
 8951:             $course_server = &domain($udom,'primary');
 8952:         } else {
 8953:             $course_server = $env{'user.home'}; 
 8954:         }
 8955:     }
 8956:     my %host_servers =
 8957:         &Apache::lonnet::get_servers($udom,'library');
 8958:     unless ($host_servers{$course_server}) {
 8959:         return 'error: invalid home server for course: '.$course_server;
 8960:     }
 8961: # ------------------------------------------------------------- Make the course
 8962:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8963:                       $course_server);
 8964:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8965:     my $uhome=&homeserver($uname,$udom,'true');
 8966:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8967: 	return 'error: no such course';
 8968:     }
 8969: # ----------------------------------------------------------------- Course made
 8970: # log existence
 8971:     my $now = time;
 8972:     my $newcourse = {
 8973:                     $udom.'_'.$uname => {
 8974:                                      description => $description,
 8975:                                      inst_code   => $inst_code,
 8976:                                      owner       => $course_owner,
 8977:                                      type        => $crstype,
 8978:                                      creator     => $env{'user.name'}.':'.
 8979:                                                     $env{'user.domain'},
 8980:                                      created     => $now,
 8981:                                      context     => $context,
 8982:                                                 },
 8983:                     };
 8984:     &courseidput($udom,$newcourse,$uhome,'notime');
 8985: # set toplevel url
 8986:     my $topurl=$url;
 8987:     unless ($nonstandard) {
 8988: # ------------------------------------------ For standard courses, make top url
 8989:         my $mapurl=&clutter($url);
 8990:         if ($mapurl eq '/res/') { $mapurl=''; }
 8991:         $env{'form.initmap'}=(<<ENDINITMAP);
 8992: <map>
 8993: <resource id="1" type="start"></resource>
 8994: <resource id="2" src="$mapurl"></resource>
 8995: <resource id="3" type="finish"></resource>
 8996: <link index="1" from="1" to="2"></link>
 8997: <link index="2" from="2" to="3"></link>
 8998: </map>
 8999: ENDINITMAP
 9000:         $topurl=&declutter(
 9001:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9002:                           );
 9003:     }
 9004: # ----------------------------------------------------------- Write preferences
 9005:     &writecoursepref($udom.'_'.$uname,
 9006:                      ('description'              => $description,
 9007:                       'url'                      => $topurl,
 9008:                       'internal.creator'         => $env{'user.name'}.':'.
 9009:                                                     $env{'user.domain'},
 9010:                       'internal.created'         => $now,
 9011:                       'internal.creationcontext' => $context)
 9012:                     );
 9013:     return '/'.$udom.'/'.$uname;
 9014: }
 9015: 
 9016: # ------------------------------------------------------------------- Create ID
 9017: sub generate_coursenum {
 9018:     my ($udom,$crstype) = @_;
 9019:     my $domdesc = &domain($udom);
 9020:     return 'error: invalid domain' if ($domdesc eq '');
 9021:     my $first;
 9022:     if ($crstype eq 'Community') {
 9023:         $first = '0';
 9024:     } else {
 9025:         $first = int(1+rand(9)); 
 9026:     } 
 9027:     my $uname=$first.
 9028:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9029:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9030:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9031: # ----------------------------------------------- Make sure that does not exist
 9032:     my $uhome=&homeserver($uname,$udom,'true');
 9033:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9034:         if ($crstype eq 'Community') {
 9035:             $first = '0';
 9036:         } else {
 9037:             $first = int(1+rand(9));
 9038:         }
 9039:         $uname=$first.
 9040:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9041:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9042:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9043:         $uhome=&homeserver($uname,$udom,'true');
 9044:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9045:             return 'error: unable to generate unique course-ID';
 9046:         }
 9047:     }
 9048:     return $uname;
 9049: }
 9050: 
 9051: sub is_course {
 9052:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9053:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9054: 
 9055:     return unless $cdom and $cnum;
 9056: 
 9057:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9058:         '.');
 9059: 
 9060:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9061:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9062: }
 9063: 
 9064: sub store_userdata {
 9065:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9066:     my $result;
 9067:     if ($datakey ne '') {
 9068:         if (ref($storehash) eq 'HASH') {
 9069:             if ($udom eq '' || $uname eq '') {
 9070:                 $udom = $env{'user.domain'};
 9071:                 $uname = $env{'user.name'};
 9072:             }
 9073:             my $uhome=&homeserver($uname,$udom);
 9074:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9075:                 $result = 'error: no_host';
 9076:             } else {
 9077:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9078:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9079: 
 9080:                 my $namevalue='';
 9081:                 foreach my $key (keys(%{$storehash})) {
 9082:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9083:                 }
 9084:                 $namevalue=~s/\&$//;
 9085:                 unless ($namespace eq 'courserequests') {
 9086:                     $datakey = &escape($datakey);
 9087:                 }
 9088:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9089:                                   $namevalue,$uhome);
 9090:             }
 9091:         } else {
 9092:             $result = 'error: data to store was not a hash reference'; 
 9093:         }
 9094:     } else {
 9095:         $result= 'error: invalid requestkey'; 
 9096:     }
 9097:     return $result;
 9098: }
 9099: 
 9100: # ---------------------------------------------------------- Assign Custom Role
 9101: 
 9102: sub assigncustomrole {
 9103:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9104:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9105:                        $end,$start,$deleteflag,$selfenroll,$context);
 9106: }
 9107: 
 9108: # ----------------------------------------------------------------- Revoke Role
 9109: 
 9110: sub revokerole {
 9111:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9112:     my $now=time;
 9113:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9114: }
 9115: 
 9116: # ---------------------------------------------------------- Revoke Custom Role
 9117: 
 9118: sub revokecustomrole {
 9119:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9120:     my $now=time;
 9121:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9122:            $deleteflag,$selfenroll,$context);
 9123: }
 9124: 
 9125: # ------------------------------------------------------------ Disk usage
 9126: sub diskusage {
 9127:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9128:     $directorypath =~ s/\/$//;
 9129:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9130:                        .&escape($getpropath).':'.&escape($uname).':'
 9131:                        .&escape($udom),homeserver($uname,$udom));
 9132:     if ($listing eq 'unknown_cmd') {
 9133:         if ($getpropath) {
 9134:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9135:         }
 9136:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9137:     }
 9138:     return $listing;
 9139: }
 9140: 
 9141: sub is_locked {
 9142:     my ($file_name, $domain, $user, $which) = @_;
 9143:     my @check;
 9144:     my $is_locked;
 9145:     push (@check,$file_name);
 9146:     my %locked = &get('file_permissions',\@check,
 9147: 		      $env{'user.domain'},$env{'user.name'});
 9148:     my ($tmp)=keys(%locked);
 9149:     if ($tmp=~/^error:/) { undef(%locked); }
 9150:     
 9151:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9152:         $is_locked = 'false';
 9153:         foreach my $entry (@{$locked{$file_name}}) {
 9154:            if (ref($entry) eq 'ARRAY') {
 9155:                $is_locked = 'true';
 9156:                if (ref($which) eq 'ARRAY') {
 9157:                    push(@{$which},$entry);
 9158:                } else {
 9159:                    last;
 9160:                }
 9161:            }
 9162:        }
 9163:     } else {
 9164:         $is_locked = 'false';
 9165:     }
 9166:     return $is_locked;
 9167: }
 9168: 
 9169: sub declutter_portfile {
 9170:     my ($file) = @_;
 9171:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9172:     return $file;
 9173: }
 9174: 
 9175: # ------------------------------------------------------------- Mark as Read Only
 9176: 
 9177: sub mark_as_readonly {
 9178:     my ($domain,$user,$files,$what) = @_;
 9179:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9180:     my ($tmp)=keys(%current_permissions);
 9181:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9182:     foreach my $file (@{$files}) {
 9183: 	$file = &declutter_portfile($file);
 9184:         push(@{$current_permissions{$file}},$what);
 9185:     }
 9186:     &put('file_permissions',\%current_permissions,$domain,$user);
 9187:     return;
 9188: }
 9189: 
 9190: # ------------------------------------------------------------Save Selected Files
 9191: 
 9192: sub save_selected_files {
 9193:     my ($user, $path, @files) = @_;
 9194:     my $filename = $user."savedfiles";
 9195:     my @other_files = &files_not_in_path($user, $path);
 9196:     open (OUT, '>'.$tmpdir.$filename);
 9197:     foreach my $file (@files) {
 9198:         print (OUT $env{'form.currentpath'}.$file."\n");
 9199:     }
 9200:     foreach my $file (@other_files) {
 9201:         print (OUT $file."\n");
 9202:     }
 9203:     close (OUT);
 9204:     return 'ok';
 9205: }
 9206: 
 9207: sub clear_selected_files {
 9208:     my ($user) = @_;
 9209:     my $filename = $user."savedfiles";
 9210:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9211:     print (OUT undef);
 9212:     close (OUT);
 9213:     return ("ok");    
 9214: }
 9215: 
 9216: sub files_in_path {
 9217:     my ($user, $path) = @_;
 9218:     my $filename = $user."savedfiles";
 9219:     my %return_files;
 9220:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9221:     while (my $line_in = <IN>) {
 9222:         chomp ($line_in);
 9223:         my @paths_and_file = split (m!/!, $line_in);
 9224:         my $file_part = pop (@paths_and_file);
 9225:         my $path_part = join ('/', @paths_and_file);
 9226:         $path_part.='/';
 9227:         my $path_and_file = $path_part.$file_part;
 9228:         if ($path_part eq $path) {
 9229:             $return_files{$file_part}= 'selected';
 9230:         }
 9231:     }
 9232:     close (IN);
 9233:     return (\%return_files);
 9234: }
 9235: 
 9236: # called in portfolio select mode, to show files selected NOT in current directory
 9237: sub files_not_in_path {
 9238:     my ($user, $path) = @_;
 9239:     my $filename = $user."savedfiles";
 9240:     my @return_files;
 9241:     my $path_part;
 9242:     open(IN, '<'.LONCAPA::.$filename);
 9243:     while (my $line = <IN>) {
 9244:         #ok, I know it's clunky, but I want it to work
 9245:         my @paths_and_file = split(m|/|, $line);
 9246:         my $file_part = pop(@paths_and_file);
 9247:         chomp($file_part);
 9248:         my $path_part = join('/', @paths_and_file);
 9249:         $path_part .= '/';
 9250:         my $path_and_file = $path_part.$file_part;
 9251:         if ($path_part ne $path) {
 9252:             push(@return_files, ($path_and_file));
 9253:         }
 9254:     }
 9255:     close(OUT);
 9256:     return (@return_files);
 9257: }
 9258: 
 9259: #------------------------------Submitted/Handedback Portfolio Files Versioning
 9260:  
 9261: sub portfiles_versioning {
 9262:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
 9263:     my $portfolio_root = '/userfiles/portfolio';
 9264:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
 9265:     foreach my $file (@{$portfiles}) {
 9266:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 9267:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 9268:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
 9269:         my $getpropath = 1;
 9270:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
 9271:                                              $stu_name,$getpropath);
 9272:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 9273:         my $new_answer = 
 9274:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
 9275:         if ($new_answer ne 'problem getting file') {
 9276:             push(@{$versioned_portfiles}, $directory.$new_answer);
 9277:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
 9278:                               [$symb,$env{'request.course.id'},'graded']);
 9279:         }
 9280:     }
 9281: }
 9282: 
 9283: sub get_next_version {
 9284:     my ($answer_name, $answer_ext, $dir_list) = @_;
 9285:     my $version;
 9286:     if (ref($dir_list) eq 'ARRAY') {
 9287:         foreach my $row (@{$dir_list}) {
 9288:             my ($file) = split(/\&/,$row,2);
 9289:             my ($file_name,$file_version,$file_ext) =
 9290:                 &file_name_version_ext($file);
 9291:             if (($file_name eq $answer_name) &&
 9292:                 ($file_ext eq $answer_ext)) {
 9293:                      # gets here if filename and extension match,
 9294:                      # regardless of version
 9295:                 if ($file_version ne '') {
 9296:                     # a versioned file is found  so save it for later
 9297:                     if ($file_version > $version) {
 9298:                         $version = $file_version;
 9299:                     }
 9300:                 }
 9301:             }
 9302:         }
 9303:     }
 9304:     $version ++;
 9305:     return($version);
 9306: }
 9307: 
 9308: sub version_selected_portfile {
 9309:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 9310:     my ($answer_name,$answer_ver,$answer_ext) =
 9311:         &file_name_version_ext($file_name);
 9312:     my $new_answer;
 9313:     $env{'form.copy'} =
 9314:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 9315:     if($env{'form.copy'} eq '-1') {
 9316:         $new_answer = 'problem getting file';
 9317:     } else {
 9318:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 9319:         my $copy_result = 
 9320:             &finishuserfileupload($stu_name,$domain,'copy',
 9321:                                   '/portfolio'.$directory.$new_answer);
 9322:     }
 9323:     undef($env{'form.copy'});
 9324:     return ($new_answer);
 9325: }
 9326: 
 9327: sub file_name_version_ext {
 9328:     my ($file)=@_;
 9329:     my @file_parts = split(/\./, $file);
 9330:     my ($name,$version,$ext);
 9331:     if (@file_parts > 1) {
 9332:         $ext=pop(@file_parts);
 9333:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 9334:             $version=pop(@file_parts);
 9335:         }
 9336:         $name=join('.',@file_parts);
 9337:     } else {
 9338:         $name=join('.',@file_parts);
 9339:     }
 9340:     return($name,$version,$ext);
 9341: }
 9342: 
 9343: #----------------------------------------------Get portfolio file permissions
 9344: 
 9345: sub get_portfile_permissions {
 9346:     my ($domain,$user) = @_;
 9347:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9348:     my ($tmp)=keys(%current_permissions);
 9349:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9350:     return \%current_permissions;
 9351: }
 9352: 
 9353: #---------------------------------------------Get portfolio file access controls
 9354: 
 9355: sub get_access_controls {
 9356:     my ($current_permissions,$group,$file) = @_;
 9357:     my %access;
 9358:     my $real_file = $file;
 9359:     $file =~ s/\.meta$//;
 9360:     if (defined($file)) {
 9361:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9362:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9363:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9364:             }
 9365:         }
 9366:     } else {
 9367:         foreach my $key (keys(%{$current_permissions})) {
 9368:             if ($key =~ /\0accesscontrol$/) {
 9369:                 if (defined($group)) {
 9370:                     if ($key !~ m-^\Q$group\E/-) {
 9371:                         next;
 9372:                     }
 9373:                 }
 9374:                 my ($fullpath) = split(/\0/,$key);
 9375:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9376:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9377:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9378:                     }
 9379:                 }
 9380:             }
 9381:         }
 9382:     }
 9383:     return %access;
 9384: }
 9385: 
 9386: sub modify_access_controls {
 9387:     my ($file_name,$changes,$domain,$user)=@_;
 9388:     my ($outcome,$deloutcome);
 9389:     my %store_permissions;
 9390:     my %new_values;
 9391:     my %new_control;
 9392:     my %translation;
 9393:     my @deletions = ();
 9394:     my $now = time;
 9395:     if (exists($$changes{'activate'})) {
 9396:         if (ref($$changes{'activate'}) eq 'HASH') {
 9397:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9398:             my $numnew = scalar(@newitems);
 9399:             for (my $i=0; $i<$numnew; $i++) {
 9400:                 my $newkey = $newitems[$i];
 9401:                 my $newid = &Apache::loncommon::get_cgi_id();
 9402:                 if ($newkey =~ /^\d+:/) { 
 9403:                     $newkey =~ s/^(\d+)/$newid/;
 9404:                     $translation{$1} = $newid;
 9405:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9406:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9407:                     $translation{$1} = $newid;
 9408:                 }
 9409:                 $new_values{$file_name."\0".$newkey} = 
 9410:                                           $$changes{'activate'}{$newitems[$i]};
 9411:                 $new_control{$newkey} = $now;
 9412:             }
 9413:         }
 9414:     }
 9415:     my %todelete;
 9416:     my %changed_items;
 9417:     foreach my $action ('delete','update') {
 9418:         if (exists($$changes{$action})) {
 9419:             if (ref($$changes{$action}) eq 'HASH') {
 9420:                 foreach my $key (keys(%{$$changes{$action}})) {
 9421:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9422:                     if ($action eq 'delete') { 
 9423:                         $todelete{$itemnum} = 1;
 9424:                     } else {
 9425:                         $changed_items{$itemnum} = $key;
 9426:                     }
 9427:                 }
 9428:             }
 9429:         }
 9430:     }
 9431:     # get lock on access controls for file.
 9432:     my $lockhash = {
 9433:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9434:                                                        ':'.$env{'user.domain'},
 9435:                    }; 
 9436:     my $tries = 0;
 9437:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9438:    
 9439:     while (($gotlock ne 'ok') && $tries <3) {
 9440:         $tries ++;
 9441:         sleep 1;
 9442:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9443:     }
 9444:     if ($gotlock eq 'ok') {
 9445:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9446:         my ($tmp)=keys(%curr_permissions);
 9447:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9448:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9449:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9450:             if (ref($curr_controls) eq 'HASH') {
 9451:                 foreach my $control_item (keys(%{$curr_controls})) {
 9452:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9453:                     if (defined($todelete{$itemnum})) {
 9454:                         push(@deletions,$file_name."\0".$control_item);
 9455:                     } else {
 9456:                         if (defined($changed_items{$itemnum})) {
 9457:                             $new_control{$changed_items{$itemnum}} = $now;
 9458:                             push(@deletions,$file_name."\0".$control_item);
 9459:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9460:                         } else {
 9461:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9462:                         }
 9463:                     }
 9464:                 }
 9465:             }
 9466:         }
 9467:         my ($group);
 9468:         if (&is_course($domain,$user)) {
 9469:             ($group,my $file) = split(/\//,$file_name,2);
 9470:         }
 9471:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9472:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9473:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9474:         #  remove lock
 9475:         my @del_lock = ($file_name."\0".'locked_access_records');
 9476:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9477:         my $sqlresult =
 9478:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9479:                                     $group);
 9480:     } else {
 9481:         $outcome = "error: could not obtain lockfile\n";  
 9482:     }
 9483:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9484: }
 9485: 
 9486: sub make_public_indefinitely {
 9487:     my (@requrl) = @_;
 9488:     return &automated_portfile_access('public',\@requrl);
 9489: }
 9490: 
 9491: sub automated_portfile_access {
 9492:     my ($accesstype,$addsref,$delsref,$info) = @_;
 9493:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
 9494:         return 'invalid';
 9495:     }
 9496:     my %urls;
 9497:     if (ref($addsref) eq 'ARRAY') {
 9498:         foreach my $requrl (@{$addsref}) {
 9499:             if (&is_portfolio_url($requrl)) {
 9500:                 unless (exists($urls{$requrl})) {
 9501:                     $urls{$requrl} = 'add';
 9502:                 }
 9503:             }
 9504:         }
 9505:     }
 9506:     if (ref($delsref) eq 'ARRAY') {
 9507:         foreach my $requrl (@{$delsref}) { 
 9508:             if (&is_portfolio_url($requrl)) {
 9509:                 unless (exists($urls{$requrl})) {
 9510:                     $urls{$requrl} = 'delete'; 
 9511:                 }
 9512:             }
 9513:         }
 9514:     }
 9515:     unless (keys(%urls)) {
 9516:         return 'invalid';
 9517:     }
 9518:     my $ip;
 9519:     if ($accesstype eq 'ip') {
 9520:         if (ref($info) eq 'HASH') {
 9521:             if ($info->{'ip'} ne '') {
 9522:                 $ip = $info->{'ip'};
 9523:             }
 9524:         }
 9525:         if ($ip eq '') {
 9526:             return 'invalid';
 9527:         }
 9528:     }
 9529:     my $errors;
 9530:     my $now = time;
 9531:     my %current_perms;
 9532:     foreach my $requrl (sort(keys(%urls))) {
 9533:         my $action;
 9534:         if ($urls{$requrl} eq 'add') {
 9535:             $action = 'activate';
 9536:         } else {
 9537:             $action = 'none';
 9538:         }
 9539:         my $aclnum = 0;
 9540:         my (undef,$udom,$unum,$file_name,$group) =
 9541:             &parse_portfolio_url($requrl);
 9542:         unless (exists($current_perms{$unum.':'.$udom})) {
 9543:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
 9544:         }
 9545:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
 9546:                                                    $group,$file_name);
 9547:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9548:             my ($num,$scope,$end,$start) = 
 9549:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9550:             if ($scope eq $accesstype) {
 9551:                 if (($start <= $now) && ($end == 0)) {
 9552:                     if ($accesstype eq 'ip') {
 9553:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
 9554:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
 9555:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
 9556:                                     if ($urls{$requrl} eq 'add') {
 9557:                                         $action = 'none';
 9558:                                         last;
 9559:                                     } else {
 9560:                                         $action = 'delete';
 9561:                                         $aclnum = $num;
 9562:                                         last;
 9563:                                     }
 9564:                                 }
 9565:                             }
 9566:                         }
 9567:                     } elsif ($accesstype eq 'public') {
 9568:                         if ($urls{$requrl} eq 'add') {
 9569:                             $action = 'none';
 9570:                             last;
 9571:                         } else {
 9572:                             $action = 'delete';
 9573:                             $aclnum = $num;
 9574:                             last;
 9575:                         }
 9576:                     }
 9577:                 } elsif ($accesstype eq 'public') {
 9578:                     $action = 'update';
 9579:                     $aclnum = $num;
 9580:                     last;
 9581:                 }
 9582:             }
 9583:         }
 9584:         if ($action eq 'none') {
 9585:             next;
 9586:         } else {
 9587:             my %changes;
 9588:             my $newend = 0;
 9589:             my $newstart = $now;
 9590:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
 9591:             $changes{$action}{$newkey} = {
 9592:                 type => $accesstype,
 9593:                 time => {
 9594:                     start => $newstart,
 9595:                     end   => $newend,
 9596:                 },
 9597:             };
 9598:             if ($accesstype eq 'ip') {
 9599:                 $changes{$action}{$newkey}{'ip'} = [$ip];
 9600:             }
 9601:             my ($outcome,$deloutcome,$new_values,$translation) =
 9602:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9603:             unless ($outcome eq 'ok') {
 9604:                 $errors .= $outcome.' ';
 9605:             }
 9606:         }
 9607:     }
 9608:     if ($errors) {
 9609:         $errors =~ s/\s$//;
 9610:         return $errors;
 9611:     } else {
 9612:         return 'ok';
 9613:     }
 9614: }
 9615: 
 9616: #------------------------------------------------------Get Marked as Read Only
 9617: 
 9618: sub get_marked_as_readonly {
 9619:     my ($domain,$user,$what,$group) = @_;
 9620:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9621:     my @readonly_files;
 9622:     my $cmp1=$what;
 9623:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9624:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9625:         if (defined($group)) {
 9626:             if ($file_name !~ m-^\Q$group\E/-) {
 9627:                 next;
 9628:             }
 9629:         }
 9630:         if (ref($value) eq "ARRAY"){
 9631:             foreach my $stored_what (@{$value}) {
 9632:                 my $cmp2=$stored_what;
 9633:                 if (ref($stored_what) eq 'ARRAY') {
 9634:                     $cmp2=join('',@{$stored_what});
 9635:                 }
 9636:                 if ($cmp1 eq $cmp2) {
 9637:                     push(@readonly_files, $file_name);
 9638:                     last;
 9639:                 } elsif (!defined($what)) {
 9640:                     push(@readonly_files, $file_name);
 9641:                     last;
 9642:                 }
 9643:             }
 9644:         }
 9645:     }
 9646:     return @readonly_files;
 9647: }
 9648: #-----------------------------------------------------------Get Marked as Read Only Hash
 9649: 
 9650: sub get_marked_as_readonly_hash {
 9651:     my ($current_permissions,$group,$what) = @_;
 9652:     my %readonly_files;
 9653:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9654:         if (defined($group)) {
 9655:             if ($file_name !~ m-^\Q$group\E/-) {
 9656:                 next;
 9657:             }
 9658:         }
 9659:         if (ref($value) eq "ARRAY"){
 9660:             foreach my $stored_what (@{$value}) {
 9661:                 if (ref($stored_what) eq 'ARRAY') {
 9662:                     foreach my $lock_descriptor(@{$stored_what}) {
 9663:                         if ($lock_descriptor eq 'graded') {
 9664:                             $readonly_files{$file_name} = 'graded';
 9665:                         } elsif ($lock_descriptor eq 'handback') {
 9666:                             $readonly_files{$file_name} = 'handback';
 9667:                         } else {
 9668:                             if (!exists($readonly_files{$file_name})) {
 9669:                                 $readonly_files{$file_name} = 'locked';
 9670:                             }
 9671:                         }
 9672:                     }
 9673:                 } 
 9674:             }
 9675:         } 
 9676:     }
 9677:     return %readonly_files;
 9678: }
 9679: # ------------------------------------------------------------ Unmark as Read Only
 9680: 
 9681: sub unmark_as_readonly {
 9682:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9683:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9684:     my ($domain,$user,$what,$file_name,$group) = @_;
 9685:     $file_name = &declutter_portfile($file_name);
 9686:     my $symb_crs = $what;
 9687:     if (ref($what)) { $symb_crs=join('',@$what); }
 9688:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9689:     my ($tmp)=keys(%current_permissions);
 9690:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9691:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9692:     foreach my $file (@readonly_files) {
 9693: 	my $clean_file = &declutter_portfile($file);
 9694: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9695: 	my $current_locks = $current_permissions{$file};
 9696:         my @new_locks;
 9697:         my @del_keys;
 9698:         if (ref($current_locks) eq "ARRAY"){
 9699:             foreach my $locker (@{$current_locks}) {
 9700:                 my $compare=$locker;
 9701:                 if (ref($locker) eq 'ARRAY') {
 9702:                     $compare=join('',@{$locker});
 9703:                     if ($compare ne $symb_crs) {
 9704:                         push(@new_locks, $locker);
 9705:                     }
 9706:                 }
 9707:             }
 9708:             if (scalar(@new_locks) > 0) {
 9709:                 $current_permissions{$file} = \@new_locks;
 9710:             } else {
 9711:                 push(@del_keys, $file);
 9712:                 &del('file_permissions',\@del_keys, $domain, $user);
 9713:                 delete($current_permissions{$file});
 9714:             }
 9715:         }
 9716:     }
 9717:     &put('file_permissions',\%current_permissions,$domain,$user);
 9718:     return;
 9719: }
 9720: 
 9721: # ------------------------------------------------------------ Directory lister
 9722: 
 9723: sub dirlist {
 9724:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9725:     $uri=~s/^\///;
 9726:     $uri=~s/\/$//;
 9727:     my ($udom, $uname);
 9728:     if ($getuserdir) {
 9729:         $udom = $userdomain;
 9730:         $uname = $username;
 9731:     } else {
 9732:         (undef,$udom,$uname)=split(/\//,$uri);
 9733:         if(defined($userdomain)) {
 9734:             $udom = $userdomain;
 9735:         }
 9736:         if(defined($username)) {
 9737:             $uname = $username;
 9738:         }
 9739:     }
 9740:     my ($dirRoot,$listing,@listing_results);
 9741: 
 9742:     $dirRoot = $perlvar{'lonDocRoot'};
 9743:     if (defined($getpropath)) {
 9744:         $dirRoot = &propath($udom,$uname);
 9745:         $dirRoot =~ s/\/$//;
 9746:     } elsif (defined($getuserdir)) {
 9747:         my $subdir=$uname.'__';
 9748:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9749:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9750:                    ."/$udom/$subdir/$uname";
 9751:     } elsif (defined($alternateRoot)) {
 9752:         $dirRoot = $alternateRoot;
 9753:     }
 9754: 
 9755:     if($udom) {
 9756:         if($uname) {
 9757:             my $uhome = &homeserver($uname,$udom);
 9758:             if ($uhome eq 'no_host') {
 9759:                 return ([],'no_host');
 9760:             }
 9761:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9762:                               .$getuserdir.':'.&escape($dirRoot)
 9763:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9764:             if ($listing eq 'unknown_cmd') {
 9765:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9766:             } else {
 9767:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9768:             }
 9769:             if ($listing eq 'unknown_cmd') {
 9770:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9771:                 @listing_results = split(/:/,$listing);
 9772:             } else {
 9773:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9774:             }
 9775:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9776:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9777:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9778:                 return ([],$listing);
 9779:             } else {
 9780:                 return (\@listing_results);
 9781:             }
 9782:         } elsif(!$alternateRoot) {
 9783:             my (%allusers,%listerror);
 9784: 	    my %servers = &get_servers($udom,'library');
 9785:  	    foreach my $tryserver (keys(%servers)) {
 9786:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9787:                                   &escape($udom),$tryserver);
 9788:                 if ($listing eq 'unknown_cmd') {
 9789: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9790: 				      $udom, $tryserver);
 9791:                 } else {
 9792:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9793:                 }
 9794: 		if ($listing eq 'unknown_cmd') {
 9795: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9796: 				      $udom, $tryserver);
 9797: 		    @listing_results = split(/:/,$listing);
 9798: 		} else {
 9799: 		    @listing_results =
 9800: 			map { &unescape($_); } split(/:/,$listing);
 9801: 		}
 9802:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9803:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9804:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9805:                     $listerror{$tryserver} = $listing;
 9806:                 } else {
 9807: 		    foreach my $line (@listing_results) {
 9808: 			my ($entry) = split(/&/,$line,2);
 9809: 			$allusers{$entry} = 1;
 9810: 		    }
 9811: 		}
 9812:             }
 9813:             my @alluserslist=();
 9814:             foreach my $user (sort(keys(%allusers))) {
 9815:                 push(@alluserslist,$user.'&user');
 9816:             }
 9817:             return (\@alluserslist);
 9818:         } else {
 9819:             return ([],'missing username');
 9820:         }
 9821:     } elsif(!defined($getpropath)) {
 9822:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9823:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9824:         return (\@all_domains);
 9825:     } else {
 9826:         return ([],'missing domain');
 9827:     }
 9828: }
 9829: 
 9830: # --------------------------------------------- GetFileTimestamp
 9831: # This function utilizes dirlist and returns the date stamp for
 9832: # when it was last modified.  It will also return an error of -1
 9833: # if an error occurs
 9834: 
 9835: sub GetFileTimestamp {
 9836:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9837:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9838:     $studentName   = &LONCAPA::clean_username($studentName);
 9839:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9840:                                     undef,$getuserdir);
 9841:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9842:         return -1;
 9843:     }
 9844:     if (ref($fileref) eq 'ARRAY') {
 9845:         my @stats = split('&',$fileref->[0]);
 9846:         # @stats contains first the filename, then the stat output
 9847:         return $stats[10]; # so this is 10 instead of 9.
 9848:     } else {
 9849:         return -1;
 9850:     }
 9851: }
 9852: 
 9853: sub stat_file {
 9854:     my ($uri) = @_;
 9855:     $uri = &clutter_with_no_wrapper($uri);
 9856: 
 9857:     my ($udom,$uname,$file);
 9858:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9859: 	($udom,$uname,$file) =
 9860: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9861: 	$file = 'userfiles/'.$file;
 9862:     }
 9863:     if ($uri =~ m-^/res/-) {
 9864: 	($udom,$uname) = 
 9865: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9866: 	$file = $uri;
 9867:     }
 9868: 
 9869:     if (!$udom || !$uname || !$file) {
 9870: 	# unable to handle the uri
 9871: 	return ();
 9872:     }
 9873:     my $getpropath;
 9874:     if ($file =~ /^userfiles\//) {
 9875:         $getpropath = 1;
 9876:     }
 9877:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9878:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9879:         return ();
 9880:     } else {
 9881:         if (ref($listref) eq 'ARRAY') {
 9882:             my @stats = split('&',$listref->[0]);
 9883: 	    shift(@stats); #filename is first
 9884: 	    return @stats;
 9885:         }
 9886:     }
 9887:     return ();
 9888: }
 9889: 
 9890: # -------------------------------------------------------- Value of a Condition
 9891: 
 9892: # gets the value of a specific preevaluated condition
 9893: #    stored in the string  $env{user.state.<cid>}
 9894: # or looks up a condition reference in the bighash and if if hasn't
 9895: # already been evaluated recurses into docondval to get the value of
 9896: # the condition, then memoizing it to 
 9897: #   $env{user.state.<cid>.<condition>}
 9898: sub directcondval {
 9899:     my $number=shift;
 9900:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9901: 	&Apache::lonuserstate::evalstate();
 9902:     }
 9903:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9904: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9905:     } elsif ($number =~ /^_/) {
 9906: 	my $sub_condition;
 9907: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9908: 		&GDBM_READER(),0640)) {
 9909: 	    $sub_condition=$bighash{'conditions'.$number};
 9910: 	    untie(%bighash);
 9911: 	}
 9912: 	my $value = &docondval($sub_condition);
 9913: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9914: 	return $value;
 9915:     }
 9916:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9917:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9918:     } else {
 9919:        return 2;
 9920:     }
 9921: }
 9922: 
 9923: # get the collection of conditions for this resource
 9924: sub condval {
 9925:     my $condidx=shift;
 9926:     my $allpathcond='';
 9927:     foreach my $cond (split(/\|/,$condidx)) {
 9928: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9929: 	    $allpathcond.=
 9930: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9931: 	}
 9932:     }
 9933:     $allpathcond=~s/\|$//;
 9934:     return &docondval($allpathcond);
 9935: }
 9936: 
 9937: #evaluates an expression of conditions
 9938: sub docondval {
 9939:     my ($allpathcond) = @_;
 9940:     my $result=0;
 9941:     if ($env{'request.course.id'}
 9942: 	&& defined($allpathcond)) {
 9943: 	my $operand='|';
 9944: 	my @stack;
 9945: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9946: 	    if ($chunk eq '(') {
 9947: 		push @stack,($operand,$result);
 9948: 	    } elsif ($chunk eq ')') {
 9949: 		my $before=pop @stack;
 9950: 		if (pop @stack eq '&') {
 9951: 		    $result=$result>$before?$before:$result;
 9952: 		} else {
 9953: 		    $result=$result>$before?$result:$before;
 9954: 		}
 9955: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9956: 		$operand=$chunk;
 9957: 	    } else {
 9958: 		my $new=directcondval($chunk);
 9959: 		if ($operand eq '&') {
 9960: 		    $result=$result>$new?$new:$result;
 9961: 		} else {
 9962: 		    $result=$result>$new?$result:$new;
 9963: 		}
 9964: 	    }
 9965: 	}
 9966:     }
 9967:     return $result;
 9968: }
 9969: 
 9970: # ---------------------------------------------------- Devalidate courseresdata
 9971: 
 9972: sub devalidatecourseresdata {
 9973:     my ($coursenum,$coursedomain)=@_;
 9974:     my $hashid=$coursenum.':'.$coursedomain;
 9975:     &devalidate_cache_new('courseres',$hashid);
 9976: }
 9977: 
 9978: 
 9979: # --------------------------------------------------- Course Resourcedata Query
 9980: #
 9981: #  Parameters:
 9982: #      $coursenum    - Number of the course.
 9983: #      $coursedomain - Domain at which the course was created.
 9984: #  Returns:
 9985: #     A hash of the course parameters along (I think) with timestamps
 9986: #     and version info.
 9987: 
 9988: sub get_courseresdata {
 9989:     my ($coursenum,$coursedomain)=@_;
 9990:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9991:     my $hashid=$coursenum.':'.$coursedomain;
 9992:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9993:     my %dumpreply;
 9994:     unless (defined($cached)) {
 9995: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9996: 	$result=\%dumpreply;
 9997: 	my ($tmp) = keys(%dumpreply);
 9998: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9999: 	    &do_cache_new('courseres',$hashid,$result,600);
10000: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10001: 	    return $tmp;
10002: 	} elsif ($tmp =~ /^(error)/) {
10003: 	    $result=undef;
10004: 	    &do_cache_new('courseres',$hashid,$result,600);
10005: 	}
10006:     }
10007:     return $result;
10008: }
10009: 
10010: sub devalidateuserresdata {
10011:     my ($uname,$udom)=@_;
10012:     my $hashid="$udom:$uname";
10013:     &devalidate_cache_new('userres',$hashid);
10014: }
10015: 
10016: sub get_userresdata {
10017:     my ($uname,$udom)=@_;
10018:     #most student don\'t have any data set, check if there is some data
10019:     if (&EXT_cache_status($udom,$uname)) { return undef; }
10020: 
10021:     my $hashid="$udom:$uname";
10022:     my ($result,$cached)=&is_cached_new('userres',$hashid);
10023:     if (!defined($cached)) {
10024: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
10025: 	$result=\%resourcedata;
10026: 	&do_cache_new('userres',$hashid,$result,600);
10027:     }
10028:     my ($tmp)=keys(%$result);
10029:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10030: 	return $result;
10031:     }
10032:     #error 2 occurs when the .db doesn't exist
10033:     if ($tmp!~/error: 2 /) {
10034: 	&logthis("<font color=\"blue\">WARNING:".
10035: 		 " Trying to get resource data for ".
10036: 		 $uname." at ".$udom.": ".
10037: 		 $tmp."</font>");
10038:     } elsif ($tmp=~/error: 2 /) {
10039: 	#&EXT_cache_set($udom,$uname);
10040: 	&do_cache_new('userres',$hashid,undef,600);
10041: 	undef($tmp); # not really an error so don't send it back
10042:     }
10043:     return $tmp;
10044: }
10045: #----------------------------------------------- resdata - return resource data
10046: #  Purpose:
10047: #    Return resource data for either users or for a course.
10048: #  Parameters:
10049: #     $name      - Course/user name.
10050: #     $domain    - Name of the domain the user/course is registered on.
10051: #     $type      - Type of thing $name is (must be 'course' or 'user'
10052: #     @which     - Array of names of resources desired.
10053: #  Returns:
10054: #     The value of the first reasource in @which that is found in the
10055: #     resource hash.
10056: #  Exceptional Conditions:
10057: #     If the $type passed in is not valid (not the string 'course' or 
10058: #     'user', an undefined  reference is returned.
10059: #     If none of the resources are found, an undef is returned
10060: sub resdata {
10061:     my ($name,$domain,$type,@which)=@_;
10062:     my $result;
10063:     if ($type eq 'course') {
10064: 	$result=&get_courseresdata($name,$domain);
10065:     } elsif ($type eq 'user') {
10066: 	$result=&get_userresdata($name,$domain);
10067:     }
10068:     if (!ref($result)) { return $result; }    
10069:     foreach my $item (@which) {
10070: 	if (defined($result->{$item->[0]})) {
10071: 	    return [$result->{$item->[0]},$item->[1]];
10072: 	}
10073:     }
10074:     return undef;
10075: }
10076: 
10077: sub get_numsuppfiles {
10078:     my ($cnum,$cdom,$ignorecache)=@_;
10079:     my $hashid=$cnum.':'.$cdom;
10080:     my ($suppcount,$cached);
10081:     unless ($ignorecache) {
10082:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10083:     }
10084:     unless (defined($cached)) {
10085:         my $chome=&homeserver($cnum,$cdom);
10086:         unless ($chome eq 'no_host') {
10087:             ($suppcount,my $errors) = (0,0);
10088:             my $suppmap = 'supplemental.sequence';
10089:             ($suppcount,$errors) = 
10090:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10091:         }
10092:         &do_cache_new('suppcount',$hashid,$suppcount,600);
10093:     }
10094:     return $suppcount;
10095: }
10096: 
10097: #
10098: # EXT resource caching routines
10099: #
10100: 
10101: sub clear_EXT_cache_status {
10102:     &delenv('cache.EXT.');
10103: }
10104: 
10105: sub EXT_cache_status {
10106:     my ($target_domain,$target_user) = @_;
10107:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10108:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10109:         # We know already the user has no data
10110:         return 1;
10111:     } else {
10112:         return 0;
10113:     }
10114: }
10115: 
10116: sub EXT_cache_set {
10117:     my ($target_domain,$target_user) = @_;
10118:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10119:     #&appenv({$cachename => time});
10120: }
10121: 
10122: # --------------------------------------------------------- Value of a Variable
10123: sub EXT {
10124: 
10125:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10126:     unless ($varname) { return ''; }
10127:     #get real user name/domain, courseid and symb
10128:     my $courseid;
10129:     my $publicuser;
10130:     if ($symbparm) {
10131: 	$symbparm=&get_symb_from_alias($symbparm);
10132:     }
10133:     if (!($uname && $udom)) {
10134:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10135:       if (!$symbparm) {	$symbparm=$cursymb; }
10136:     } else {
10137: 	$courseid=$env{'request.course.id'};
10138:     }
10139:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10140:     my $rest;
10141:     if (defined($therest[0])) {
10142:        $rest=join('.',@therest);
10143:     } else {
10144:        $rest='';
10145:     }
10146: 
10147:     my $qualifierrest=$qualifier;
10148:     if ($rest) { $qualifierrest.='.'.$rest; }
10149:     my $spacequalifierrest=$space;
10150:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10151:     if ($realm eq 'user') {
10152: # --------------------------------------------------------------- user.resource
10153: 	if ($space eq 'resource') {
10154: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10155: 		  || defined($Apache::lonhomework::parsing_a_task))
10156: 		 &&
10157: 		 ($symbparm eq &symbread()) ) {	
10158: 		# if we are in the middle of processing the resource the
10159: 		# get the value we are planning on committing
10160:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10161:                     return $Apache::lonhomework::results{$qualifierrest};
10162:                 } else {
10163:                     return $Apache::lonhomework::history{$qualifierrest};
10164:                 }
10165: 	    } else {
10166: 		my %restored;
10167: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10168: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10169: 		} else {
10170: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10171: 		}
10172: 		return $restored{$qualifierrest};
10173: 	    }
10174: # ----------------------------------------------------------------- user.access
10175:         } elsif ($space eq 'access') {
10176: 	    # FIXME - not supporting calls for a specific user
10177:             return &allowed($qualifier,$rest);
10178: # ------------------------------------------ user.preferences, user.environment
10179:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10180: 	    if (($uname eq $env{'user.name'}) &&
10181: 		($udom eq $env{'user.domain'})) {
10182: 		return $env{join('.',('environment',$qualifierrest))};
10183: 	    } else {
10184: 		my %returnhash;
10185: 		if (!$publicuser) {
10186: 		    %returnhash=&userenvironment($udom,$uname,
10187: 						 $qualifierrest);
10188: 		}
10189: 		return $returnhash{$qualifierrest};
10190: 	    }
10191: # ----------------------------------------------------------------- user.course
10192:         } elsif ($space eq 'course') {
10193: 	    # FIXME - not supporting calls for a specific user
10194:             return $env{join('.',('request.course',$qualifier))};
10195: # ------------------------------------------------------------------- user.role
10196:         } elsif ($space eq 'role') {
10197: 	    # FIXME - not supporting calls for a specific user
10198:             my ($role,$where)=split(/\./,$env{'request.role'});
10199:             if ($qualifier eq 'value') {
10200: 		return $role;
10201:             } elsif ($qualifier eq 'extent') {
10202:                 return $where;
10203:             }
10204: # ----------------------------------------------------------------- user.domain
10205:         } elsif ($space eq 'domain') {
10206:             return $udom;
10207: # ------------------------------------------------------------------- user.name
10208:         } elsif ($space eq 'name') {
10209:             return $uname;
10210: # ---------------------------------------------------- Any other user namespace
10211:         } else {
10212: 	    my %reply;
10213: 	    if (!$publicuser) {
10214: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10215: 	    }
10216: 	    return $reply{$qualifierrest};
10217:         }
10218:     } elsif ($realm eq 'query') {
10219: # ---------------------------------------------- pull stuff out of query string
10220:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10221: 						[$spacequalifierrest]);
10222: 	return $env{'form.'.$spacequalifierrest}; 
10223:    } elsif ($realm eq 'request') {
10224: # ------------------------------------------------------------- request.browser
10225:         if ($space eq 'browser') {
10226:             return $env{'browser.'.$qualifier};
10227: # ------------------------------------------------------------ request.filename
10228:         } else {
10229:             return $env{'request.'.$spacequalifierrest};
10230:         }
10231:     } elsif ($realm eq 'course') {
10232: # ---------------------------------------------------------- course.description
10233:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10234:     } elsif ($realm eq 'resource') {
10235: 
10236: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10237: 	    if (!$symbparm) { $symbparm=&symbread(); }
10238: 	}
10239: 
10240:         if ($qualifier eq '') {
10241: 	    if ($space eq 'title') {
10242: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10243: 	        return &gettitle($symbparm);
10244: 	    }
10245: 	
10246: 	    if ($space eq 'map') {
10247: 	        my ($map) = &decode_symb($symbparm);
10248: 	        return &symbread($map);
10249: 	    }
10250:             if ($space eq 'maptitle') {
10251:                 my ($map) = &decode_symb($symbparm);
10252:                 return &gettitle($map);
10253:             }
10254: 	    if ($space eq 'filename') {
10255: 	        if ($symbparm) {
10256: 		    return &clutter((&decode_symb($symbparm))[2]);
10257: 	        }
10258: 	        return &hreflocation('',$env{'request.filename'});
10259: 	    }
10260: 
10261:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10262:                 if ($space eq 'visibleparts') {
10263:                     my $navmap = Apache::lonnavmaps::navmap->new();
10264:                     my $item;
10265:                     if (ref($navmap)) {
10266:                         my $res = $navmap->getBySymb($symbparm);
10267:                         my $parts = $res->parts();
10268:                         if (ref($parts) eq 'ARRAY') {
10269:                             $item = join(',',@{$parts});
10270:                         }
10271:                         undef($navmap);
10272:                     }
10273:                     return $item;
10274:                 }
10275:             }
10276:         }
10277: 
10278: 	my ($section, $group, @groups);
10279: 	my ($courselevelm,$courselevel);
10280:         if (($courseid eq '') && ($cid)) {
10281:             $courseid = $cid;
10282:         }
10283: 	if (($symbparm && $courseid) && 
10284: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10285: 
10286: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10287: 
10288: # ----------------------------------------------------- Cascading lookup scheme
10289: 	    my $symbp=$symbparm;
10290: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10291: 
10292: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10293: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10294: 
10295: 	    if (($env{'user.name'} eq $uname) &&
10296: 		($env{'user.domain'} eq $udom)) {
10297: 		$section=$env{'request.course.sec'};
10298:                 @groups = split(/:/,$env{'request.course.groups'});  
10299:                 @groups=&sort_course_groups($courseid,@groups); 
10300: 	    } else {
10301: 		if (! defined($usection)) {
10302: 		    $section=&getsection($udom,$uname,$courseid);
10303: 		} else {
10304: 		    $section = $usection;
10305: 		}
10306:                 @groups = &get_users_groups($udom,$uname,$courseid);
10307: 	    }
10308: 
10309: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10310: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10311: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10312: 
10313: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10314: 	    my $courselevelr=$courseid.'.'.$symbparm;
10315: 	    $courselevelm=$courseid.'.'.$mapparm;
10316: 
10317: # ----------------------------------------------------------- first, check user
10318: 
10319: 	    my $userreply=&resdata($uname,$udom,'user',
10320: 				       ([$courselevelr,'resource'],
10321: 					[$courselevelm,'map'     ],
10322: 					[$courselevel, 'course'  ]));
10323: 	    if (defined($userreply)) { return &get_reply($userreply); }
10324: 
10325: # ------------------------------------------------ second, check some of course
10326:             my $coursereply;
10327:             if (@groups > 0) {
10328:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10329:                                        $mapparm,$spacequalifierrest);
10330:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10331:             }
10332: 
10333: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10334: 				  $env{'course.'.$courseid.'.domain'},
10335: 				  'course',
10336: 				  ([$seclevelr,   'resource'],
10337: 				   [$seclevelm,   'map'     ],
10338: 				   [$seclevel,    'course'  ],
10339: 				   [$courselevelr,'resource']));
10340: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10341: 
10342: # ------------------------------------------------------ third, check map parms
10343: 	    my %parmhash=();
10344: 	    my $thisparm='';
10345: 	    if (tie(%parmhash,'GDBM_File',
10346: 		    $env{'request.course.fn'}.'_parms.db',
10347: 		    &GDBM_READER(),0640)) {
10348: 		$thisparm=$parmhash{$symbparm};
10349: 		untie(%parmhash);
10350: 	    }
10351: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10352: 	}
10353: # ------------------------------------------ fourth, look in resource metadata
10354: 
10355: 	$spacequalifierrest=~s/\./\_/;
10356: 	my $filename;
10357: 	if (!$symbparm) { $symbparm=&symbread(); }
10358: 	if ($symbparm) {
10359: 	    $filename=(&decode_symb($symbparm))[2];
10360: 	} else {
10361: 	    $filename=$env{'request.filename'};
10362: 	}
10363: 	my $metadata=&metadata($filename,$spacequalifierrest);
10364: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10365: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10366: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10367: 
10368: # ---------------------------------------------- fourth, look in rest of course
10369: 	if ($symbparm && defined($courseid) && 
10370: 	    $courseid eq $env{'request.course.id'}) {
10371: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10372: 				     $env{'course.'.$courseid.'.domain'},
10373: 				     'course',
10374: 				     ([$courselevelm,'map'   ],
10375: 				      [$courselevel, 'course']));
10376: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10377: 	}
10378: # ------------------------------------------------------------------ Cascade up
10379: 	unless ($space eq '0') {
10380: 	    my @parts=split(/_/,$space);
10381: 	    my $id=pop(@parts);
10382: 	    my $part=join('_',@parts);
10383: 	    if ($part eq '') { $part='0'; }
10384: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10385: 				 $symbparm,$udom,$uname,$section,1);
10386: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10387: 	}
10388: 	if ($recurse) { return undef; }
10389: 	my $pack_def=&packages_tab_default($filename,$varname);
10390: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10391: # ---------------------------------------------------- Any other user namespace
10392:     } elsif ($realm eq 'environment') {
10393: # ----------------------------------------------------------------- environment
10394: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10395: 	    return $env{'environment.'.$spacequalifierrest};
10396: 	} else {
10397: 	    if ($uname eq 'anonymous' && $udom eq '') {
10398: 		return '';
10399: 	    }
10400: 	    my %returnhash=&userenvironment($udom,$uname,
10401: 					    $spacequalifierrest);
10402: 	    return $returnhash{$spacequalifierrest};
10403: 	}
10404:     } elsif ($realm eq 'system') {
10405: # ----------------------------------------------------------------- system.time
10406: 	if ($space eq 'time') {
10407: 	    return time;
10408:         }
10409:     } elsif ($realm eq 'server') {
10410: # ----------------------------------------------------------------- system.time
10411: 	if ($space eq 'name') {
10412: 	    return $ENV{'SERVER_NAME'};
10413:         }
10414:     }
10415:     return '';
10416: }
10417: 
10418: sub get_reply {
10419:     my ($reply_value) = @_;
10420:     if (ref($reply_value) eq 'ARRAY') {
10421:         if (wantarray) {
10422: 	    return @$reply_value;
10423:         }
10424:         return $reply_value->[0];
10425:     } else {
10426:         return $reply_value;
10427:     }
10428: }
10429: 
10430: sub check_group_parms {
10431:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10432:     my @groupitems = ();
10433:     my $resultitem;
10434:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10435:     foreach my $group (@{$groups}) {
10436:         foreach my $level (@levels) {
10437:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10438:              push(@groupitems,[$item,$level->[1]]);
10439:         }
10440:     }
10441:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10442:                             $env{'course.'.$courseid.'.domain'},
10443:                                      'course',@groupitems);
10444:     return $coursereply;
10445: }
10446: 
10447: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10448:     my ($courseid,@groups) = @_;
10449:     @groups = sort(@groups);
10450:     return @groups;
10451: }
10452: 
10453: sub packages_tab_default {
10454:     my ($uri,$varname)=@_;
10455:     my (undef,$part,$name)=split(/\./,$varname);
10456: 
10457:     my (@extension,@specifics,$do_default);
10458:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10459: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10460: 	if ($pack_type eq 'default') {
10461: 	    $do_default=1;
10462: 	} elsif ($pack_type eq 'extension') {
10463: 	    push(@extension,[$package,$pack_type,$pack_part]);
10464: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10465: 	    # only look at packages defaults for packages that this id is
10466: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10467: 	}
10468:     }
10469:     # first look for a package that matches the requested part id
10470:     foreach my $package (@specifics) {
10471: 	my (undef,$pack_type,$pack_part)=@{$package};
10472: 	next if ($pack_part ne $part);
10473: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10474: 	    return $packagetab{"$pack_type&$name&default"};
10475: 	}
10476:     }
10477:     # look for any possible matching non extension_ package
10478:     foreach my $package (@specifics) {
10479: 	my (undef,$pack_type,$pack_part)=@{$package};
10480: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10481: 	    return $packagetab{"$pack_type&$name&default"};
10482: 	}
10483: 	if ($pack_type eq 'part') { $pack_part='0'; }
10484: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10485: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10486: 	}
10487:     }
10488:     # look for any posible extension_ match
10489:     foreach my $package (@extension) {
10490: 	my ($package,$pack_type)=@{$package};
10491: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10492: 	    return $packagetab{"$pack_type&$name&default"};
10493: 	}
10494: 	if (defined($packagetab{$package."&$name&default"})) {
10495: 	    return $packagetab{$package."&$name&default"};
10496: 	}
10497:     }
10498:     # look for a global default setting
10499:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10500: 	return $packagetab{"default&$name&default"};
10501:     }
10502:     return undef;
10503: }
10504: 
10505: sub add_prefix_and_part {
10506:     my ($prefix,$part)=@_;
10507:     my $keyroot;
10508:     if (defined($prefix) && $prefix !~ /^__/) {
10509: 	# prefix that has a part already
10510: 	$keyroot=$prefix;
10511:     } elsif (defined($prefix)) {
10512: 	# prefix that is missing a part
10513: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10514:     } else {
10515: 	# no prefix at all
10516: 	if (defined($part)) { $keyroot='_'.$part; }
10517:     }
10518:     return $keyroot;
10519: }
10520: 
10521: # ---------------------------------------------------------------- Get metadata
10522: 
10523: my %metaentry;
10524: my %importedpartids;
10525: sub metadata {
10526:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10527:     $uri=&declutter($uri);
10528:     # if it is a non metadata possible uri return quickly
10529:     if (($uri eq '') || 
10530: 	(($uri =~ m|^/*adm/|) && 
10531: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10532:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10533: 	return undef;
10534:     }
10535:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10536: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10537: 	return undef;
10538:     }
10539:     my $filename=$uri;
10540:     $uri=~s/\.meta$//;
10541: #
10542: # Is the metadata already cached?
10543: # Look at timestamp of caching
10544: # Everything is cached by the main uri, libraries are never directly cached
10545: #
10546:     if (!defined($liburi)) {
10547: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10548: 	if (defined($cached)) { return $result->{':'.$what}; }
10549:     }
10550:     {
10551: # Imported parts would go here
10552:         my %importedids=();
10553:         my @origfileimportpartids=();
10554:         my $importedparts=0;
10555: #
10556: # Is this a recursive call for a library?
10557: #
10558: #	if (! exists($metacache{$uri})) {
10559: #	    $metacache{$uri}={};
10560: #	}
10561: 	my $cachetime = 60*60;
10562:         if ($liburi) {
10563: 	    $liburi=&declutter($liburi);
10564:             $filename=$liburi;
10565:         } else {
10566: 	    &devalidate_cache_new('meta',$uri);
10567: 	    undef(%metaentry);
10568: 	}
10569:         my %metathesekeys=();
10570:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10571: 	my $metastring;
10572: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10573: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10574: 	    $metastring = 
10575: 		&Apache::lonnet::ssi_body($which,
10576: 					  ('grade_target' => 'meta'));
10577: 	    $cachetime = 1; # only want this cached in the child not long term
10578: 	} elsif (($uri !~ m -^(editupload)/-) && 
10579:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10580: 	    my $file=&filelocation('',&clutter($filename));
10581: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10582: 	    $metastring=&getfile($file);
10583: 	}
10584:         my $parser=HTML::LCParser->new(\$metastring);
10585:         my $token;
10586:         undef %metathesekeys;
10587:         while ($token=$parser->get_token) {
10588: 	    if ($token->[0] eq 'S') {
10589: 		if (defined($token->[2]->{'package'})) {
10590: #
10591: # This is a package - get package info
10592: #
10593: 		    my $package=$token->[2]->{'package'};
10594: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10595: 		    if (defined($token->[2]->{'id'})) { 
10596: 			$keyroot.='_'.$token->[2]->{'id'}; 
10597: 		    }
10598: 		    if ($metaentry{':packages'}) {
10599: 			$metaentry{':packages'}.=','.$package.$keyroot;
10600: 		    } else {
10601: 			$metaentry{':packages'}=$package.$keyroot;
10602: 		    }
10603: 		    foreach my $pack_entry (keys(%packagetab)) {
10604: 			my $part=$keyroot;
10605: 			$part=~s/^\_//;
10606: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10607: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10608: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10609: 			    # ignore package.tab specified default values
10610:                             # here &package_tab_default() will fetch those
10611: 			    if ($subp eq 'default') { next; }
10612: 			    my $value=$packagetab{$pack_entry};
10613: 			    my $unikey;
10614: 			    if ($pack =~ /_0$/) {
10615: 				$unikey='parameter_0_'.$name;
10616: 				$part=0;
10617: 			    } else {
10618: 				$unikey='parameter'.$keyroot.'_'.$name;
10619: 			    }
10620: 			    if ($subp eq 'display') {
10621: 				$value.=' [Part: '.$part.']';
10622: 			    }
10623: 			    $metaentry{':'.$unikey.'.part'}=$part;
10624: 			    $metathesekeys{$unikey}=1;
10625: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10626: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10627: 			    }
10628: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10629: 				$metaentry{':'.$unikey}=
10630: 				    $metaentry{':'.$unikey.'.default'};
10631: 			    }
10632: 			}
10633: 		    }
10634: 		} else {
10635: #
10636: # This is not a package - some other kind of start tag
10637: #
10638: 		    my $entry=$token->[1];
10639: 		    my $unikey='';
10640: 
10641: 		    if ($entry eq 'import') {
10642: #
10643: # Importing a library here
10644: #
10645:                         my $location=$parser->get_text('/import');
10646:                         my $dir=$filename;
10647:                         $dir=~s|[^/]*$||;
10648:                         $location=&filelocation($dir,$location);
10649:                        
10650:                         my $importmode=$token->[2]->{'importmode'};
10651:                         if ($importmode eq 'problem') {
10652: # Import as problem/response
10653:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10654:                         } elsif ($importmode eq 'part') {
10655: # Import as part(s)
10656:                            $importedparts=1;
10657: # We need to get the original file and the imported file to get the part order correct
10658: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10659: # Load and inspect original file
10660:                            if ($#origfileimportpartids<0) {
10661:                               undef(%importedpartids);
10662:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10663:                               my $origfile=&getfile($origfilelocation);
10664:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10665:                            }
10666: 
10667: # Load and inspect imported file
10668:                            my $impfile=&getfile($location);
10669:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10670:                            if ($#impfilepartids>=0) {
10671: # This problem had parts
10672:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10673:                            } else {
10674: # Importing by turning a single problem into a problem part
10675: # It gets the import-tags ID as part-ID
10676:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10677:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10678:                            }
10679:                         } else {
10680: # Normal import
10681:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10682:                            if (defined($token->[2]->{'id'})) {
10683:                               $unikey.='_'.$token->[2]->{'id'};
10684:                            }
10685:                         }
10686: 
10687: 			if ($depthcount<20) {
10688: 			    my $metadata = 
10689: 				&metadata($uri,'keys', $location,$unikey,
10690: 					  $depthcount+1);
10691: 			    foreach my $meta (split(',',$metadata)) {
10692: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10693: 				$metathesekeys{$meta}=1;
10694: 			    }
10695: 			
10696:                         }
10697: 		    } else {
10698: #
10699: # Not importing, some other kind of non-package, non-library start tag
10700: # 
10701:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10702:                         if (defined($token->[2]->{'id'})) {
10703:                             $unikey.='_'.$token->[2]->{'id'};
10704:                         }
10705: 			if (defined($token->[2]->{'name'})) { 
10706: 			    $unikey.='_'.$token->[2]->{'name'}; 
10707: 			}
10708: 			$metathesekeys{$unikey}=1;
10709: 			foreach my $param (@{$token->[3]}) {
10710: 			    $metaentry{':'.$unikey.'.'.$param} =
10711: 				$token->[2]->{$param};
10712: 			}
10713: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10714: 			my $default=$metaentry{':'.$unikey.'.default'};
10715: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10716: 		 # only ws inside the tag, and not in default, so use default
10717: 		 # as value
10718: 			    $metaentry{':'.$unikey}=$default;
10719: 			} elsif ( $internaltext =~ /\S/ ) {
10720: 		  # something interesting inside the tag
10721: 			    $metaentry{':'.$unikey}=$internaltext;
10722: 			} else {
10723: 		  # no interesting values, don't set a default
10724: 			}
10725: # end of not-a-package not-a-library import
10726: 		    }
10727: # end of not-a-package start tag
10728: 		}
10729: # the next is the end of "start tag"
10730: 	    }
10731: 	}
10732: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10733: 	$extension = lc($extension);
10734: 	if ($extension eq 'htm') { $extension='html'; }
10735: 
10736: 	foreach my $key (keys(%packagetab)) {
10737: 	    #no specific packages #how's our extension
10738: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10739: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10740: 					 \%metathesekeys);
10741: 	}
10742: 
10743: 	if (!exists($metaentry{':packages'})
10744: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10745: 	    foreach my $key (keys(%packagetab)) {
10746: 		#no specific packages well let's get default then
10747: 		if ($key!~/^default&/) { next; }
10748: 		&metadata_create_package_def($uri,$key,'default',
10749: 					     \%metathesekeys);
10750: 	    }
10751: 	}
10752: # are there custom rights to evaluate
10753: 	if ($metaentry{':copyright'} eq 'custom') {
10754: 
10755:     #
10756:     # Importing a rights file here
10757:     #
10758: 	    unless ($depthcount) {
10759: 		my $location=$metaentry{':customdistributionfile'};
10760: 		my $dir=$filename;
10761: 		$dir=~s|[^/]*$||;
10762: 		$location=&filelocation($dir,$location);
10763: 		my $rights_metadata =
10764: 		    &metadata($uri,'keys',$location,'_rights',
10765: 			      $depthcount+1);
10766: 		foreach my $rights (split(',',$rights_metadata)) {
10767: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10768: 		    $metathesekeys{$rights}=1;
10769: 		}
10770: 	    }
10771: 	}
10772: 	# uniqifiy package listing
10773: 	my %seen;
10774: 	my @uniq_packages =
10775: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10776: 	$metaentry{':packages'} = join(',',@uniq_packages);
10777: 
10778:         if ($importedparts) {
10779: # We had imported parts and need to rebuild partorder
10780:            $metaentry{':partorder'}='';
10781:            $metathesekeys{'partorder'}=1;
10782:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10783:                if ($origfileimportpartids[$index] eq 'part') {
10784: # original part, part of the problem
10785:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10786:                } else {
10787: # we have imported parts at this position
10788:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10789:                }
10790:            }
10791:            $metaentry{':partorder'}=~s/^\,//;
10792:         }
10793: 
10794: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10795: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10796: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10797: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10798: # this is the end of "was not already recently cached
10799:     }
10800:     return $metaentry{':'.$what};
10801: }
10802: 
10803: sub metadata_create_package_def {
10804:     my ($uri,$key,$package,$metathesekeys)=@_;
10805:     my ($pack,$name,$subp)=split(/\&/,$key);
10806:     if ($subp eq 'default') { next; }
10807:     
10808:     if (defined($metaentry{':packages'})) {
10809: 	$metaentry{':packages'}.=','.$package;
10810:     } else {
10811: 	$metaentry{':packages'}=$package;
10812:     }
10813:     my $value=$packagetab{$key};
10814:     my $unikey;
10815:     $unikey='parameter_0_'.$name;
10816:     $metaentry{':'.$unikey.'.part'}=0;
10817:     $$metathesekeys{$unikey}=1;
10818:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10819: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10820:     }
10821:     if (defined($metaentry{':'.$unikey.'.default'})) {
10822: 	$metaentry{':'.$unikey}=
10823: 	    $metaentry{':'.$unikey.'.default'};
10824:     }
10825: }
10826: 
10827: sub metadata_generate_part0 {
10828:     my ($metadata,$metacache,$uri) = @_;
10829:     my %allnames;
10830:     foreach my $metakey (keys(%$metadata)) {
10831: 	if ($metakey=~/^parameter\_(.*)/) {
10832: 	  my $part=$$metacache{':'.$metakey.'.part'};
10833: 	  my $name=$$metacache{':'.$metakey.'.name'};
10834: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10835: 	    $allnames{$name}=$part;
10836: 	  }
10837: 	}
10838:     }
10839:     foreach my $name (keys(%allnames)) {
10840:       $$metadata{"parameter_0_$name"}=1;
10841:       my $key=":parameter_0_$name";
10842:       $$metacache{"$key.part"}='0';
10843:       $$metacache{"$key.name"}=$name;
10844:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10845: 					   $allnames{$name}.'_'.$name.
10846: 					   '.type'};
10847:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10848: 			     '.display'};
10849:       my $expr='[Part: '.$allnames{$name}.']';
10850:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10851:       $$metacache{"$key.display"}=$olddis;
10852:     }
10853: }
10854: 
10855: # ------------------------------------------------------ Devalidate title cache
10856: 
10857: sub devalidate_title_cache {
10858:     my ($url)=@_;
10859:     if (!$env{'request.course.id'}) { return; }
10860:     my $symb=&symbread($url);
10861:     if (!$symb) { return; }
10862:     my $key=$env{'request.course.id'}."\0".$symb;
10863:     &devalidate_cache_new('title',$key);
10864: }
10865: 
10866: # ------------------------------------------------- Get the title of a course
10867: 
10868: sub current_course_title {
10869:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10870: }
10871: # ------------------------------------------------- Get the title of a resource
10872: 
10873: sub gettitle {
10874:     my $urlsymb=shift;
10875:     my $symb=&symbread($urlsymb);
10876:     if ($symb) {
10877: 	my $key=$env{'request.course.id'}."\0".$symb;
10878: 	my ($result,$cached)=&is_cached_new('title',$key);
10879: 	if (defined($cached)) { 
10880: 	    return $result;
10881: 	}
10882: 	my ($map,$resid,$url)=&decode_symb($symb);
10883: 	my $title='';
10884: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10885: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10886: 	} else {
10887: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10888: 		    &GDBM_READER(),0640)) {
10889: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10890: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10891: 		untie(%bighash);
10892: 	    }
10893: 	}
10894: 	$title=~s/\&colon\;/\:/gs;
10895: 	if ($title) {
10896: # Remember both $symb and $title for dynamic metadata
10897:             $accesshash{$symb.'___crstitle'}=$title;
10898:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10899: # Cache this title and then return it
10900: 	    return &do_cache_new('title',$key,$title,600);
10901: 	}
10902: 	$urlsymb=$url;
10903:     }
10904:     my $title=&metadata($urlsymb,'title');
10905:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10906:     return $title;
10907: }
10908: 
10909: sub get_slot {
10910:     my ($which,$cnum,$cdom)=@_;
10911:     if (!$cnum || !$cdom) {
10912: 	(undef,my $courseid)=&whichuser();
10913: 	$cdom=$env{'course.'.$courseid.'.domain'};
10914: 	$cnum=$env{'course.'.$courseid.'.num'};
10915:     }
10916:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10917:     my %slotinfo;
10918:     if (exists($remembered{$key})) {
10919: 	$slotinfo{$which} = $remembered{$key};
10920:     } else {
10921: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10922: 	&Apache::lonhomework::showhash(%slotinfo);
10923: 	my ($tmp)=keys(%slotinfo);
10924: 	if ($tmp=~/^error:/) { return (); }
10925: 	$remembered{$key} = $slotinfo{$which};
10926:     }
10927:     if (ref($slotinfo{$which}) eq 'HASH') {
10928: 	return %{$slotinfo{$which}};
10929:     }
10930:     return $slotinfo{$which};
10931: }
10932: 
10933: sub get_reservable_slots {
10934:     my ($cnum,$cdom,$uname,$udom) = @_;
10935:     my $now = time;
10936:     my $reservable_info;
10937:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10938:     if (exists($remembered{$key})) {
10939:         $reservable_info = $remembered{$key};
10940:     } else {
10941:         my %resv;
10942:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10943:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10944:         $reservable_info = \%resv;
10945:         $remembered{$key} = $reservable_info;
10946:     }
10947:     return $reservable_info;
10948: }
10949: 
10950: sub get_course_slots {
10951:     my ($cnum,$cdom) = @_;
10952:     my $hashid=$cnum.':'.$cdom;
10953:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10954:     if (defined($cached)) {
10955:         if (ref($result) eq 'HASH') {
10956:             return %{$result};
10957:         }
10958:     } else {
10959:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10960:         my ($tmp) = keys(%slots);
10961:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10962:             &do_cache_new('allslots',$hashid,\%slots,600);
10963:             return %slots;
10964:         }
10965:     }
10966:     return;
10967: }
10968: 
10969: sub devalidate_slots_cache {
10970:     my ($cnum,$cdom)=@_;
10971:     my $hashid=$cnum.':'.$cdom;
10972:     &devalidate_cache_new('allslots',$hashid);
10973: }
10974: 
10975: sub get_coursechange {
10976:     my ($cdom,$cnum) = @_;
10977:     if ($cdom eq '' || $cnum eq '') {
10978:         return unless ($env{'request.course.id'});
10979:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10980:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10981:     }
10982:     my $hashid=$cdom.'_'.$cnum;
10983:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10984:     if ((defined($cached)) && ($change ne '')) {
10985:         return $change;
10986:     } else {
10987:         my %crshash;
10988:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10989:         if ($crshash{'internal.contentchange'} eq '') {
10990:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10991:             if ($change eq '') {
10992:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10993:                 $change = $crshash{'internal.created'};
10994:             }
10995:         } else {
10996:             $change = $crshash{'internal.contentchange'};
10997:         }
10998:         my $cachetime = 600;
10999:         &do_cache_new('crschange',$hashid,$change,$cachetime);
11000:     }
11001:     return $change;
11002: }
11003: 
11004: sub devalidate_coursechange_cache {
11005:     my ($cnum,$cdom)=@_;
11006:     my $hashid=$cnum.':'.$cdom;
11007:     &devalidate_cache_new('crschange',$hashid);
11008: }
11009: 
11010: # ------------------------------------------------- Update symbolic store links
11011: 
11012: sub symblist {
11013:     my ($mapname,%newhash)=@_;
11014:     $mapname=&deversion(&declutter($mapname));
11015:     my %hash;
11016:     if (($env{'request.course.fn'}) && (%newhash)) {
11017:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11018:                       &GDBM_WRCREAT(),0640)) {
11019: 	    foreach my $url (keys(%newhash)) {
11020: 		next if ($url eq 'last_known'
11021: 			 && $env{'form.no_update_last_known'});
11022: 		$hash{declutter($url)}=&encode_symb($mapname,
11023: 						    $newhash{$url}->[1],
11024: 						    $newhash{$url}->[0]);
11025:             }
11026:             if (untie(%hash)) {
11027: 		return 'ok';
11028:             }
11029:         }
11030:     }
11031:     return 'error';
11032: }
11033: 
11034: # --------------------------------------------------------------- Verify a symb
11035: 
11036: sub symbverify {
11037:     my ($symb,$thisurl,$encstate)=@_;
11038:     my $thisfn=$thisurl;
11039:     $thisfn=&declutter($thisfn);
11040: # direct jump to resource in page or to a sequence - will construct own symbs
11041:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11042: # check URL part
11043:     my ($map,$resid,$url)=&decode_symb($symb);
11044: 
11045:     unless ($url eq $thisfn) { return 0; }
11046: 
11047:     $symb=&symbclean($symb);
11048:     $thisurl=&deversion($thisurl);
11049:     $thisfn=&deversion($thisfn);
11050: 
11051:     my %bighash;
11052:     my $okay=0;
11053: 
11054:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11055:                             &GDBM_READER(),0640)) {
11056:         my $noclutter;
11057:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11058:             $thisurl =~ s/\?.+$//;
11059:             if ($map =~ m{^uploaded/.+\.page$}) {
11060:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11061:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
11062:                 $noclutter = 1;
11063:             }
11064:         }
11065:         my $ids;
11066:         if ($noclutter) {
11067:             $ids=$bighash{'ids_'.$thisurl};
11068:         } else {
11069:             $ids=$bighash{'ids_'.&clutter($thisurl)};
11070:         }
11071:         unless ($ids) {
11072:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
11073:             $ids=$bighash{$idkey};
11074:         }
11075:         if ($ids) {
11076: # ------------------------------------------------------------------- Has ID(s)
11077:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11078:                 $symb =~ s/\?.+$//;
11079:             }
11080: 	    foreach my $id (split(/\,/,$ids)) {
11081: 	       my ($mapid,$resid)=split(/\./,$id);
11082:                if (
11083:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11084:    eq $symb) {
11085:                    if (ref($encstate)) {
11086:                        $$encstate = $bighash{'encrypted_'.$id};
11087:                    }
11088: 		   if (($env{'request.role.adv'}) ||
11089: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11090:                        ($thisurl eq '/adm/navmaps')) {
11091: 		       $okay=1;
11092:                        last;
11093: 		   }
11094: 	       }
11095: 	   }
11096:         }
11097: 	untie(%bighash);
11098:     }
11099:     return $okay;
11100: }
11101: 
11102: # --------------------------------------------------------------- Clean-up symb
11103: 
11104: sub symbclean {
11105:     my $symb=shift;
11106:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11107: # remove version from map
11108:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11109: 
11110: # remove version from URL
11111:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11112: 
11113: # remove wrapper
11114: 
11115:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11116:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11117:     return $symb;
11118: }
11119: 
11120: # ---------------------------------------------- Split symb to find map and url
11121: 
11122: sub encode_symb {
11123:     my ($map,$resid,$url)=@_;
11124:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11125: }
11126: 
11127: sub decode_symb {
11128:     my $symb=shift;
11129:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11130:     my ($map,$resid,$url)=split(/___/,$symb);
11131:     return (&fixversion($map),$resid,&fixversion($url));
11132: }
11133: 
11134: sub fixversion {
11135:     my $fn=shift;
11136:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11137:     my %bighash;
11138:     my $uri=&clutter($fn);
11139:     my $key=$env{'request.course.id'}.'_'.$uri;
11140: # is this cached?
11141:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11142:     if (defined($cached)) { return $result; }
11143: # unfortunately not cached, or expired
11144:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11145: 	    &GDBM_READER(),0640)) {
11146:  	if ($bighash{'version_'.$uri}) {
11147:  	    my $version=$bighash{'version_'.$uri};
11148:  	    unless (($version eq 'mostrecent') || 
11149: 		    ($version==&getversion($uri))) {
11150:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11151:  	    }
11152:  	}
11153:  	untie %bighash;
11154:     }
11155:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11156: }
11157: 
11158: sub deversion {
11159:     my $url=shift;
11160:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11161:     return $url;
11162: }
11163: 
11164: # ------------------------------------------------------ Return symb list entry
11165: 
11166: sub symbread {
11167:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
11168:     my $cache_str='request.symbread.cached.'.$thisfn;
11169:     if (defined($env{$cache_str})) {
11170:         if ($ignorecachednull) {
11171:             return $env{$cache_str} unless ($env{$cache_str} eq '');
11172:         } else {
11173:             return $env{$cache_str};
11174:         }
11175:     }
11176: # no filename provided? try from environment
11177:     unless ($thisfn) {
11178:         if ($env{'request.symb'}) {
11179: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
11180: 	}
11181: 	$thisfn=$env{'request.filename'};
11182:     }
11183:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11184: # is that filename actually a symb? Verify, clean, and return
11185:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11186: 	if (&symbverify($thisfn,$1)) {
11187: 	    return $env{$cache_str}=&symbclean($thisfn);
11188: 	}
11189:     }
11190:     $thisfn=declutter($thisfn);
11191:     my %hash;
11192:     my %bighash;
11193:     my $syval='';
11194:     if (($env{'request.course.fn'}) && ($thisfn)) {
11195:         my $targetfn = $thisfn;
11196:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11197:             $targetfn = 'adm/wrapper/'.$thisfn;
11198:         }
11199: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11200: 	    $targetfn=$1;
11201: 	}
11202:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11203:                       &GDBM_READER(),0640)) {
11204: 	    $syval=$hash{$targetfn};
11205:             untie(%hash);
11206:         }
11207: # ---------------------------------------------------------- There was an entry
11208:         if ($syval) {
11209: 	    #unless ($syval=~/\_\d+$/) {
11210: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11211: 		    #&appenv({'request.ambiguous' => $thisfn});
11212: 		    #return $env{$cache_str}='';
11213: 		#}    
11214: 		#$syval.=$1;
11215: 	    #}
11216:         } else {
11217: # ------------------------------------------------------- Was not in symb table
11218:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11219:                             &GDBM_READER(),0640)) {
11220: # ---------------------------------------------- Get ID(s) for current resource
11221:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11222:               unless ($ids) { 
11223:                  $ids=$bighash{'ids_/'.$thisfn};
11224:               }
11225:               unless ($ids) {
11226: # alias?
11227: 		  $ids=$bighash{'mapalias_'.$thisfn};
11228:               }
11229:               if ($ids) {
11230: # ------------------------------------------------------------------- Has ID(s)
11231:                  my @possibilities=split(/\,/,$ids);
11232:                  if ($#possibilities==0) {
11233: # ----------------------------------------------- There is only one possibility
11234: 		     my ($mapid,$resid)=split(/\./,$ids);
11235: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11236: 						    $resid,$thisfn);
11237:                      if (ref($possibles) eq 'HASH') {
11238:                          $possibles->{$syval} = 1;    
11239:                      }
11240:                      if ($checkforblock) {
11241:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11242:                          if (@blockers) {
11243:                              $syval = '';
11244:                              return;
11245:                          }
11246:                      }
11247:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
11248: # ------------------------------------------ There is more than one possibility
11249:                      my $realpossible=0;
11250:                      foreach my $id (@possibilities) {
11251: 			 my $file=$bighash{'src_'.$id};
11252:                          my $canaccess;
11253:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11254:                              $canaccess = 1;
11255:                          } else { 
11256:                              $canaccess = &allowed('bre',$file);
11257:                          }
11258:                          if ($canaccess) {
11259:          		     my ($mapid,$resid)=split(/\./,$id);
11260:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
11261:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11262: 						             $resid,$thisfn);
11263:                                  if (ref($possibles) eq 'HASH') {
11264:                                      $possibles->{$syval} = 1;
11265:                                  }
11266:                                  if ($checkforblock) {
11267:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11268:                                      unless (@blockers > 0) {
11269:                                          $syval = $poss_syval;
11270:                                          $realpossible++;
11271:                                      }
11272:                                  } else {
11273:                                      $syval = $poss_syval;
11274:                                      $realpossible++;
11275:                                  }
11276:                              }
11277: 			 }
11278:                      }
11279: 		     if ($realpossible!=1) { $syval=''; }
11280:                  } else {
11281:                      $syval='';
11282:                  }
11283: 	      }
11284:               untie(%bighash);
11285:            }
11286:         }
11287:         if ($syval) {
11288: 	    return $env{$cache_str}=$syval;
11289:         }
11290:     }
11291:     &appenv({'request.ambiguous' => $thisfn});
11292:     return $env{$cache_str}='';
11293: }
11294: 
11295: # ---------------------------------------------------------- Return random seed
11296: 
11297: sub numval {
11298:     my $txt=shift;
11299:     $txt=~tr/A-J/0-9/;
11300:     $txt=~tr/a-j/0-9/;
11301:     $txt=~tr/K-T/0-9/;
11302:     $txt=~tr/k-t/0-9/;
11303:     $txt=~tr/U-Z/0-5/;
11304:     $txt=~tr/u-z/0-5/;
11305:     $txt=~s/\D//g;
11306:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11307:     return int($txt);
11308: }
11309: 
11310: sub numval2 {
11311:     my $txt=shift;
11312:     $txt=~tr/A-J/0-9/;
11313:     $txt=~tr/a-j/0-9/;
11314:     $txt=~tr/K-T/0-9/;
11315:     $txt=~tr/k-t/0-9/;
11316:     $txt=~tr/U-Z/0-5/;
11317:     $txt=~tr/u-z/0-5/;
11318:     $txt=~s/\D//g;
11319:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11320:     my $total;
11321:     foreach my $val (@txts) { $total+=$val; }
11322:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11323:     return int($total);
11324: }
11325: 
11326: sub numval3 {
11327:     use integer;
11328:     my $txt=shift;
11329:     $txt=~tr/A-J/0-9/;
11330:     $txt=~tr/a-j/0-9/;
11331:     $txt=~tr/K-T/0-9/;
11332:     $txt=~tr/k-t/0-9/;
11333:     $txt=~tr/U-Z/0-5/;
11334:     $txt=~tr/u-z/0-5/;
11335:     $txt=~s/\D//g;
11336:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11337:     my $total;
11338:     foreach my $val (@txts) { $total+=$val; }
11339:     if ($_64bit) { $total=(($total<<32)>>32); }
11340:     return $total;
11341: }
11342: 
11343: sub digest {
11344:     my ($data)=@_;
11345:     my $digest=&Digest::MD5::md5($data);
11346:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11347:     my ($e,$f);
11348:     {
11349:         use integer;
11350:         $e=($a+$b);
11351:         $f=($c+$d);
11352:         if ($_64bit) {
11353:             $e=(($e<<32)>>32);
11354:             $f=(($f<<32)>>32);
11355:         }
11356:     }
11357:     if (wantarray) {
11358: 	return ($e,$f);
11359:     } else {
11360: 	my $g;
11361: 	{
11362: 	    use integer;
11363: 	    $g=($e+$f);
11364: 	    if ($_64bit) {
11365: 		$g=(($g<<32)>>32);
11366: 	    }
11367: 	}
11368: 	return $g;
11369:     }
11370: }
11371: 
11372: sub latest_rnd_algorithm_id {
11373:     return '64bit5';
11374: }
11375: 
11376: sub get_rand_alg {
11377:     my ($courseid)=@_;
11378:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11379:     if ($courseid) {
11380: 	return $env{"course.$courseid.rndseed"};
11381:     }
11382:     return &latest_rnd_algorithm_id();
11383: }
11384: 
11385: sub validCODE {
11386:     my ($CODE)=@_;
11387:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11388:     return 0;
11389: }
11390: 
11391: sub getCODE {
11392:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11393:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11394: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11395: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11396: 	return $Apache::lonhomework::history{'resource.CODE'};
11397:     }
11398:     return undef;
11399: }
11400: #
11401: #  Determines the random seed for a specific context:
11402: #
11403: # parameters:
11404: #   symb      - in course context the symb for the seed.
11405: #   course_id - The course id of the form domain_coursenum.
11406: #   domain    - Domain for the user.
11407: #   course    - Course for the user.
11408: #   cenv      - environment of the course.
11409: #
11410: # NOTE:
11411: #   All parameters are picked out of the environment if missing
11412: #   or not defined.
11413: #   If a symb cannot be determined the current time is used instead.
11414: #
11415: #  For a given well defined symb, courside, domain, username,
11416: #  and course environment, the seed is reproducible.
11417: #
11418: sub rndseed {
11419:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11420:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11421:     if (!defined($symb)) {
11422: 	unless ($symb=$wsymb) { return time; }
11423:     }
11424:     if (!defined $courseid) { 
11425: 	$courseid=$wcourseid; 
11426:     }
11427:     if (!defined $domain) { $domain=$wdomain; }
11428:     if (!defined $username) { $username=$wusername }
11429: 
11430:     my $which;
11431:     if (defined($cenv->{'rndseed'})) {
11432: 	$which = $cenv->{'rndseed'};
11433:     } else {
11434: 	$which =&get_rand_alg($courseid);
11435:     }
11436:     if (defined(&getCODE())) {
11437: 
11438: 	if ($which eq '64bit5') {
11439: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11440: 	} elsif ($which eq '64bit4') {
11441: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11442: 	} else {
11443: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11444: 	}
11445:     } elsif ($which eq '64bit5') {
11446: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11447:     } elsif ($which eq '64bit4') {
11448: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11449:     } elsif ($which eq '64bit3') {
11450: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11451:     } elsif ($which eq '64bit2') {
11452: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11453:     } elsif ($which eq '64bit') {
11454: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11455:     }
11456:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11457: }
11458: 
11459: sub rndseed_32bit {
11460:     my ($symb,$courseid,$domain,$username)=@_;
11461:     {
11462: 	use integer;
11463: 	my $symbchck=unpack("%32C*",$symb) << 27;
11464: 	my $symbseed=numval($symb) << 22;
11465: 	my $namechck=unpack("%32C*",$username) << 17;
11466: 	my $nameseed=numval($username) << 12;
11467: 	my $domainseed=unpack("%32C*",$domain) << 7;
11468: 	my $courseseed=unpack("%32C*",$courseid);
11469: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11470: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11471: 	#&logthis("rndseed :$num:$symb");
11472: 	if ($_64bit) { $num=(($num<<32)>>32); }
11473: 	return $num;
11474:     }
11475: }
11476: 
11477: sub rndseed_64bit {
11478:     my ($symb,$courseid,$domain,$username)=@_;
11479:     {
11480: 	use integer;
11481: 	my $symbchck=unpack("%32S*",$symb) << 21;
11482: 	my $symbseed=numval($symb) << 10;
11483: 	my $namechck=unpack("%32S*",$username);
11484: 	
11485: 	my $nameseed=numval($username) << 21;
11486: 	my $domainseed=unpack("%32S*",$domain) << 10;
11487: 	my $courseseed=unpack("%32S*",$courseid);
11488: 	
11489: 	my $num1=$symbchck+$symbseed+$namechck;
11490: 	my $num2=$nameseed+$domainseed+$courseseed;
11491: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11492: 	#&logthis("rndseed :$num:$symb");
11493: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11494: 	return "$num1,$num2";
11495:     }
11496: }
11497: 
11498: sub rndseed_64bit2 {
11499:     my ($symb,$courseid,$domain,$username)=@_;
11500:     {
11501: 	use integer;
11502: 	# strings need to be an even # of cahracters long, it it is odd the
11503:         # last characters gets thrown away
11504: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11505: 	my $symbseed=numval($symb) << 10;
11506: 	my $namechck=unpack("%32S*",$username.' ');
11507: 	
11508: 	my $nameseed=numval($username) << 21;
11509: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11510: 	my $courseseed=unpack("%32S*",$courseid.' ');
11511: 	
11512: 	my $num1=$symbchck+$symbseed+$namechck;
11513: 	my $num2=$nameseed+$domainseed+$courseseed;
11514: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11515: 	#&logthis("rndseed :$num:$symb");
11516: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11517: 	return "$num1,$num2";
11518:     }
11519: }
11520: 
11521: sub rndseed_64bit3 {
11522:     my ($symb,$courseid,$domain,$username)=@_;
11523:     {
11524: 	use integer;
11525: 	# strings need to be an even # of cahracters long, it it is odd the
11526:         # last characters gets thrown away
11527: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11528: 	my $symbseed=numval2($symb) << 10;
11529: 	my $namechck=unpack("%32S*",$username.' ');
11530: 	
11531: 	my $nameseed=numval2($username) << 21;
11532: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11533: 	my $courseseed=unpack("%32S*",$courseid.' ');
11534: 	
11535: 	my $num1=$symbchck+$symbseed+$namechck;
11536: 	my $num2=$nameseed+$domainseed+$courseseed;
11537: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11538: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11539: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11540: 	
11541: 	return "$num1:$num2";
11542:     }
11543: }
11544: 
11545: sub rndseed_64bit4 {
11546:     my ($symb,$courseid,$domain,$username)=@_;
11547:     {
11548: 	use integer;
11549: 	# strings need to be an even # of cahracters long, it it is odd the
11550:         # last characters gets thrown away
11551: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11552: 	my $symbseed=numval3($symb) << 10;
11553: 	my $namechck=unpack("%32S*",$username.' ');
11554: 	
11555: 	my $nameseed=numval3($username) << 21;
11556: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11557: 	my $courseseed=unpack("%32S*",$courseid.' ');
11558: 	
11559: 	my $num1=$symbchck+$symbseed+$namechck;
11560: 	my $num2=$nameseed+$domainseed+$courseseed;
11561: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11562: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11563: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11564: 	
11565: 	return "$num1:$num2";
11566:     }
11567: }
11568: 
11569: sub rndseed_64bit5 {
11570:     my ($symb,$courseid,$domain,$username)=@_;
11571:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11572:     return "$num1:$num2";
11573: }
11574: 
11575: sub rndseed_CODE_64bit {
11576:     my ($symb,$courseid,$domain,$username)=@_;
11577:     {
11578: 	use integer;
11579: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11580: 	my $symbseed=numval2($symb);
11581: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11582: 	my $CODEseed=numval(&getCODE());
11583: 	my $courseseed=unpack("%32S*",$courseid.' ');
11584: 	my $num1=$symbseed+$CODEchck;
11585: 	my $num2=$CODEseed+$courseseed+$symbchck;
11586: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11587: 	#&logthis("rndseed :$num1:$num2:$symb");
11588: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11589: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11590: 	return "$num1:$num2";
11591:     }
11592: }
11593: 
11594: sub rndseed_CODE_64bit4 {
11595:     my ($symb,$courseid,$domain,$username)=@_;
11596:     {
11597: 	use integer;
11598: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11599: 	my $symbseed=numval3($symb);
11600: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11601: 	my $CODEseed=numval3(&getCODE());
11602: 	my $courseseed=unpack("%32S*",$courseid.' ');
11603: 	my $num1=$symbseed+$CODEchck;
11604: 	my $num2=$CODEseed+$courseseed+$symbchck;
11605: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11606: 	#&logthis("rndseed :$num1:$num2:$symb");
11607: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11608: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11609: 	return "$num1:$num2";
11610:     }
11611: }
11612: 
11613: sub rndseed_CODE_64bit5 {
11614:     my ($symb,$courseid,$domain,$username)=@_;
11615:     my $code = &getCODE();
11616:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11617:     return "$num1:$num2";
11618: }
11619: 
11620: sub setup_random_from_rndseed {
11621:     my ($rndseed)=@_;
11622:     if ($rndseed =~/([,:])/) {
11623:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11624:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11625:             &Math::Random::random_set_seed_from_phrase($rndseed);
11626:         } else {
11627:             &Math::Random::random_set_seed($num1,$num2);
11628:         }
11629:     } else {
11630: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11631:     }
11632: }
11633: 
11634: sub latest_receipt_algorithm_id {
11635:     return 'receipt3';
11636: }
11637: 
11638: sub recunique {
11639:     my $fucourseid=shift;
11640:     my $unique;
11641:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11642: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11643: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11644:     } else {
11645: 	$unique=$perlvar{'lonReceipt'};
11646:     }
11647:     return unpack("%32C*",$unique);
11648: }
11649: 
11650: sub recprefix {
11651:     my $fucourseid=shift;
11652:     my $prefix;
11653:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11654: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11655: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11656:     } else {
11657: 	$prefix=$perlvar{'lonHostID'};
11658:     }
11659:     return unpack("%32C*",$prefix);
11660: }
11661: 
11662: sub ireceipt {
11663:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11664: 
11665:     my $return =&recprefix($fucourseid).'-';
11666: 
11667:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11668: 	$env{'request.state'} eq 'construct') {
11669: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11670: 	return $return;
11671:     }
11672: 
11673:     my $cuname=unpack("%32C*",$funame);
11674:     my $cudom=unpack("%32C*",$fudom);
11675:     my $cucourseid=unpack("%32C*",$fucourseid);
11676:     my $cusymb=unpack("%32C*",$fusymb);
11677:     my $cunique=&recunique($fucourseid);
11678:     my $cpart=unpack("%32S*",$part);
11679:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11680: 
11681: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11682: 			       
11683: 	$return.= ($cunique%$cuname+
11684: 		   $cunique%$cudom+
11685: 		   $cusymb%$cuname+
11686: 		   $cusymb%$cudom+
11687: 		   $cucourseid%$cuname+
11688: 		   $cucourseid%$cudom+
11689: 		   $cpart%$cuname+
11690: 		   $cpart%$cudom);
11691:     } else {
11692: 	$return.= ($cunique%$cuname+
11693: 		   $cunique%$cudom+
11694: 		   $cusymb%$cuname+
11695: 		   $cusymb%$cudom+
11696: 		   $cucourseid%$cuname+
11697: 		   $cucourseid%$cudom);
11698:     }
11699:     return $return;
11700: }
11701: 
11702: sub receipt {
11703:     my ($part)=@_;
11704:     my ($symb,$courseid,$domain,$name) = &whichuser();
11705:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11706: }
11707: 
11708: sub whichuser {
11709:     my ($passedsymb)=@_;
11710:     my ($symb,$courseid,$domain,$name,$publicuser);
11711:     if (defined($env{'form.grade_symb'})) {
11712: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11713: 	my $allowed=&allowed('vgr',$tmp_courseid);
11714: 	if (!$allowed &&
11715: 	    exists($env{'request.course.sec'}) &&
11716: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11717: 	    $allowed=&allowed('vgr',$tmp_courseid.
11718: 			      '/'.$env{'request.course.sec'});
11719: 	}
11720: 	if ($allowed) {
11721: 	    ($symb)=&get_env_multiple('form.grade_symb');
11722: 	    $courseid=$tmp_courseid;
11723: 	    ($domain)=&get_env_multiple('form.grade_domain');
11724: 	    ($name)=&get_env_multiple('form.grade_username');
11725: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11726: 	}
11727:     }
11728:     if (!$passedsymb) {
11729: 	$symb=&symbread();
11730:     } else {
11731: 	$symb=$passedsymb;
11732:     }
11733:     $courseid=$env{'request.course.id'};
11734:     $domain=$env{'user.domain'};
11735:     $name=$env{'user.name'};
11736:     if ($name eq 'public' && $domain eq 'public') {
11737: 	if (!defined($env{'form.username'})) {
11738: 	    $env{'form.username'}.=time.rand(10000000);
11739: 	}
11740: 	$name.=$env{'form.username'};
11741:     }
11742:     return ($symb,$courseid,$domain,$name,$publicuser);
11743: 
11744: }
11745: 
11746: # ------------------------------------------------------------ Serves up a file
11747: # returns either the contents of the file or 
11748: # -1 if the file doesn't exist
11749: #
11750: # if the target is a file that was uploaded via DOCS, 
11751: # a check will be made to see if a current copy exists on the local server,
11752: # if it does this will be served, otherwise a copy will be retrieved from
11753: # the home server for the course and stored in /home/httpd/html/userfiles on
11754: # the local server.   
11755: 
11756: sub getfile {
11757:     my ($file) = @_;
11758:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11759:     &repcopy($file);
11760:     return &readfile($file);
11761: }
11762: 
11763: sub repcopy_userfile {
11764:     my ($file)=@_;
11765:     my $londocroot = $perlvar{'lonDocRoot'};
11766:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11767:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11768:     my ($cdom,$cnum,$filename) = 
11769: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11770:     my $uri="/uploaded/$cdom/$cnum/$filename";
11771:     if (-e "$file") {
11772: # we already have a local copy, check it out
11773: 	my @fileinfo = stat($file);
11774: 	my $rtncode;
11775: 	my $info;
11776: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11777: 	if ($lwpresp ne 'ok') {
11778: # there is no such file anymore, even though we had a local copy
11779: 	    if ($rtncode eq '404') {
11780: 		unlink($file);
11781: 	    }
11782: 	    return -1;
11783: 	}
11784: 	if ($info < $fileinfo[9]) {
11785: # nice, the file we have is up-to-date, just say okay
11786: 	    return 'ok';
11787: 	} else {
11788: # the file is outdated, get rid of it
11789: 	    unlink($file);
11790: 	}
11791:     }
11792: # one way or the other, at this point, we don't have the file
11793: # construct the correct path for the file
11794:     my @parts = ($cdom,$cnum); 
11795:     if ($filename =~ m|^(.+)/[^/]+$|) {
11796: 	push @parts, split(/\//,$1);
11797:     }
11798:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11799:     foreach my $part (@parts) {
11800: 	$path .= '/'.$part;
11801: 	if (!-e $path) {
11802: 	    mkdir($path,0770);
11803: 	}
11804:     }
11805: # now the path exists for sure
11806: # get a user agent
11807:     my $ua=new LWP::UserAgent;
11808:     my $transferfile=$file.'.in.transfer';
11809: # FIXME: this should flock
11810:     if (-e $transferfile) { return 'ok'; }
11811:     my $request;
11812:     $uri=~s/^\///;
11813:     my $homeserver = &homeserver($cnum,$cdom);
11814:     my $protocol = $protocol{$homeserver};
11815:     $protocol = 'http' if ($protocol ne 'https');
11816:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11817:     my $response=$ua->request($request,$transferfile);
11818: # did it work?
11819:     if ($response->is_error()) {
11820: 	unlink($transferfile);
11821: 	&logthis("Userfile repcopy failed for $uri");
11822: 	return -1;
11823:     }
11824: # worked, rename the transfer file
11825:     rename($transferfile,$file);
11826:     return 'ok';
11827: }
11828: 
11829: sub tokenwrapper {
11830:     my $uri=shift;
11831:     $uri=~s|^https?\://([^/]+)||;
11832:     $uri=~s|^/||;
11833:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11834:     my $token=$1;
11835:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11836:     if ($udom && $uname && $file) {
11837: 	$file=~s|(\?\.*)*$||;
11838:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11839:         my $homeserver = &homeserver($uname,$udom);
11840:         my $protocol = $protocol{$homeserver};
11841:         $protocol = 'http' if ($protocol ne 'https');
11842:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11843:                (($uri=~/\?/)?'&':'?').'token='.$token.
11844:                                '&tokenissued='.$perlvar{'lonHostID'};
11845:     } else {
11846:         return '/adm/notfound.html';
11847:     }
11848: }
11849: 
11850: # call with reqtype HEAD: get last modification time
11851: # call with reqtype GET: get the file contents
11852: # Do not call this with reqtype GET for large files! It loads everything into memory
11853: #
11854: sub getuploaded {
11855:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11856:     $uri=~s/^\///;
11857:     my $homeserver = &homeserver($cnum,$cdom);
11858:     my $protocol = $protocol{$homeserver};
11859:     $protocol = 'http' if ($protocol ne 'https');
11860:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11861:     my $ua=new LWP::UserAgent;
11862:     my $request=new HTTP::Request($reqtype,$uri);
11863:     my $response=$ua->request($request);
11864:     $$rtncode = $response->code;
11865:     if (! $response->is_success()) {
11866: 	return 'failed';
11867:     }      
11868:     if ($reqtype eq 'HEAD') {
11869: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11870:     } elsif ($reqtype eq 'GET') {
11871: 	$$info = $response->content;
11872:     }
11873:     return 'ok';
11874: }
11875: 
11876: sub readfile {
11877:     my $file = shift;
11878:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11879:     my $fh;
11880:     open($fh,"<$file");
11881:     my $a='';
11882:     while (my $line = <$fh>) { $a .= $line; }
11883:     return $a;
11884: }
11885: 
11886: sub filelocation {
11887:     my ($dir,$file) = @_;
11888:     my $location;
11889:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11890: 
11891:     if ($file =~ m-^/adm/-) {
11892: 	$file=~s-^/adm/wrapper/-/-;
11893: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11894:     }
11895: 
11896:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11897:         $location = $file;
11898:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11899:         my ($udom,$uname,$filename)=
11900:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11901:         my $home=&homeserver($uname,$udom);
11902:         my $is_me=0;
11903:         my @ids=&current_machine_ids();
11904:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11905:         if ($is_me) {
11906:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11907:         } else {
11908:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11909:   	      $udom.'/'.$uname.'/'.$filename;
11910:         }
11911:     } elsif ($file =~ m-^/adm/-) {
11912: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11913:     } else {
11914:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11915:         $file=~s:^/(res|priv)/:/:;
11916:         my $space=$1;
11917:         if ( !( $file =~ m:^/:) ) {
11918:             $location = $dir. '/'.$file;
11919:         } else {
11920:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11921:         }
11922:     }
11923:     $location=~s://+:/:g; # remove duplicate /
11924:     while ($location=~m{/\.\./}) {
11925: 	if ($location =~ m{/[^/]+/\.\./}) {
11926: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11927: 	} else {
11928: 	    $location=~ s{/\.\./}{/}g;
11929: 	}
11930:     } #remove dir/..
11931:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11932:     return $location;
11933: }
11934: 
11935: sub hreflocation {
11936:     my ($dir,$file)=@_;
11937:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11938: 	$file=filelocation($dir,$file);
11939:     } elsif ($file=~m-^/adm/-) {
11940: 	$file=~s-^/adm/wrapper/-/-;
11941: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11942:     }
11943:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11944: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11945:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11946: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11947: 	        {/uploaded/$1/$2/}x;
11948:     }
11949:     if ($file=~ m{^/userfiles/}) {
11950: 	$file =~ s{^/userfiles/}{/uploaded/};
11951:     }
11952:     return $file;
11953: }
11954: 
11955: 
11956: 
11957: 
11958: 
11959: sub current_machine_domains {
11960:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11961: }
11962: 
11963: sub machine_domains {
11964:     my ($hostname) = @_;
11965:     my @domains;
11966:     my %hostname = &all_hostnames();
11967:     while( my($id, $name) = each(%hostname)) {
11968: #	&logthis("-$id-$name-$hostname-");
11969: 	if ($hostname eq $name) {
11970: 	    push(@domains,&host_domain($id));
11971: 	}
11972:     }
11973:     return @domains;
11974: }
11975: 
11976: sub current_machine_ids {
11977:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11978: }
11979: 
11980: sub machine_ids {
11981:     my ($hostname) = @_;
11982:     $hostname ||= &hostname($perlvar{'lonHostID'});
11983:     my @ids;
11984:     my %name_to_host = &all_names();
11985:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11986: 	return @{ $name_to_host{$hostname} };
11987:     }
11988:     return;
11989: }
11990: 
11991: sub additional_machine_domains {
11992:     my @domains;
11993:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11994:     while( my $line = <$fh>) {
11995:         $line =~ s/\s//g;
11996:         push(@domains,$line);
11997:     }
11998:     return @domains;
11999: }
12000: 
12001: sub default_login_domain {
12002:     my $domain = $perlvar{'lonDefDomain'};
12003:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12004:     foreach my $posdom (&current_machine_domains(),
12005:                         &additional_machine_domains()) {
12006:         if (lc($posdom) eq lc($testdomain)) {
12007:             $domain=$posdom;
12008:             last;
12009:         }
12010:     }
12011:     return $domain;
12012: }
12013: 
12014: # ------------------------------------------------------------- Declutters URLs
12015: 
12016: sub declutter {
12017:     my $thisfn=shift;
12018:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12019:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12020:         $thisfn=~s{^/home/httpd/html}{};
12021:     }
12022:     $thisfn=~s/^\///;
12023:     $thisfn=~s|^adm/wrapper/||;
12024:     $thisfn=~s|^adm/coursedocs/showdoc/||;
12025:     $thisfn=~s/^res\///;
12026:     $thisfn=~s/^priv\///;
12027:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12028:         $thisfn=~s/\?.+$//;
12029:     }
12030:     return $thisfn;
12031: }
12032: 
12033: # ------------------------------------------------------------- Clutter up URLs
12034: 
12035: sub clutter {
12036:     my $thisfn='/'.&declutter(shift);
12037:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
12038: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
12039:        $thisfn='/res'.$thisfn; 
12040:     }
12041:     if ($thisfn !~m|^/adm|) {
12042: 	if ($thisfn =~ m|^/ext/|) {
12043: 	    $thisfn='/adm/wrapper'.$thisfn;
12044: 	} else {
12045: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
12046: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
12047: 	    if ($embstyle eq 'ssi'
12048: 		|| ($embstyle eq 'hdn')
12049: 		|| ($embstyle eq 'rat')
12050: 		|| ($embstyle eq 'prv')
12051: 		|| ($embstyle eq 'ign')) {
12052: 		#do nothing with these
12053: 	    } elsif (($embstyle eq 'img') 
12054: 		|| ($embstyle eq 'emb')
12055: 		|| ($embstyle eq 'wrp')) {
12056: 		$thisfn='/adm/wrapper'.$thisfn;
12057: 	    } elsif ($embstyle eq 'unk'
12058: 		     && $thisfn!~/\.(sequence|page)$/) {
12059: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
12060: 	    } else {
12061: #		&logthis("Got a blank emb style");
12062: 	    }
12063: 	}
12064:     }
12065:     return $thisfn;
12066: }
12067: 
12068: sub clutter_with_no_wrapper {
12069:     my $uri = &clutter(shift);
12070:     if ($uri =~ m-^/adm/-) {
12071: 	$uri =~ s-^/adm/wrapper/-/-;
12072: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
12073:     }
12074:     return $uri;
12075: }
12076: 
12077: sub freeze_escape {
12078:     my ($value)=@_;
12079:     if (ref($value)) {
12080: 	$value=&nfreeze($value);
12081: 	return '__FROZEN__'.&escape($value);
12082:     }
12083:     return &escape($value);
12084: }
12085: 
12086: 
12087: sub thaw_unescape {
12088:     my ($value)=@_;
12089:     if ($value =~ /^__FROZEN__/) {
12090: 	substr($value,0,10,undef);
12091: 	$value=&unescape($value);
12092: 	return &thaw($value);
12093:     }
12094:     return &unescape($value);
12095: }
12096: 
12097: sub correct_line_ends {
12098:     my ($result)=@_;
12099:     $$result =~s/\r\n/\n/mg;
12100:     $$result =~s/\r/\n/mg;
12101: }
12102: # ================================================================ Main Program
12103: 
12104: sub goodbye {
12105:    &logthis("Starting Shut down");
12106: #not converted to using infrastruture and probably shouldn't be
12107:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
12108: #converted
12109: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
12110:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12111: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12112: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
12113: #1.1 only
12114: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12115: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12116: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12117: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12118:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12119:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12120:    &logthis(sprintf("%-20s is %s",'hits',$hits));
12121:    &flushcourselogs();
12122:    &logthis("Shutting down");
12123: }
12124: 
12125: sub get_dns {
12126:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12127:     if (!$ignore_cache) {
12128: 	my ($content,$cached)=
12129: 	    &Apache::lonnet::is_cached_new('dns',$url);
12130: 	if ($cached) {
12131: 	    &$func($content,$hashref);
12132: 	    return;
12133: 	}
12134:     }
12135: 
12136:     my %alldns;
12137:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12138:     foreach my $dns (<$config>) {
12139: 	next if ($dns !~ /^\^(\S*)/x);
12140:         my $line = $1;
12141:         my ($host,$protocol) = split(/:/,$line);
12142:         if ($protocol ne 'https') {
12143:             $protocol = 'http';
12144:         }
12145: 	$alldns{$host} = $protocol;
12146:     }
12147:     while (%alldns) {
12148: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12149: 	my $ua=new LWP::UserAgent;
12150:         $ua->timeout(30);
12151: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12152: 	my $response=$ua->request($request);
12153:         delete($alldns{$dns});
12154: 	next if ($response->is_error());
12155: 	my @content = split("\n",$response->content);
12156: 	unless ($nocache) {
12157: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12158: 	}
12159: 	&$func(\@content,$hashref);
12160: 	return;
12161:     }
12162:     close($config);
12163:     my $which = (split('/',$url))[3];
12164:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12165:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12166:     my @content = <$config>;
12167:     &$func(\@content,$hashref);
12168:     return;
12169: }
12170: 
12171: # ------------------------------------------------------Get DNS checksums file
12172: sub parse_dns_checksums_tab {
12173:     my ($lines,$hashref) = @_;
12174:     my $lonhost = $perlvar{'lonHostID'};
12175:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12176:     my $loncaparev = &get_server_loncaparev($machine_dom);
12177:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12178:     my $webconfdir = '/etc/httpd/conf';
12179:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12180:         $webconfdir = '/etc/apache2';
12181:     } elsif ($distro =~ /^sles(\d+)$/) {
12182:         if ($1 >= 10) {
12183:             $webconfdir = '/etc/apache2';
12184:         }
12185:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12186:         if ($1 >= 10.0) {
12187:             $webconfdir = '/etc/apache2';
12188:         }
12189:     }
12190:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12191:     my (%chksum,%revnum);
12192:     if (ref($lines) eq 'ARRAY') {
12193:         chomp(@{$lines});
12194:         my $version = shift(@{$lines});
12195:         if ($version eq $release) {  
12196:             foreach my $line (@{$lines}) {
12197:                 my ($file,$version,$shasum) = split(/,/,$line);
12198:                 if ($file =~ m{^/etc/httpd/conf}) {
12199:                     if ($webconfdir eq '/etc/apache2') {
12200:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12201:                     }
12202:                 }
12203:                 $chksum{$file} = $shasum;
12204:                 $revnum{$file} = $version;
12205:             }
12206:             if (ref($hashref) eq 'HASH') {
12207:                 %{$hashref} = (
12208:                                 sums     => \%chksum,
12209:                                 versions => \%revnum,
12210:                               );
12211:             }
12212:         }
12213:     }
12214:     return;
12215: }
12216: 
12217: sub fetch_dns_checksums {
12218:     my %checksums;
12219:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12220:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12221:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12222:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12223:              \%checksums);
12224:     return \%checksums;
12225: }
12226: 
12227: # ------------------------------------------------------------ Read domain file
12228: {
12229:     my $loaded;
12230:     my %domain;
12231: 
12232:     sub parse_domain_tab {
12233: 	my ($lines) = @_;
12234: 	foreach my $line (@$lines) {
12235: 	    next if ($line =~ /^(\#|\s*$ )/x);
12236: 
12237: 	    chomp($line);
12238: 	    my ($name,@elements) = split(/:/,$line,9);
12239: 	    my %this_domain;
12240: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12241: 			       'lang_def', 'city', 'longi', 'lati',
12242: 			       'primary') {
12243: 		$this_domain{$field} = shift(@elements);
12244: 	    }
12245: 	    $domain{$name} = \%this_domain;
12246: 	}
12247:     }
12248: 
12249:     sub reset_domain_info {
12250: 	undef($loaded);
12251: 	undef(%domain);
12252:     }
12253: 
12254:     sub load_domain_tab {
12255: 	my ($ignore_cache) = @_;
12256: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
12257: 	my $fh;
12258: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12259: 	    my @lines = <$fh>;
12260: 	    &parse_domain_tab(\@lines);
12261: 	}
12262: 	close($fh);
12263: 	$loaded = 1;
12264:     }
12265: 
12266:     sub domain {
12267: 	&load_domain_tab() if (!$loaded);
12268: 
12269: 	my ($name,$what) = @_;
12270: 	return if ( !exists($domain{$name}) );
12271: 
12272: 	if (!$what) {
12273: 	    return $domain{$name}{'description'};
12274: 	}
12275: 	return $domain{$name}{$what};
12276:     }
12277: 
12278:     sub domain_info {
12279:         &load_domain_tab() if (!$loaded);
12280:         return %domain;
12281:     }
12282: 
12283: }
12284: 
12285: 
12286: # ------------------------------------------------------------- Read hosts file
12287: {
12288:     my %hostname;
12289:     my %hostdom;
12290:     my %libserv;
12291:     my $loaded;
12292:     my %name_to_host;
12293:     my %internetdom;
12294:     my %LC_dns_serv;
12295: 
12296:     sub parse_hosts_tab {
12297: 	my ($file) = @_;
12298: 	foreach my $configline (@$file) {
12299: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12300:             chomp($configline);
12301: 	    if ($configline =~ /^\^/) {
12302:                 if ($configline =~ /^\^([\w.\-]+)/) {
12303:                     $LC_dns_serv{$1} = 1;
12304:                 }
12305:                 next;
12306:             }
12307: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12308: 	    $name=~s/\s//g;
12309: 	    if ($id && $domain && $role && $name) {
12310: 		$hostname{$id}=$name;
12311: 		push(@{$name_to_host{$name}}, $id);
12312: 		$hostdom{$id}=$domain;
12313: 		if ($role eq 'library') { $libserv{$id}=$name; }
12314:                 if (defined($protocol)) {
12315:                     if ($protocol eq 'https') {
12316:                         $protocol{$id} = $protocol;
12317:                     } else {
12318:                         $protocol{$id} = 'http'; 
12319:                     }
12320:                 } else {
12321:                     $protocol{$id} = 'http';
12322:                 }
12323:                 if (defined($intdom)) {
12324:                     $internetdom{$id} = $intdom;
12325:                 }
12326: 	    }
12327: 	}
12328:     }
12329:     
12330:     sub reset_hosts_info {
12331: 	&purge_remembered();
12332: 	&reset_domain_info();
12333: 	&reset_hosts_ip_info();
12334: 	undef(%name_to_host);
12335: 	undef(%hostname);
12336: 	undef(%hostdom);
12337: 	undef(%libserv);
12338: 	undef($loaded);
12339:     }
12340: 
12341:     sub load_hosts_tab {
12342: 	my ($ignore_cache) = @_;
12343: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12344: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12345: 	my @config = <$config>;
12346: 	&parse_hosts_tab(\@config);
12347: 	close($config);
12348: 	$loaded=1;
12349:     }
12350: 
12351:     sub hostname {
12352: 	&load_hosts_tab() if (!$loaded);
12353: 
12354: 	my ($lonid) = @_;
12355: 	return $hostname{$lonid};
12356:     }
12357: 
12358:     sub all_hostnames {
12359: 	&load_hosts_tab() if (!$loaded);
12360: 
12361: 	return %hostname;
12362:     }
12363: 
12364:     sub all_names {
12365: 	&load_hosts_tab() if (!$loaded);
12366: 
12367: 	return %name_to_host;
12368:     }
12369: 
12370:     sub all_host_domain {
12371:         &load_hosts_tab() if (!$loaded);
12372:         return %hostdom;
12373:     }
12374: 
12375:     sub is_library {
12376: 	&load_hosts_tab() if (!$loaded);
12377: 
12378: 	return exists($libserv{$_[0]});
12379:     }
12380: 
12381:     sub all_library {
12382: 	&load_hosts_tab() if (!$loaded);
12383: 
12384: 	return %libserv;
12385:     }
12386: 
12387:     sub unique_library {
12388: 	#2x reverse removes all hostnames that appear more than once
12389:         my %unique = reverse &all_library();
12390:         return reverse %unique;
12391:     }
12392: 
12393:     sub get_servers {
12394: 	&load_hosts_tab() if (!$loaded);
12395: 
12396: 	my ($domain,$type) = @_;
12397: 	my %possible_hosts = ($type eq 'library') ? %libserv
12398: 	                                          : %hostname;
12399: 	my %result;
12400: 	if (ref($domain) eq 'ARRAY') {
12401: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12402: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12403: 		    $result{$host} = $hostname;
12404: 		}
12405: 	    }
12406: 	} else {
12407: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12408: 		if ($hostdom{$host} eq $domain) {
12409: 		    $result{$host} = $hostname;
12410: 		}
12411: 	    }
12412: 	}
12413: 	return %result;
12414:     }
12415: 
12416:     sub get_unique_servers {
12417:         my %unique = reverse &get_servers(@_);
12418: 	return reverse %unique;
12419:     }
12420: 
12421:     sub host_domain {
12422: 	&load_hosts_tab() if (!$loaded);
12423: 
12424: 	my ($lonid) = @_;
12425: 	return $hostdom{$lonid};
12426:     }
12427: 
12428:     sub all_domains {
12429: 	&load_hosts_tab() if (!$loaded);
12430: 
12431: 	my %seen;
12432: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12433: 	return @uniq;
12434:     }
12435: 
12436:     sub internet_dom {
12437:         &load_hosts_tab() if (!$loaded);
12438: 
12439:         my ($lonid) = @_;
12440:         return $internetdom{$lonid};
12441:     }
12442: 
12443:     sub is_LC_dns {
12444:         &load_hosts_tab() if (!$loaded);
12445: 
12446:         my ($hostname) = @_;
12447:         return exists($LC_dns_serv{$hostname});
12448:     }
12449: 
12450: }
12451: 
12452: { 
12453:     my %iphost;
12454:     my %name_to_ip;
12455:     my %lonid_to_ip;
12456: 
12457:     sub get_hosts_from_ip {
12458: 	my ($ip) = @_;
12459: 	my %iphosts = &get_iphost();
12460: 	if (ref($iphosts{$ip})) {
12461: 	    return @{$iphosts{$ip}};
12462: 	}
12463: 	return;
12464:     }
12465:     
12466:     sub reset_hosts_ip_info {
12467: 	undef(%iphost);
12468: 	undef(%name_to_ip);
12469: 	undef(%lonid_to_ip);
12470:     }
12471: 
12472:     sub get_host_ip {
12473: 	my ($lonid) = @_;
12474: 	if (exists($lonid_to_ip{$lonid})) {
12475: 	    return $lonid_to_ip{$lonid};
12476: 	}
12477: 	my $name=&hostname($lonid);
12478:    	my $ip = gethostbyname($name);
12479: 	return if (!$ip || length($ip) ne 4);
12480: 	$ip=inet_ntoa($ip);
12481: 	$name_to_ip{$name}   = $ip;
12482: 	$lonid_to_ip{$lonid} = $ip;
12483: 	return $ip;
12484:     }
12485:     
12486:     sub get_iphost {
12487: 	my ($ignore_cache) = @_;
12488: 
12489: 	if (!$ignore_cache) {
12490: 	    if (%iphost) {
12491: 		return %iphost;
12492: 	    }
12493: 	    my ($ip_info,$cached)=
12494: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12495: 	    if ($cached) {
12496: 		%iphost      = %{$ip_info->[0]};
12497: 		%name_to_ip  = %{$ip_info->[1]};
12498: 		%lonid_to_ip = %{$ip_info->[2]};
12499: 		return %iphost;
12500: 	    }
12501: 	}
12502: 
12503: 	# get yesterday's info for fallback
12504: 	my %old_name_to_ip;
12505: 	my ($ip_info,$cached)=
12506: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12507: 	if ($cached) {
12508: 	    %old_name_to_ip = %{$ip_info->[1]};
12509: 	}
12510: 
12511: 	my %name_to_host = &all_names();
12512: 	foreach my $name (keys(%name_to_host)) {
12513: 	    my $ip;
12514: 	    if (!exists($name_to_ip{$name})) {
12515: 		$ip = gethostbyname($name);
12516: 		if (!$ip || length($ip) ne 4) {
12517: 		    if (defined($old_name_to_ip{$name})) {
12518: 			$ip = $old_name_to_ip{$name};
12519: 			&logthis("Can't find $name defaulting to old $ip");
12520: 		    } else {
12521: 			&logthis("Name $name no IP found");
12522: 			next;
12523: 		    }
12524: 		} else {
12525: 		    $ip=inet_ntoa($ip);
12526: 		}
12527: 		$name_to_ip{$name} = $ip;
12528: 	    } else {
12529: 		$ip = $name_to_ip{$name};
12530: 	    }
12531: 	    foreach my $id (@{ $name_to_host{$name} }) {
12532: 		$lonid_to_ip{$id} = $ip;
12533: 	    }
12534: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12535: 	}
12536: 	&do_cache_new('iphost','iphost',
12537: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12538: 		      48*60*60);
12539: 
12540: 	return %iphost;
12541:     }
12542: 
12543:     #
12544:     #  Given a DNS returns the loncapa host name for that DNS 
12545:     # 
12546:     sub host_from_dns {
12547:         my ($dns) = @_;
12548:         my @hosts;
12549:         my $ip;
12550: 
12551:         if (exists($name_to_ip{$dns})) {
12552:             $ip = $name_to_ip{$dns};
12553:         }
12554:         if (!$ip) {
12555:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12556:             if (length($ip) == 4) { 
12557: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12558:             }
12559:         }
12560:         if ($ip) {
12561: 	    @hosts = get_hosts_from_ip($ip);
12562: 	    return $hosts[0];
12563:         }
12564:         return undef;
12565:     }
12566: 
12567:     sub get_internet_names {
12568:         my ($lonid) = @_;
12569:         return if ($lonid eq '');
12570:         my ($idnref,$cached)=
12571:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12572:         if ($cached) {
12573:             return $idnref;
12574:         }
12575:         my $ip = &get_host_ip($lonid);
12576:         my @hosts = &get_hosts_from_ip($ip);
12577:         my %iphost = &get_iphost();
12578:         my (@idns,%seen);
12579:         foreach my $id (@hosts) {
12580:             my $dom = &host_domain($id);
12581:             my $prim_id = &domain($dom,'primary');
12582:             my $prim_ip = &get_host_ip($prim_id);
12583:             next if ($seen{$prim_ip});
12584:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12585:                 foreach my $id (@{$iphost{$prim_ip}}) {
12586:                     my $intdom = &internet_dom($id);
12587:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12588:                         push(@idns,$intdom);
12589:                     }
12590:                 }
12591:             }
12592:             $seen{$prim_ip} = 1;
12593:         }
12594:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12595:     }
12596: 
12597: }
12598: 
12599: sub all_loncaparevs {
12600:     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);
12601: }
12602: 
12603: # ---------------------------------------------------------- Read loncaparev table
12604: {
12605:     sub load_loncaparevs { 
12606:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12607:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12608:                 while (my $configline=<$config>) {
12609:                     chomp($configline);
12610:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12611:                     $loncaparevs{$hostid}=$loncaparev;
12612:                 }
12613:                 close($config);
12614:             }
12615:         }
12616:     }
12617: }
12618: 
12619: # ---------------------------------------------------------- Read serverhostID table
12620: {
12621:     sub load_serverhomeIDs {
12622:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12623:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12624:                 while (my $configline=<$config>) {
12625:                     chomp($configline);
12626:                     my ($name,$id)=split(/:/,$configline);
12627:                     $serverhomeIDs{$name}=$id;
12628:                 }
12629:                 close($config);
12630:             }
12631:         }
12632:     }
12633: }
12634: 
12635: 
12636: BEGIN {
12637: 
12638: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12639:     unless ($readit) {
12640: {
12641:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12642:     %perlvar = (%perlvar,%{$configvars});
12643: }
12644: 
12645: 
12646: # ------------------------------------------------------ Read spare server file
12647: {
12648:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12649: 
12650:     while (my $configline=<$config>) {
12651:        chomp($configline);
12652:        if ($configline) {
12653: 	   my ($host,$type) = split(':',$configline,2);
12654: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12655: 	   push(@{ $spareid{$type} }, $host);
12656:        }
12657:     }
12658:     close($config);
12659: }
12660: # ------------------------------------------------------------ Read permissions
12661: {
12662:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12663: 
12664:     while (my $configline=<$config>) {
12665: 	chomp($configline);
12666: 	if ($configline) {
12667: 	    my ($role,$perm)=split(/ /,$configline);
12668: 	    if ($perm ne '') { $pr{$role}=$perm; }
12669: 	}
12670:     }
12671:     close($config);
12672: }
12673: 
12674: # -------------------------------------------- Read plain texts for permissions
12675: {
12676:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12677: 
12678:     while (my $configline=<$config>) {
12679: 	chomp($configline);
12680: 	if ($configline) {
12681: 	    my ($short,@plain)=split(/:/,$configline);
12682:             %{$prp{$short}} = ();
12683: 	    if (@plain > 0) {
12684:                 $prp{$short}{'std'} = $plain[0];
12685:                 for (my $i=1; $i<@plain; $i++) {
12686:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12687:                 }
12688:             }
12689: 	}
12690:     }
12691:     close($config);
12692: }
12693: 
12694: # ---------------------------------------------------------- Read package table
12695: {
12696:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12697: 
12698:     while (my $configline=<$config>) {
12699: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12700: 	chomp($configline);
12701: 	my ($short,$plain)=split(/:/,$configline);
12702: 	my ($pack,$name)=split(/\&/,$short);
12703: 	if ($plain ne '') {
12704: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12705: 	    $packagetab{$short}=$plain; 
12706: 	}
12707:     }
12708:     close($config);
12709: }
12710: 
12711: # ---------------------------------------------------------- Read loncaparev table
12712: 
12713: &load_loncaparevs();
12714: 
12715: # ---------------------------------------------------------- Read serverhostID table
12716: 
12717: &load_serverhomeIDs();
12718: 
12719: # ---------------------------------------------------------- Read releaseslist XML
12720: {
12721:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12722:     if (-e $file) {
12723:         my $parser = HTML::LCParser->new($file);
12724:         while (my $token = $parser->get_token()) {
12725:             if ($token->[0] eq 'S') {
12726:                 my $item = $token->[1];
12727:                 my $name = $token->[2]{'name'};
12728:                 my $value = $token->[2]{'value'};
12729:                 if ($item ne '' && $name ne '' && $value ne '') {
12730:                     my $release = $parser->get_text();
12731:                     $release =~ s/(^\s*|\s*$ )//gx;
12732:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12733:                 }
12734:             }
12735:         }
12736:     }
12737: }
12738: 
12739: # ---------------------------------------------------------- Read managers table
12740: {
12741:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12742:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12743:             while (my $configline=<$config>) {
12744:                 chomp($configline);
12745:                 next if ($configline =~ /^\#/);
12746:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12747:                     $managerstab{$configline} = 1;
12748:                 }
12749:             }
12750:             close($config);
12751:         }
12752:     }
12753: }
12754: 
12755: # ------------- set up temporary directory
12756: {
12757:     $tmpdir = LONCAPA::tempdir();
12758: 
12759: }
12760: 
12761: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12762: 				'compress_threshold'=> 20_000,
12763:  			        });
12764: 
12765: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12766: $dumpcount=0;
12767: $locknum=0;
12768: 
12769: &logtouch();
12770: &logthis('<font color="yellow">INFO: Read configuration</font>');
12771: $readit=1;
12772:     {
12773: 	use integer;
12774: 	my $test=(2**32)+1;
12775: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12776: 	&logthis(" Detected 64bit platform ($_64bit)");
12777:     }
12778: }
12779: }
12780: 
12781: 1;
12782: __END__
12783: 
12784: =pod
12785: 
12786: =head1 NAME
12787: 
12788: Apache::lonnet - Subroutines to ask questions about things in the network.
12789: 
12790: =head1 SYNOPSIS
12791: 
12792: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12793: 
12794:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12795: 
12796: Common parameters:
12797: 
12798: =over 4
12799: 
12800: =item *
12801: 
12802: $uname : an internal username (if $cname expecting a course Id specifically)
12803: 
12804: =item *
12805: 
12806: $udom : a domain (if $cdom expecting a course's domain specifically)
12807: 
12808: =item *
12809: 
12810: $symb : a resource instance identifier
12811: 
12812: =item *
12813: 
12814: $namespace : the name of a .db file that contains the data needed or
12815: being set.
12816: 
12817: =back
12818: 
12819: =head1 OVERVIEW
12820: 
12821: lonnet provides subroutines which interact with the
12822: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12823: about classes, users, and resources.
12824: 
12825: For many of these objects you can also use this to store data about
12826: them or modify them in various ways.
12827: 
12828: =head2 Symbs
12829: 
12830: To identify a specific instance of a resource, LON-CAPA uses symbols
12831: or "symbs"X<symb>. These identifiers are built from the URL of the
12832: map, the resource number of the resource in the map, and the URL of
12833: the resource itself. The latter is somewhat redundant, but might help
12834: if maps change.
12835: 
12836: An example is
12837: 
12838:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12839: 
12840: The respective map entry is
12841: 
12842:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12843:   title="Problem 2">
12844:  </resource>
12845: 
12846: Symbs are used by the random number generator, as well as to store and
12847: restore data specific to a certain instance of for example a problem.
12848: 
12849: =head2 Storing And Retrieving Data
12850: 
12851: X<store()>X<cstore()>X<restore()>Three of the most important functions
12852: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12853: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12854: is is the non-critical message twin of cstore. These functions are for
12855: handlers to store a perl hash to a user's permanent data space in an
12856: easy manner, and to retrieve it again on another call. It is expected
12857: that a handler would use this once at the beginning to retrieve data,
12858: and then again once at the end to send only the new data back.
12859: 
12860: The data is stored in the user's data directory on the user's
12861: homeserver under the ID of the course.
12862: 
12863: The hash that is returned by restore will have all of the previous
12864: value for all of the elements of the hash.
12865: 
12866: Example:
12867: 
12868:  #creating a hash
12869:  my %hash;
12870:  $hash{'foo'}='bar';
12871: 
12872:  #storing it
12873:  &Apache::lonnet::cstore(\%hash);
12874: 
12875:  #changing a value
12876:  $hash{'foo'}='notbar';
12877: 
12878:  #adding a new value
12879:  $hash{'bar'}='foo';
12880:  &Apache::lonnet::cstore(\%hash);
12881: 
12882:  #retrieving the hash
12883:  my %history=&Apache::lonnet::restore();
12884: 
12885:  #print the hash
12886:  foreach my $key (sort(keys(%history))) {
12887:    print("\%history{$key} = $history{$key}");
12888:  }
12889: 
12890: Will print out:
12891: 
12892:  %history{1:foo} = bar
12893:  %history{1:keys} = foo:timestamp
12894:  %history{1:timestamp} = 990455579
12895:  %history{2:bar} = foo
12896:  %history{2:foo} = notbar
12897:  %history{2:keys} = foo:bar:timestamp
12898:  %history{2:timestamp} = 990455580
12899:  %history{bar} = foo
12900:  %history{foo} = notbar
12901:  %history{timestamp} = 990455580
12902:  %history{version} = 2
12903: 
12904: Note that the special hash entries C<keys>, C<version> and
12905: C<timestamp> were added to the hash. C<version> will be equal to the
12906: total number of versions of the data that have been stored. The
12907: C<timestamp> attribute will be the UNIX time the hash was
12908: stored. C<keys> is available in every historical section to list which
12909: keys were added or changed at a specific historical revision of a
12910: hash.
12911: 
12912: B<Warning>: do not store the hash that restore returns directly. This
12913: will cause a mess since it will restore the historical keys as if the
12914: were new keys. I.E. 1:foo will become 1:1:foo etc.
12915: 
12916: Calling convention:
12917: 
12918:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12919:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
12920: 
12921: For more detailed information, see lonnet specific documentation.
12922: 
12923: =head1 RETURN MESSAGES
12924: 
12925: =over 4
12926: 
12927: =item * B<con_lost>: unable to contact remote host
12928: 
12929: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12930: when the connection is brought back up
12931: 
12932: =item * B<con_failed>: unable to contact remote host and unable to save message
12933: for later delivery
12934: 
12935: =item * B<error:>: an error a occurred, a description of the error follows the :
12936: 
12937: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12938: that was requested
12939: 
12940: =back
12941: 
12942: =head1 PUBLIC SUBROUTINES
12943: 
12944: =head2 Session Environment Functions
12945: 
12946: =over 4
12947: 
12948: =item * 
12949: X<appenv()>
12950: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12951: the user envirnoment file, and will be restored for each access this
12952: user makes during this session, also modifies the %env for the current
12953: process. Optional rolesarrayref - if defined contains a reference to an array
12954: of roles which are exempt from the restriction on modifying user.role entries 
12955: in the user's environment.db and in %env.    
12956: 
12957: =item *
12958: X<delenv()>
12959: B<delenv($delthis,$regexp)>: removes all items from the session
12960: environment file that begin with $delthis. If the 
12961: optional second arg - $regexp - is true, $delthis is treated as a 
12962: regular expression, otherwise \Q$delthis\E is used. 
12963: The values are also deleted from the current processes %env.
12964: 
12965: =item * get_env_multiple($name) 
12966: 
12967: gets $name from the %env hash, it seemlessly handles the cases where multiple
12968: values may be defined and end up as an array ref.
12969: 
12970: returns an array of values
12971: 
12972: =back
12973: 
12974: =head2 User Information
12975: 
12976: =over 4
12977: 
12978: =item *
12979: X<queryauthenticate()>
12980: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12981: authentication scheme
12982: 
12983: =item *
12984: X<authenticate()>
12985: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12986: authenticate user from domain's lib servers (first use the current
12987: one). C<$upass> should be the users password.
12988: $checkdefauth is optional (value is 1 if a check should be made to
12989:    authenticate user using default authentication method, and allow
12990:    account creation if username does not have account in the domain).
12991: $clientcancheckhost is optional (value is 1 if checking whether the
12992:    server can host will occur on the client side in lonauth.pm).   
12993: 
12994: =item *
12995: X<homeserver()>
12996: B<homeserver($uname,$udom)>: find the server which has
12997: the user's directory and files (there must be only one), this caches
12998: the answer, and also caches if there is a borken connection.
12999: 
13000: =item *
13001: X<idget()>
13002: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13003: (IDs are a unique resource in a domain, there must be only 1 ID per
13004: username, and only 1 username per ID in a specific domain) (returns
13005: hash: id=>name,id=>name)
13006: 
13007: =item *
13008: X<idrget()>
13009: B<idrget($udom,@unames)>: find the IDs behind a list of
13010: usernames (returns hash: name=>id,name=>id)
13011: 
13012: =item *
13013: X<idput()>
13014: B<idput($udom,%ids)>: store away a list of names and associated IDs
13015: 
13016: =item *
13017: X<rolesinit()>
13018: B<rolesinit($udom,$username)>: get user privileges.
13019: returns user role, first access and timer interval hashes
13020: 
13021: =item *
13022: X<privileged()>
13023: B<privileged($username,$domain)>: returns a true if user has a
13024: privileged and active role (i.e. su or dc), false otherwise.
13025: 
13026: =item *
13027: X<getsection()>
13028: B<getsection($udom,$uname,$cname)>: finds the section of student in the
13029: course $cname, return section name/number or '' for "not in course"
13030: and '-1' for "no section"
13031: 
13032: =item *
13033: X<userenvironment()>
13034: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
13035: passed in @what from the requested user's environment, returns a hash
13036: 
13037: =item * 
13038: X<userlog_query()>
13039: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13040: activity.log file. %filters defines filters applied when parsing the
13041: log file. These can be start or end timestamps, or the type of action
13042: - log to look for Login or Logout events, check for Checkin or
13043: Checkout, role for role selection. The response is in the form
13044: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
13045: escaped strings of the action recorded in the activity.log file.
13046: 
13047: =back
13048: 
13049: =head2 User Roles
13050: 
13051: =over 4
13052: 
13053: =item *
13054: 
13055: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
13056: returns codes for allowed actions.
13057: 
13058: The first argument is required, all others are optional.
13059: 
13060: $priv is the privilege being checked.
13061: $uri contains additional information about what is being checked for access (e.g.,
13062: URL, course ID etc.). 
13063: $symb is the unique resource instance identifier in a course; if needed,
13064: but not provided, it will be retrieved via a call to &symbread(). 
13065: $role is the role for which a priv is being checked (only used if priv is evb). 
13066: $clientip is the user's IP address (only used when checking for access to portfolio 
13067: files).
13068: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
13069: prevents recursive calls to &allowed.
13070: 
13071:  F: full access
13072:  U,I,K: authentication modes (cxx only)
13073:  '': forbidden
13074:  1: user needs to choose course
13075:  2: browse allowed
13076:  A: passphrase authentication needed
13077:  B: access temporarily blocked because of a blocking event in a course.
13078: 
13079: =item *
13080: 
13081: constructaccess($url,$setpriv) : check for access to construction space URL
13082: 
13083: See if the owner domain and name in the URL match those in the
13084: expected environment.  If so, return three element list
13085: ($ownername,$ownerdomain,$ownerhome).
13086: 
13087: Otherwise return the null string.
13088: 
13089: If second argument 'setpriv' is true, it assigns the privileges,
13090: and returns the same three element list, unless the owner has
13091: blocked "ad hoc" Domain Coordinator access to the Author Space,
13092: in which case the null string is returned.
13093: 
13094: =item *
13095: 
13096: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13097: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13098: and course level
13099: 
13100: =item *
13101: 
13102: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
13103: (rolesplain.tab); plain text explanation of a user role term.
13104: $type is Course (default) or Community.
13105: If $forcedefault evaluates to true, text returned will be default 
13106: text for $type. Otherwise, if this is a course, the text returned 
13107: will be a custom name for the role (if defined in the course's 
13108: environment).  If no custom name is defined the default is returned.
13109:    
13110: =item *
13111: 
13112: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
13113: All arguments are optional. Returns a hash of a roles, either for
13114: co-author/assistant author roles for a user's Construction Space
13115: (default), or if $context is 'userroles', roles for the user himself,
13116: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13117: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13118: For each key, value is set to colon-separated start and end times for
13119: the role.  If no username and domain are specified, will default to
13120: current user/domain. Types, roles, and roledoms are references to arrays
13121: of role statuses (active, future or previous), roles 
13122: (e.g., cc,in, st etc.) and domains of the roles which can be used
13123: to restrict the list of roles reported. If no array ref is 
13124: provided for types, will default to return only active roles.
13125: 
13126: =item *
13127: 
13128: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13129: user: $uname:$udom has a role in the course: $cdom_$cnum. 
13130: 
13131: Additional optional arguments are: $type (if role checking is to be restricted 
13132: to certain user status types -- previous (expired roles), active (currently
13133: available roles) or future (roles available in the future), and
13134: $hideprivileged -- if true will not report course roles for users who
13135: have active Domain Coordinator role in course's domain or in additional
13136: domains (specified in 'Domains to check for privileged users' in course
13137: environment -- set via:  Course Settings -> Classlists and staff listing).
13138: 
13139: =item *
13140: 
13141: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13142: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13143: $possdomains and $possroles are optional array refs -- to domains to check and
13144: roles to check.  If $possdomains is not specified, a dump will be done of the
13145: users' roles.db to check for a dc or su role in any domain. This can be
13146: time consuming if &privileged is called repeatedly (e.g., when displaying a
13147: classlist), so in such cases, supplying a $possdomains array is preferred, as
13148: this then allows &privileged_by_domain() to be used, which caches the identity
13149: of privileged users, eliminating the need for repeated calls to &dump().
13150: 
13151: =item *
13152: 
13153: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13154: where the outer hash keys are domains specified in the $possdomains array ref,
13155: next inner hash keys are privileged roles specified in the $roles array ref,
13156: and the innermost hash contains key = value pairs for username:domain = end:start
13157: for active or future "privileged" users with that role in that domain. To avoid
13158: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13159: innerhash are cached using priv_$role and $dom as the identifiers.
13160: 
13161: =back
13162: 
13163: =head2 User Modification
13164: 
13165: =over 4
13166: 
13167: =item *
13168: 
13169: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13170: user for the level given by URL.  Optional start and end dates (leave empty
13171: string or zero for "no date")
13172: 
13173: =item *
13174: 
13175: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13176: change a users, password, possible return values are: ok,
13177: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13178: refused
13179: 
13180: =item *
13181: 
13182: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13183: 
13184: =item *
13185: 
13186: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13187:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13188: 
13189: will update user information (firstname,middlename,lastname,generation,
13190: permanentemail), and if forceid is true, student/employee ID also.
13191: A user's institutional affiliation(s) can also be updated.
13192: User information fields will not be overwritten with empty entries 
13193: unless the field is included in the $candelete array reference.
13194: This array is included when a single user is modified via "Manage Users",
13195: or when Autoupdate.pl is run by cron in a domain.
13196: 
13197: =item *
13198: 
13199: modifystudent
13200: 
13201: modify a student's enrollment and identification information.
13202: The course id is resolved based on the current user's environment.  
13203: This means the invoking user must be a course coordinator or otherwise
13204: associated with a course.
13205: 
13206: This call is essentially a wrapper for lonnet::modifyuser and
13207: lonnet::modify_student_enrollment
13208: 
13209: Inputs: 
13210: 
13211: =over 4
13212: 
13213: =item B<$udom> Student's loncapa domain
13214: 
13215: =item B<$uname> Student's loncapa login name
13216: 
13217: =item B<$uid> Student/Employee ID
13218: 
13219: =item B<$umode> Student's authentication mode
13220: 
13221: =item B<$upass> Student's password
13222: 
13223: =item B<$first> Student's first name
13224: 
13225: =item B<$middle> Student's middle name
13226: 
13227: =item B<$last> Student's last name
13228: 
13229: =item B<$gene> Student's generation
13230: 
13231: =item B<$usec> Student's section in course
13232: 
13233: =item B<$end> Unix time of the roles expiration
13234: 
13235: =item B<$start> Unix time of the roles start date
13236: 
13237: =item B<$forceid> If defined, allow $uid to be changed
13238: 
13239: =item B<$desiredhome> server to use as home server for student
13240: 
13241: =item B<$email> Student's permanent e-mail address
13242: 
13243: =item B<$type> Type of enrollment (auto or manual)
13244: 
13245: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13246: 
13247: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13248: 
13249: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13250: 
13251: =item B<$context> role change context (shown in User Management Logs display in a course)
13252: 
13253: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13254: 
13255: =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.
13256: 
13257: =back
13258: 
13259: =item *
13260: 
13261: modify_student_enrollment
13262: 
13263: Change a student's enrollment status in a class.  The environment variable
13264: 'role.request.course' must be defined for this function to proceed.
13265: 
13266: Inputs:
13267: 
13268: =over 4
13269: 
13270: =item $udom, student's domain
13271: 
13272: =item $uname, student's name
13273: 
13274: =item $uid, student's user id
13275: 
13276: =item $first, student's first name
13277: 
13278: =item $middle
13279: 
13280: =item $last
13281: 
13282: =item $gene
13283: 
13284: =item $usec
13285: 
13286: =item $end
13287: 
13288: =item $start
13289: 
13290: =item $type
13291: 
13292: =item $locktype
13293: 
13294: =item $cid
13295: 
13296: =item $selfenroll
13297: 
13298: =item $context
13299: 
13300: =item $credits, number of credits student will earn from this class
13301: 
13302: =back
13303: 
13304: 
13305: =item *
13306: 
13307: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13308: custom role; give a custom role to a user for the level given by URL.  Specify
13309: name and domain of role author, and role name
13310: 
13311: =item *
13312: 
13313: revokerole($udom,$uname,$url,$role) : revoke a role for url
13314: 
13315: =item *
13316: 
13317: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13318: 
13319: =back
13320: 
13321: =head2 Course Infomation
13322: 
13323: =over 4
13324: 
13325: =item *
13326: 
13327: coursedescription($courseid,$options) : returns a hash of information about the
13328: specified course id, including all environment settings for the
13329: course, the description of the course will be in the hash under the
13330: key 'description'
13331: 
13332: $options is an optional parameter that if supplied is a hash reference that controls
13333: what how this function works.  It has the following key/values:
13334: 
13335: =over 4
13336: 
13337: =item freshen_cache
13338: 
13339: If defined, and the environment cache for the course is valid, it is 
13340: returned in the returned hash.
13341: 
13342: =item one_time
13343: 
13344: If defined, the last cache time is set to _now_
13345: 
13346: =item user
13347: 
13348: If defined, the supplied username is used instead of the current user.
13349: 
13350: 
13351: =back
13352: 
13353: =item *
13354: 
13355: resdata($name,$domain,$type,@which) : request for current parameter
13356: setting for a specific $type, where $type is either 'course' or 'user',
13357: @what should be a list of parameters to ask about. This routine caches
13358: answers for 10 minutes.
13359: 
13360: =item *
13361: 
13362: get_courseresdata($courseid, $domain) : dump the entire course resource
13363: data base, returning a hash that is keyed by the resource name and has
13364: values that are the resource value.  I believe that the timestamps and
13365: versions are also returned.
13366: 
13367: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13368: supplemental content area. This routine caches the number of files for 
13369: 10 minutes.
13370: 
13371: =back
13372: 
13373: =head2 Course Modification
13374: 
13375: =over 4
13376: 
13377: =item *
13378: 
13379: writecoursepref($courseid,%prefs) : write preferences (environment
13380: database) for a course
13381: 
13382: =item *
13383: 
13384: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13385: 
13386: =item *
13387: 
13388: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13389: 
13390: =item *
13391: 
13392: is_course($courseid), is_course($cdom, $cnum)
13393: 
13394: Accepts either a combined $courseid (in the form of domain_courseid) or the
13395: two component version $cdom, $cnum. It checks if the specified course exists.
13396: 
13397: Returns:
13398:     undef if the course doesn't exist, otherwise
13399:     in scalar context the combined courseid.
13400:     in list context the two components of the course identifier, domain and 
13401:     courseid.    
13402: 
13403: =back
13404: 
13405: =head2 Resource Subroutines
13406: 
13407: =over 4
13408: 
13409: =item *
13410: 
13411: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13412: 
13413: =item *
13414: 
13415: repcopy($filename) : subscribes to the requested file, and attempts to
13416: replicate from the owning library server, Might return
13417: 'unavailable', 'not_found', 'forbidden', 'ok', or
13418: 'bad_request', also attempts to grab the metadata for the
13419: resource. Expects the local filesystem pathname
13420: (/home/httpd/html/res/....)
13421: 
13422: =back
13423: 
13424: =head2 Resource Information
13425: 
13426: =over 4
13427: 
13428: =item *
13429: 
13430: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13431: and returns the value of a variety of different possible values,
13432: $varname should be a request string, and the other parameters can be
13433: used to specify who and what one is asking about. Ordinarily, $cid 
13434: does not need to be specified, as it is retrived from 
13435: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13436: within lonuserstate::loadmap() when initializing a course, before
13437: $env{'request.course.id'} has been set, so it needs to be provided
13438: in that one case.
13439: 
13440: Possible values for $varname are environment.lastname (or other item
13441: from the envirnment hash), user.name (or someother aspect about the
13442: user), resource.0.maxtries (or some other part and parameter of a
13443: resource)
13444: 
13445: =item *
13446: 
13447: directcondval($number) : get current value of a condition; reads from a state
13448: string
13449: 
13450: =item *
13451: 
13452: condval($condidx) : value of condition index based on state
13453: 
13454: =item *
13455: 
13456: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13457: resource's metadata, $what should be either a specific key, or either
13458: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13459: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13460: 
13461: this function automatically caches all requests
13462: 
13463: =item *
13464: 
13465: metadata_query($query,$custom,$customshow) : make a metadata query against the
13466: network of library servers; returns file handle of where SQL and regex results
13467: will be stored for query
13468: 
13469: =item *
13470: 
13471: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
13472: return symbolic list entry (all arguments optional). 
13473: 
13474: Args: filename is the filename (including path) for the file for which a symb 
13475: is required; donotrecurse, if true will prevent calls to allowed() being made 
13476: to check access status if more than one resource was found in the bighash 
13477: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
13478: a randompick); ignorecachednull, if true will prevent a symb of '' being 
13479: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13480: cause possible symbs to be checked to determine if they are subject to content
13481: blocking, if so they will not be included as possible symbs; possibles is a
13482: ref to a hash, which, as a side effect, will be populated with all possible 
13483: symbs (content blocking not tested).
13484:  
13485: returns the data handle
13486: 
13487: =item *
13488: 
13489: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13490: and is a possible symb for the URL in $thisfn, and if is an encrypted
13491: resource that the user accessed using /enc/ returns a 1 on success, 0
13492: on failure, user must be in a course, as it assumes the existence of
13493: the course initial hash, and uses $env('request.course.id'}.  The third
13494: arg is an optional reference to a scalar.  If this arg is passed in the 
13495: call to symbverify, it will be set to 1 if the symb has been set to be 
13496: encrypted; otherwise it will be null.  
13497: 
13498: =item *
13499: 
13500: symbclean($symb) : removes versions numbers from a symb, returns the
13501: cleaned symb
13502: 
13503: =item *
13504: 
13505: is_on_map($uri) : checks if the $uri is somewhere on the current
13506: course map, user must be in a course for it to work.
13507: 
13508: =item *
13509: 
13510: numval($salt) : return random seed value (addend for rndseed)
13511: 
13512: =item *
13513: 
13514: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13515: a random seed, all arguments are optional, if they aren't sent it uses the
13516: environment to derive them. Note: if symb isn't sent and it can't get one
13517: from &symbread it will use the current time as its return value
13518: 
13519: =item *
13520: 
13521: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13522: unfakeable, receipt
13523: 
13524: =item *
13525: 
13526: receipt() : API to ireceipt working off of env values; given out to users
13527: 
13528: =item *
13529: 
13530: countacc($url) : count the number of accesses to a given URL
13531: 
13532: =item *
13533: 
13534: 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
13535: 
13536: =item *
13537: 
13538: 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)
13539: 
13540: =item *
13541: 
13542: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13543: 
13544: =item *
13545: 
13546: devalidate($symb) : devalidate temporary spreadsheet calculations,
13547: forcing spreadsheet to reevaluate the resource scores next time.
13548: 
13549: =item * 
13550: 
13551: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13552: when viewing in course context.
13553: 
13554:  input: six args -- filename (decluttered), course number, course domain,
13555:                     url, symb (if registered) and group (if this is a 
13556:                     group item -- e.g., bulletin board, group page etc.).
13557: 
13558:  output: array of five scalars --
13559:          $cfile -- url for file editing if editable on current server
13560:          $home -- homeserver of resource (i.e., for author if published,
13561:                                           or course if uploaded.).
13562:          $switchserver --  1 if server switch will be needed.
13563:          $forceedit -- 1 if icon/link should be to go to edit mode 
13564:          $forceview -- 1 if icon/link should be to go to view mode
13565: 
13566: =item *
13567: 
13568: is_course_upload($file,$cnum,$cdom)
13569: 
13570: Used in course context to determine if current file was uploaded to 
13571: the course (i.e., would be found in /userfiles/docs on the course's 
13572: homeserver.
13573: 
13574:   input: 3 args -- filename (decluttered), course number and course domain.
13575:   output: boolean -- 1 if file was uploaded.
13576: 
13577: =back
13578: 
13579: =head2 Storing/Retreiving Data
13580: 
13581: =over 4
13582: 
13583: =item *
13584: 
13585: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13586: permanently for this url; hashref needs to be given and should be a \%hashname;
13587: the remaining args aren't required and if they aren't passed or are '' they will
13588: be derived from the env (with the exception of $laststore, which is an 
13589: optional arg used when a user's submission is stored in grading).
13590: $laststore is $version=$timestamp, where $version is the most recent version
13591: number retrieved for the corresponding $symb in the $namespace db file, and
13592: $timestamp is the timestamp for that transaction (UNIX time).
13593: $laststore is currently only passed when cstore() is called by 
13594: structuretags::finalize_storage().
13595: 
13596: =item *
13597: 
13598: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13599: but uses critical subroutine
13600: 
13601: =item *
13602: 
13603: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13604: all args are optional
13605: 
13606: =item *
13607: 
13608: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13609: dumps the complete (or key matching regexp) namespace into a hash
13610: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13611: normally &store()ed into
13612: 
13613: $range should be either an integer '100' (give me the first 100
13614:                                            matching records)
13615:               or be  two integers sperated by a - with no spaces
13616:                  '30-50' (give me the 30th through the 50th matching
13617:                           records)
13618: 
13619: 
13620: =item *
13621: 
13622: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13623: replaces a &store() version of data with a replacement set of data
13624: for a particular resource in a namespace passed in the $storehash hash 
13625: reference. If $tolog is true, the transaction is logged in the courselog
13626: with an action=PUTSTORE.
13627: 
13628: =item *
13629: 
13630: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13631: works very similar to store/cstore, but all data is stored in a
13632: temporary location and can be reset using tmpreset, $storehash should
13633: be a hash reference, returns nothing on success
13634: 
13635: =item *
13636: 
13637: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13638: similar to restore, but all data is stored in a temporary location and
13639: can be reset using tmpreset. Returns a hash of values on success,
13640: error string otherwise.
13641: 
13642: =item *
13643: 
13644: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13645: deltes all keys for $symb form the temporary storage hash.
13646: 
13647: =item *
13648: 
13649: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13650: reference filled in from namesp ($udom and $uname are optional)
13651: 
13652: =item *
13653: 
13654: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13655: namesp ($udom and $uname are optional)
13656: 
13657: =item *
13658: 
13659: dump($namespace,$udom,$uname,$regexp,$range) : 
13660: dumps the complete (or key matching regexp) namespace into a hash
13661: ($udom, $uname, $regexp, $range are optional)
13662: 
13663: $range should be either an integer '100' (give me the first 100
13664:                                            matching records)
13665:               or be  two integers sperated by a - with no spaces
13666:                  '30-50' (give me the 30th through the 50th matching
13667:                           records)
13668: =item *
13669: 
13670: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13671: $store can be a scalar, an array reference, or if the amount to be 
13672: incremented is > 1, a hash reference.
13673: 
13674: ($udom and $uname are optional)
13675: 
13676: =item *
13677: 
13678: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13679: ($udom and $uname are optional)
13680: 
13681: =item *
13682: 
13683: cput($namespace,$storehash,$udom,$uname) : critical put
13684: ($udom and $uname are optional)
13685: 
13686: =item *
13687: 
13688: newput($namespace,$storehash,$udom,$uname) :
13689: 
13690: Attempts to store the items in the $storehash, but only if they don't
13691: currently exist, if this succeeds you can be certain that you have 
13692: successfully created a new key value pair in the $namespace db.
13693: 
13694: 
13695: Args:
13696:  $namespace: name of database to store values to
13697:  $storehash: hashref to store to the db
13698:  $udom: (optional) domain of user containing the db
13699:  $uname: (optional) name of user caontaining the db
13700: 
13701: Returns:
13702:  'ok' -> succeeded in storing all keys of $storehash
13703:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13704:                         least <key> already existed in the db (other
13705:                         requested keys may also already exist)
13706:  'error: <msg>' -> unable to tie the DB or other error occurred
13707:  'con_lost' -> unable to contact request server
13708:  'refused' -> action was not allowed by remote machine
13709: 
13710: 
13711: =item *
13712: 
13713: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13714: reference filled in from namesp (encrypts the return communication)
13715: ($udom and $uname are optional)
13716: 
13717: =item *
13718: 
13719: log($udom,$name,$home,$message) : write to permanent log for user; use
13720: critical subroutine
13721: 
13722: =item *
13723: 
13724: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13725: array reference filled in from namespace found in domain level on either
13726: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13727: 
13728: =item *
13729: 
13730: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13731: domain level either on specified domain server ($uhome) or primary domain 
13732: server ($udom and $uhome are optional)
13733: 
13734: =item * 
13735: 
13736: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13737: for: authentication, language, quotas, timezone, date locale, and portal URL in
13738: the target domain.
13739: 
13740: May also include additional key => value pairs for the following groups:
13741: 
13742: =over
13743: 
13744: =item
13745: disk quotas (MB allocated by default to portfolios and authoring spaces).
13746: 
13747: =over
13748: 
13749: =item defaultquota, authorquota
13750: 
13751: =back
13752: 
13753: =item
13754: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13755: portfolio for users).
13756: 
13757: =over
13758: 
13759: =item
13760: aboutme, blog, webdav, portfolio
13761: 
13762: =back
13763: 
13764: =item
13765: requestcourses: ability to request courses, and how requests are processed.
13766: 
13767: =over
13768: 
13769: =item
13770: official, unofficial, community, textbook
13771: 
13772: =back
13773: 
13774: =item
13775: inststatus: types of institutional affiliation, and order in which they are displayed.
13776: 
13777: =over
13778: 
13779: =item
13780: inststatustypes, inststatusorder, inststatusguest
13781: 
13782: =back
13783: 
13784: =item
13785: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13786: for course's uploaded content.
13787: 
13788: =over
13789: 
13790: =item
13791: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13792: communityquota, textbookquota
13793: 
13794: =back
13795: 
13796: =item
13797: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13798: on your servers.
13799: 
13800: =over
13801: 
13802: =item 
13803: remotesessions, hostedsessions
13804: 
13805: =back
13806: 
13807: =back
13808: 
13809: In cases where a domain coordinator has never used the "Set Domain Configuration"
13810: utility to create a configuration.db file on a domain's primary library server 
13811: only the following domain defaults: auth_def, auth_arg_def, lang_def
13812: -- corresponding values are authentication type (internal, krb4, krb5,
13813: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13814: will be available. Values are retrieved from cache (if current), unless the
13815: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13816: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13817: 
13818: Typical usage:
13819: 
13820: %domdefaults = &get_domain_defaults($target_domain);
13821: 
13822: =back
13823: 
13824: =head2 Network Status Functions
13825: 
13826: =over 4
13827: 
13828: =item *
13829: 
13830: dirlist() : return directory list based on URI (first arg).
13831: 
13832: Inputs: 1 required, 5 optional.
13833: 
13834: =over
13835: 
13836: =item 
13837: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13838: 
13839: =item
13840: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13841: 
13842: =item
13843: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13844: 
13845: =item
13846: $getpropath - boolean: 1 if prepend path using &propath(). 
13847: 
13848: =item
13849: $getuserdir - boolean: 1 if prepend path for "userfiles".
13850: 
13851: =item 
13852: $alternateRoot - path to prepend in place of path from $uri.
13853: 
13854: =back
13855: 
13856: Returns: Array of up to two items.
13857: 
13858: =over
13859: 
13860: a reference to an array of files/subdirectories
13861: 
13862: =over
13863: 
13864: Each element in the array of files/subdirectories is a & separated list of
13865: item name and the result of running stat on the item.  If dirlist was requested
13866: for a file instead of a directory, the item name will be ''. For a directory 
13867: listing, if the item is a metadata file, the element will end &N&M 
13868: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13869: default copyright set (1).  
13870: 
13871: =back
13872: 
13873: a scalar containing error condition (if encountered).
13874: 
13875: =over
13876: 
13877: =item 
13878: no_host (no homeserver identified for $username:$domain).
13879: 
13880: =item 
13881: no_such_host (server contacted for listing not identified as valid host).
13882: 
13883: =item 
13884: con_lost (connection to remote server failed).
13885: 
13886: =item 
13887: refused (invalid $username:$domain received on lond side).
13888: 
13889: =item 
13890: no_such_dir (directory at specified path on lond side does not exist). 
13891: 
13892: =item 
13893: empty (directory at specified path on lond side is empty).
13894: 
13895: =over
13896: 
13897: This is currently not encountered because the &ls3, &ls2, 
13898: &ls (_handler) routines on the lond side do not filter out
13899: . and .. from a directory listing. 
13900: 
13901: =back
13902: 
13903: =back
13904: 
13905: =back
13906: 
13907: =item *
13908: 
13909: spareserver() : find server with least workload from spare.tab
13910: 
13911: 
13912: =item *
13913: 
13914: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13915: if there is no corresponding loncapa host.
13916: 
13917: =back
13918: 
13919: 
13920: =head2 Apache Request
13921: 
13922: =over 4
13923: 
13924: =item *
13925: 
13926: ssi($url,%hash) : server side include, does a complete request cycle on url to
13927: localhost, posts hash
13928: 
13929: =back
13930: 
13931: =head2 Data to String to Data
13932: 
13933: =over 4
13934: 
13935: =item *
13936: 
13937: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13938: and '&' separators, supports elements that are arrayrefs and hashrefs
13939: 
13940: =item *
13941: 
13942: hashref2str($hashref) : convert a hashref into a string complete with
13943: escaping and '=' and '&' separators, supports elements that are
13944: arrayrefs and hashrefs
13945: 
13946: =item *
13947: 
13948: arrayref2str($arrayref) : convert an arrayref into a string complete
13949: with escaping and '&' separators, supports elements that are arrayrefs
13950: and hashrefs
13951: 
13952: =item *
13953: 
13954: str2hash($string) : convert string to hash using unescaping and
13955: splitting on '=' and '&', supports elements that are arrayrefs and
13956: hashrefs
13957: 
13958: =item *
13959: 
13960: str2array($string) : convert string to hash using unescaping and
13961: splitting on '&', supports elements that are arrayrefs and hashrefs
13962: 
13963: =back
13964: 
13965: =head2 Logging Routines
13966: 
13967: 
13968: These routines allow one to make log messages in the lonnet.log and
13969: lonnet.perm logfiles.
13970: 
13971: =over 4
13972: 
13973: =item *
13974: 
13975: logtouch() : make sure the logfile, lonnet.log, exists
13976: 
13977: =item *
13978: 
13979: logthis() : append message to the normal lonnet.log file, it gets
13980: preiodically rolled over and deleted.
13981: 
13982: =item *
13983: 
13984: logperm() : append a permanent message to lonnet.perm.log, this log
13985: file never gets deleted by any automated portion of the system, only
13986: messages of critical importance should go in here.
13987: 
13988: 
13989: =back
13990: 
13991: =head2 General File Helper Routines
13992: 
13993: =over 4
13994: 
13995: =item *
13996: 
13997: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13998: (a) files in /uploaded
13999:   (i) If a local copy of the file exists - 
14000:       compares modification date of local copy with last-modified date for 
14001:       definitive version stored on home server for course. If local copy is 
14002:       stale, requests a new version from the home server and stores it. 
14003:       If the original has been removed from the home server, then local copy 
14004:       is unlinked.
14005:   (ii) If local copy does not exist -
14006:       requests the file from the home server and stores it. 
14007:   
14008:   If $caller is 'uploadrep':  
14009:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14010:     for request for files originally uploaded via DOCS. 
14011:      - returns 'ok' if fresh local copy now available, -1 otherwise.
14012:   
14013:   Otherwise:
14014:      This indicates a call from the content generation phase of the request.
14015:      -  returns the entire contents of the file or -1.
14016:      
14017: (b) files in /res
14018:    - returns the entire contents of a file or -1; 
14019:    it properly subscribes to and replicates the file if neccessary.
14020: 
14021: 
14022: =item *
14023: 
14024: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14025:                   reference
14026: 
14027: returns either a stat() list of data about the file or an empty list
14028: if the file doesn't exist or couldn't find out about it (connection
14029: problems or user unknown)
14030: 
14031: =item *
14032: 
14033: filelocation($dir,$file) : returns file system location of a file
14034: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14035: directory that relative $file lookups are to looked in ($dir of /a/dir
14036: and a file of ../bob will become /a/bob)
14037: 
14038: =item *
14039: 
14040: hreflocation($dir,$file) : returns file system location or a URL; same as
14041: filelocation except for hrefs
14042: 
14043: =item *
14044: 
14045: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14046: also removes beginning /home/httpd/html unless /priv/ follows it.
14047: 
14048: =back
14049: 
14050: =head2 Usererfile file routines (/uploaded*)
14051: 
14052: =over 4
14053: 
14054: =item *
14055: 
14056: userfileupload(): main rotine for putting a file in a user or course's
14057:                   filespace, arguments are,
14058: 
14059:  formname - required - this is the name of the element in $env where the
14060:            filename, and the contents of the file to create/modifed exist
14061:            the filename is in $env{'form.'.$formname.'.filename'} and the
14062:            contents of the file is located in $env{'form.'.$formname}
14063:  context - if coursedoc, store the file in the course of the active role
14064:              of the current user; 
14065:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14066:            if 'canceloverwrite': delete file in tmp/overwrites directory
14067:  subdir - required - subdirectory to put the file in under ../userfiles/
14068:          if undefined, it will be placed in "unknown"
14069: 
14070:  (This routine calls clean_filename() to remove any dangerous
14071:  characters from the filename, and then calls finuserfileupload() to
14072:  complete the transaction)
14073: 
14074:  returns either the url of the uploaded file (/uploaded/....) if successful
14075:  and /adm/notfound.html if unsuccessful
14076: 
14077: =item *
14078: 
14079: clean_filename(): routine for cleaing a filename up for storage in
14080:                  userfile space, argument is:
14081: 
14082:  filename - proposed filename
14083: 
14084: returns: the new clean filename
14085: 
14086: =item *
14087: 
14088: finishuserfileupload(): routine that creates and sends the file to
14089: userspace, probably shouldn't be called directly
14090: 
14091:   docuname: username or courseid of destination for the file
14092:   docudom: domain of user/course of destination for the file
14093:   formname: same as for userfileupload()
14094:   fname: filename (including subdirectories) for the file
14095:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14096:   allfiles: reference to hash used to store objects found by parser
14097:   codebase: reference to hash used for codebases of java objects found by parser
14098:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14099:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
14100:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
14101:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
14102:   context: if 'overwrite', will move the uploaded file from its temporary location to
14103:             userfiles to facilitate overwriting a previously uploaded file with same name.
14104:   mimetype: reference to scalar to accommodate mime type determined
14105:             from File::MMagic if $parser = parse.
14106: 
14107:  returns either the url of the uploaded file (/uploaded/....) if successful
14108:  and /adm/notfound.html if unsuccessful (or an error message if context 
14109:  was 'overwrite').
14110:  
14111: 
14112: =item *
14113: 
14114: renameuserfile(): renames an existing userfile to a new name
14115: 
14116:   Args:
14117:    docuname: username or courseid of destination for the file
14118:    docudom: domain of user/course of destination for the file
14119:    old: current file name (including any subdirs under userfiles)
14120:    new: desired file name (including any subdirs under userfiles)
14121: 
14122: =item *
14123: 
14124: mkdiruserfile(): creates a directory is a userfiles dir
14125: 
14126:   Args:
14127:    docuname: username or courseid of destination for the file
14128:    docudom: domain of user/course of destination for the file
14129:    dir: dir to create (including any subdirs under userfiles)
14130: 
14131: =item *
14132: 
14133: removeuserfile(): removes a file that exists in userfiles
14134: 
14135:   Args:
14136:    docuname: username or courseid of destination for the file
14137:    docudom: domain of user/course of destination for the file
14138:    fname: filname to delete (including any subdirs under userfiles)
14139: 
14140: =item *
14141: 
14142: removeuploadedurl(): convience function for removeuserfile()
14143: 
14144:   Args:
14145:    url:  a full /uploaded/... url to delete
14146: 
14147: =item * 
14148: 
14149: get_portfile_permissions():
14150:   Args:
14151:     domain: domain of user or course contain the portfolio files
14152:     user: name of user or num of course contain the portfolio files
14153:   Returns:
14154:     hashref of a dump of the proper file_permissions.db
14155:    
14156: 
14157: =item * 
14158: 
14159: get_access_controls():
14160: 
14161: Args:
14162:   current_permissions: the hash ref returned from get_portfile_permissions()
14163:   group: (optional) the group you want the files associated with
14164:   file: (optional) the file you want access info on
14165: 
14166: Returns:
14167:     a hash (keys are file names) of hashes containing
14168:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14169:         values are XML containing access control settings (see below) 
14170: 
14171: Internal notes:
14172: 
14173:  access controls are stored in file_permissions.db as key=value pairs.
14174:     key -> path to file/file_name\0uniqueID:scope_end_start
14175:         where scope -> public,guest,course,group,domains or users.
14176:               end -> UNIX time for end of access (0 -> no end date)
14177:               start -> UNIX time for start of access
14178: 
14179:     value -> XML description of access control
14180:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14181:             <start></start>
14182:             <end></end>
14183: 
14184:             <password></password>  for scope type = guest
14185: 
14186:             <domain></domain>     for scope type = course or group
14187:             <number></number>
14188:             <roles id="">
14189:              <role></role>
14190:              <access></access>
14191:              <section></section>
14192:              <group></group>
14193:             </roles>
14194: 
14195:             <dom></dom>         for scope type = domains
14196: 
14197:             <users>             for scope type = users
14198:              <user>
14199:               <uname></uname>
14200:               <udom></udom>
14201:              </user>
14202:             </users>
14203:            </scope> 
14204:               
14205:  Access data is also aggregated for each file in an additional key=value pair:
14206:  key -> path to file/file_name\0accesscontrol 
14207:  value -> reference to hash
14208:           hash contains key = value pairs
14209:           where key = uniqueID:scope_end_start
14210:                 value = UNIX time record was last updated
14211: 
14212:           Used to improve speed of look-ups of access controls for each file.  
14213:  
14214:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14215: 
14216: =item *
14217: 
14218: modify_access_controls():
14219: 
14220: Modifies access controls for a portfolio file
14221: Args
14222: 1. file name
14223: 2. reference to hash of required changes,
14224: 3. domain
14225: 4. username
14226:   where domain,username are the domain of the portfolio owner 
14227:   (either a user or a course) 
14228: 
14229: Returns:
14230: 1. result of additions or updates ('ok' or 'error', with error message). 
14231: 2. result of deletions ('ok' or 'error', with error message).
14232: 3. reference to hash of any new or updated access controls.
14233: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14234:    key = integer (inbound ID)
14235:    value = uniqueID
14236: 
14237: =item *
14238: 
14239: get_timebased_id():
14240: 
14241: Attempts to get a unique timestamp-based suffix for use with items added to a 
14242: course via the Course Editor (e.g., folders, composite pages, 
14243: group bulletin boards).
14244: 
14245: Args: (first three required; six others optional)
14246: 
14247: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14248:    docssequence, or name of group
14249: 
14250: 2. keyid (alphanumeric): name of temporary locking key in hash,
14251:    e.g., num, boardids
14252: 
14253: 3. namespace: name of gdbm file used to store suffixes already assigned;  
14254:    file will be named nohist_namespace.db
14255: 
14256: 4. cdom: domain of course; default is current course domain from %env
14257: 
14258: 5. cnum: course number; default is current course number from %env
14259: 
14260: 6. idtype: set to concat if an additional digit is to be appended to the 
14261:    unix timestamp to form the suffix, if the plain timestamp is already
14262:    in use.  Default is to not do this, but simply increment the unix 
14263:    timestamp by 1 until a unique key is obtained.
14264: 
14265: 7. who: holder of locking key; defaults to user:domain for user.
14266: 
14267: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
14268:    retrying); default is 3.
14269: 
14270: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
14271: 
14272: Returns:
14273: 
14274: 1. suffix obtained (numeric)
14275: 
14276: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14277: 
14278: 3. error: contains (localized) error message if an error occurred.
14279: 
14280: 
14281: =back
14282: 
14283: =head2 HTTP Helper Routines
14284: 
14285: =over 4
14286: 
14287: =item *
14288: 
14289: escape() : unpack non-word characters into CGI-compatible hex codes
14290: 
14291: =item *
14292: 
14293: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14294: 
14295: =back
14296: 
14297: =head1 PRIVATE SUBROUTINES
14298: 
14299: =head2 Underlying communication routines (Shouldn't call)
14300: 
14301: =over 4
14302: 
14303: =item *
14304: 
14305: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14306: 
14307: =item *
14308: 
14309: reply() : uses subreply to send a message to remote machine, logs all failures
14310: 
14311: =item *
14312: 
14313: critical() : passes a critical message to another server; if cannot
14314: get through then place message in connection buffer directory and
14315: returns con_delayed, if incapable of saving message, returns
14316: con_failed
14317: 
14318: =item *
14319: 
14320: reconlonc() : tries to reconnect lonc client processes.
14321: 
14322: =back
14323: 
14324: =head2 Resource Access Logging
14325: 
14326: =over 4
14327: 
14328: =item *
14329: 
14330: flushcourselogs() : flush (save) buffer logs and access logs
14331: 
14332: =item *
14333: 
14334: courselog($what) : save message for course in hash
14335: 
14336: =item *
14337: 
14338: courseacclog($what) : save message for course using &courselog().  Perform
14339: special processing for specific resource types (problems, exams, quizzes, etc).
14340: 
14341: =item *
14342: 
14343: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14344: as a PerlChildExitHandler
14345: 
14346: =back
14347: 
14348: =head2 Other
14349: 
14350: =over 4
14351: 
14352: =item *
14353: 
14354: symblist($mapname,%newhash) : update symbolic storage links
14355: 
14356: =back
14357: 
14358: =cut
14359: 

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