File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1355: download - view: text, annotated - select for diffs
Mon Sep 25 00:36:35 2017 UTC (6 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- When browser sends a LON-CAPA cookie for an expired session, redirect user
  to portal URL for user's domain for re-authentication.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1355 2017/09/25 00:36:35 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 HTTP::Date;
   75: use Image::Magick;
   76: 
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$context) = @_;
  234:     my ($rep,$uselocal);
  235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
  236:         $uselocal = 1;
  237:     }
  238:     if (($context ne 'cgi') && ($uselocal)) {
  239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  240:         if ($distro eq '') {
  241:             $uselocal = 0;
  242:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  243:             if ($1 < 6) {
  244:                 $uselocal = 0;
  245:             }
  246:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  247:             if ($1 < 12) {
  248:                 $uselocal = 0;
  249:             }
  250:         }
  251:     }
  252:     if ($uselocal) {
  253:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
  254:     } else {
  255:         $rep=&reply('servercerts',$lonhost);
  256:     }
  257:     my ($result,%returnhash);
  258:     if (defined($lonhost)) {
  259:         if (!defined(&hostname($lonhost))) {
  260:             return;
  261:         }
  262:     }
  263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  264:         ($rep eq 'unknown_cmd')) {
  265:         $result = $rep;
  266:     } else {
  267:         $result = 'ok';
  268:         my @pairs=split(/\&/,$rep);
  269:         foreach my $item (@pairs) {
  270:             my ($key,$value)=split(/=/,$item,2);
  271:             my $what = &unescape($key);
  272:             $returnhash{$what}=&thaw_unescape($value);
  273:         }
  274:     }
  275:     return ($result,\%returnhash);
  276: }
  277: 
  278: sub get_server_loncaparev {
  279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  280:     if (defined($lonhost)) {
  281:         if (!defined(&hostname($lonhost))) {
  282:             undef($lonhost);
  283:         }
  284:     }
  285:     if (!defined($lonhost)) {
  286:         if (defined(&domain($dom,'primary'))) {
  287:             $lonhost=&domain($dom,'primary');
  288:             if ($lonhost eq 'no_host') {
  289:                 undef($lonhost);
  290:             }
  291:         }
  292:     }
  293:     if (defined($lonhost)) {
  294:         my $cachetime = 12*3600;
  295:         if (!$ignore_cache) {
  296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  297:             if (defined($cached)) {
  298:                 return $loncaparev;
  299:             }
  300:         }
  301:         my ($answer,$loncaparev);
  302:         my @ids=&current_machine_ids();
  303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  304:             $answer = $perlvar{'lonVersion'};
  305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  306:                 $loncaparev = $1;
  307:             }
  308:         } else {
  309:             $answer = &reply('serverloncaparev',$lonhost);
  310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  311:                 if ($caller eq 'loncron') {
  312:                     my $protocol = $protocol{$lonhost};
  313:                     $protocol = 'http' if ($protocol ne 'https');
  314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  315:                     my $request=new HTTP::Request('GET',$url);
  316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  317:                     unless ($response->is_error()) {
  318:                         my $content = $response->content;
  319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  320:                             $loncaparev = $1;
  321:                         }
  322:                     }
  323:                 } else {
  324:                     $loncaparev = $loncaparevs{$lonhost};
  325:                 }
  326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  327:                 $loncaparev = $1;
  328:             }
  329:         }
  330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  331:     }
  332: }
  333: 
  334: sub get_server_homeID {
  335:     my ($hostname,$ignore_cache,$caller) = @_;
  336:     unless ($ignore_cache) {
  337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  338:         if (defined($cached)) {
  339:             return $serverhomeID;
  340:         }
  341:     }
  342:     my $cachetime = 12*3600;
  343:     my $serverhomeID;
  344:     if ($caller eq 'loncron') { 
  345:         my @machine_ids = &machine_ids($hostname);
  346:         foreach my $id (@machine_ids) {
  347:             my $response = &reply('serverhomeID',$id);
  348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  349:                 $serverhomeID = $response;
  350:                 last;
  351:             }
  352:         }
  353:         if ($serverhomeID eq '') {
  354:             $serverhomeID = $machine_ids[-1];
  355:         }
  356:     } else {
  357:         $serverhomeID = $serverhomeIDs{$hostname};
  358:     }
  359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  360: }
  361: 
  362: sub get_remote_globals {
  363:     my ($lonhost,$whathash,$ignore_cache) = @_;
  364:     my ($result,%returnhash,%whatneeded);
  365:     if (ref($whathash) eq 'HASH') {
  366:         foreach my $what (sort(keys(%{$whathash}))) {
  367:             my $hashid = $lonhost.'-'.$what;
  368:             my ($response,$cached);
  369:             unless ($ignore_cache) {
  370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  371:             }
  372:             if (defined($cached)) {
  373:                 $returnhash{$what} = $response;
  374:             } else {
  375:                 $whatneeded{$what} = 1;
  376:             }
  377:         }
  378:         if (keys(%whatneeded) == 0) {
  379:             $result = 'ok';
  380:         } else {
  381:             my $requested = &freeze_escape(\%whatneeded);
  382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  384:                 ($rep eq 'unknown_cmd')) {
  385:                 $result = $rep;
  386:             } else {
  387:                 $result = 'ok';
  388:                 my @pairs=split(/\&/,$rep);
  389:                 foreach my $item (@pairs) {
  390:                     my ($key,$value)=split(/=/,$item,2);
  391:                     my $what = &unescape($key);
  392:                     my $hashid = $lonhost.'-'.$what;
  393:                     $returnhash{$what}=&thaw_unescape($value);
  394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  395:                 }
  396:             }
  397:         }
  398:     }
  399:     return ($result,\%returnhash);
  400: }
  401: 
  402: sub remote_devalidate_cache {
  403:     my ($lonhost,$cachekeys) = @_;
  404:     my $items;
  405:     return unless (ref($cachekeys) eq 'ARRAY');
  406:     my $cachestr = join('&',@{$cachekeys});
  407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  408:     return $response;
  409: }
  410: 
  411: # -------------------------------------------------- Non-critical communication
  412: sub subreply {
  413:     my ($cmd,$server)=@_;
  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  415:     #
  416:     #  With loncnew process trimming, there's a timing hole between lonc server
  417:     #  process exit and the master server picking up the listen on the AF_UNIX
  418:     #  socket.  In that time interval, a lock file will exist:
  419: 
  420:     my $lockfile=$peerfile.".lock";
  421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  422: 	sleep(0.1);
  423:     }
  424:     # At this point, either a loncnew parent is listening or an old lonc
  425:     # or loncnew child is listening so we can connect or everything's dead.
  426:     #
  427:     #   We'll give the connection a few tries before abandoning it.  If
  428:     #   connection is not possible, we'll con_lost back to the client.
  429:     #   
  430:     my $client;
  431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  433: 				      Type    => SOCK_STREAM,
  434: 				      Timeout => 10);
  435: 	if ($client) {
  436: 	    last;		# Connected!
  437: 	} else {
  438: 	    &create_connection(&hostname($server),$server);
  439: 	}
  440:         sleep(0.1);	# Try again later if failed connection.
  441:     }
  442:     my $answer;
  443:     if ($client) {
  444: 	print $client "sethost:$server:$cmd\n";
  445: 	$answer=<$client>;
  446: 	if (!$answer) { $answer="con_lost"; }
  447: 	chomp($answer);
  448:     } else {
  449: 	$answer = 'con_lost';	# Failed connection.
  450:     }
  451:     return $answer;
  452: }
  453: 
  454: sub reply {
  455:     my ($cmd,$server)=@_;
  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  457:     my $answer=subreply($cmd,$server);
  458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  459:        &logthis("<font color=\"blue\">WARNING:".
  460:                 " $cmd to $server returned $answer</font>");
  461:     }
  462:     return $answer;
  463: }
  464: 
  465: # ----------------------------------------------------------- Send USR1 to lonc
  466: 
  467: sub reconlonc {
  468:     my ($lonid) = @_;
  469:     if ($lonid) {
  470:         my $hostname = &hostname($lonid);
  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  472: 	if ($hostname && -e $peerfile) {
  473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  475: 					     Type    => SOCK_STREAM,
  476: 					     Timeout => 10);
  477: 	    if ($client) {
  478: 		print $client ("reset_retries\n");
  479: 		my $answer=<$client>;
  480: 		#reset just this one.
  481: 	    }
  482: 	}
  483: 	return;
  484:     }
  485: 
  486:     &logthis("Trying to reconnect lonc");
  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  488:     if (open(my $fh,"<$loncfile")) {
  489: 	my $loncpid=<$fh>;
  490:         chomp($loncpid);
  491:         if (kill 0 => $loncpid) {
  492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  493:             kill USR1 => $loncpid;
  494:             sleep 1;
  495:         } else {
  496: 	    &logthis(
  497:                "<font color=\"blue\">WARNING:".
  498:                " lonc at pid $loncpid not responding, giving up</font>");
  499:         }
  500:     } else {
  501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  502:     }
  503: }
  504: 
  505: # ------------------------------------------------------ Critical communication
  506: 
  507: sub critical {
  508:     my ($cmd,$server)=@_;
  509:     unless (&hostname($server)) {
  510:         &logthis("<font color=\"blue\">WARNING:".
  511:                " Critical message to unknown server ($server)</font>");
  512:         return 'no_such_host';
  513:     }
  514:     my $answer=reply($cmd,$server);
  515:     if ($answer eq 'con_lost') {
  516: 	&reconlonc($server);
  517: 	my $answer=reply($cmd,$server);
  518:         if ($answer eq 'con_lost') {
  519:             my $now=time;
  520:             my $middlename=$cmd;
  521:             $middlename=substr($middlename,0,16);
  522:             $middlename=~s/\W//g;
  523:             my $dfilename=
  524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  525:             $dumpcount++;
  526:             {
  527: 		my $dfh;
  528: 		if (open($dfh,">$dfilename")) {
  529: 		    print $dfh "$cmd\n"; 
  530: 		    close($dfh);
  531: 		}
  532:             }
  533:             sleep 1;
  534:             my $wcmd='';
  535:             {
  536: 		my $dfh;
  537: 		if (open($dfh,"<$dfilename")) {
  538: 		    $wcmd=<$dfh>; 
  539: 		    close($dfh);
  540: 		}
  541:             }
  542:             chomp($wcmd);
  543:             if ($wcmd eq $cmd) {
  544: 		&logthis("<font color=\"blue\">WARNING: ".
  545:                          "Connection buffer $dfilename: $cmd</font>");
  546:                 &logperm("D:$server:$cmd");
  547: 	        return 'con_delayed';
  548:             } else {
  549:                 &logthis("<font color=\"red\">CRITICAL:"
  550:                         ." Critical connection failed: $server $cmd</font>");
  551:                 &logperm("F:$server:$cmd");
  552:                 return 'con_failed';
  553:             }
  554:         }
  555:     }
  556:     return $answer;
  557: }
  558: 
  559: # ------------------------------------------- check if return value is an error
  560: 
  561: sub error {
  562:     my ($result) = @_;
  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  564: 	if ($2 == 2) { return undef; }
  565: 	return $1;
  566:     }
  567:     return undef;
  568: }
  569: 
  570: sub convert_and_load_session_env {
  571:     my ($lonidsdir,$handle)=@_;
  572:     my @profile;
  573:     {
  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  575: 	if (!$opened) {
  576: 	    return 0;
  577: 	}
  578: 	flock($idf,LOCK_SH);
  579: 	@profile=<$idf>;
  580: 	close($idf);
  581:     }
  582:     my %temp_env;
  583:     foreach my $line (@profile) {
  584: 	if ($line !~ m/=/) {
  585: 	    return 0;
  586: 	}
  587: 	chomp($line);
  588: 	my ($envname,$envvalue)=split(/=/,$line,2);
  589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  590:     }
  591:     unlink("$lonidsdir/$handle.id");
  592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  593: 	    0640)) {
  594: 	%disk_env = %temp_env;
  595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  596: 	untie(%disk_env);
  597:     }
  598:     return 1;
  599: }
  600: 
  601: # ------------------------------------------- Transfer profile into environment
  602: my $env_loaded;
  603: sub transfer_profile_to_env {
  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
  605:     if (!$force_transfer && $env_loaded) { return; } 
  606: 
  607:     if (!defined($lonidsdir)) {
  608: 	$lonidsdir = $perlvar{'lonIDsDir'};
  609:     }
  610:     if (!defined($handle)) {
  611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  612:     }
  613: 
  614:     my $convert;
  615:     {
  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617: 	if (!$opened) {
  618: 	    return;
  619: 	}
  620: 	flock($idf,LOCK_SH);
  621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 		&GDBM_READER(),0640)) {
  623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  624: 	    untie(%disk_env);
  625: 	} else {
  626: 	    $convert = 1;
  627: 	}
  628:     }
  629:     if ($convert) {
  630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  631: 	    &logthis("Failed to load session, or convert session.");
  632: 	}
  633:     }
  634: 
  635:     my %remove;
  636:     while ( my $envname = each(%env) ) {
  637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  638:             if ($time < time-300) {
  639:                 $remove{$key}++;
  640:             }
  641:         }
  642:     }
  643: 
  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  645:     $env_loaded=1;
  646:     foreach my $expired_key (keys(%remove)) {
  647:         &delenv($expired_key);
  648:     }
  649: }
  650: 
  651: # ---------------------------------------------------- Check for valid session 
  652: sub check_for_valid_session {
  653:     my ($r,$name,$userhashref,$domref) = @_;
  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  655:     my ($linkname,$pubname);
  656:     if ($name eq '') {
  657:         $name = 'lonID';
  658:         $linkname = 'lonLinkID';
  659:         $pubname = 'lonPubID';
  660:     }
  661:     my $lonid=$cookies{$name};
  662:     if (!$lonid) {
  663:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
  664:             $lonid=$cookies{$linkname};
  665:         }
  666:         if (!$lonid) {
  667:             if (($name eq 'lonID') && ($pubname)) {
  668:                 $lonid=$cookies{$pubname};
  669:             }
  670:         }
  671:     }
  672:     return undef if (!$lonid);
  673: 
  674:     my $handle=&LONCAPA::clean_handle($lonid->value);
  675:     my $lonidsdir;
  676:     if ($name eq 'lonDAV') {
  677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  678:     } else {
  679:         $lonidsdir=$r->dir_config('lonIDsDir');
  680:     }
  681:     if (!-e "$lonidsdir/$handle.id") {
  682:         if ((ref($domref)) && ($name eq 'lonID') && 
  683:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  684:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  685:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  686:                 $$domref = $possudom;
  687:             }
  688:         }
  689:         return undef;
  690:     }
  691: 
  692:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  693:     return undef if (!$opened);
  694: 
  695:     flock($idf,LOCK_SH);
  696:     my %disk_env;
  697:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  698: 	    &GDBM_READER(),0640)) {
  699: 	return undef;	
  700:     }
  701: 
  702:     if (!defined($disk_env{'user.name'})
  703: 	|| !defined($disk_env{'user.domain'})) {
  704: 	return undef;
  705:     }
  706: 
  707:     if (ref($userhashref) eq 'HASH') {
  708:         $userhashref->{'name'} = $disk_env{'user.name'};
  709:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  710:     }
  711: 
  712:     return $handle;
  713: }
  714: 
  715: sub timed_flock {
  716:     my ($file,$lock_type) = @_;
  717:     my $failed=0;
  718:     eval {
  719: 	local $SIG{__DIE__}='DEFAULT';
  720: 	local $SIG{ALRM}=sub {
  721: 	    $failed=1;
  722: 	    die("failed lock");
  723: 	};
  724: 	alarm(13);
  725: 	flock($file,$lock_type);
  726: 	alarm(0);
  727:     };
  728:     if ($failed) {
  729: 	return undef;
  730:     } else {
  731: 	return 1;
  732:     }
  733: }
  734: 
  735: # ---------------------------------------------------------- Append Environment
  736: 
  737: sub appenv {
  738:     my ($newenv,$roles) = @_;
  739:     if (ref($newenv) eq 'HASH') {
  740:         foreach my $key (keys(%{$newenv})) {
  741:             my $refused = 0;
  742: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  743:                 $refused = 1;
  744:                 if (ref($roles) eq 'ARRAY') {
  745:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  746:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  747:                         $refused = 0;
  748:                     }
  749:                 }
  750:             }
  751:             if ($refused) {
  752:                 &logthis("<font color=\"blue\">WARNING: ".
  753:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  754:                          .'</font>');
  755: 	        delete($newenv->{$key});
  756:             } else {
  757:                 $env{$key}=$newenv->{$key};
  758:             }
  759:         }
  760:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  761:         if ($opened
  762: 	    && &timed_flock($env_file,LOCK_EX)
  763: 	    &&
  764: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  765: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  766: 	    while (my ($key,$value) = each(%{$newenv})) {
  767: 	        $disk_env{$key} = $value;
  768: 	    }
  769: 	    untie(%disk_env);
  770:         }
  771:     }
  772:     return 'ok';
  773: }
  774: # ----------------------------------------------------- Delete from Environment
  775: 
  776: sub delenv {
  777:     my ($delthis,$regexp,$roles) = @_;
  778:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  779:         my $refused = 1;
  780:         if (ref($roles) eq 'ARRAY') {
  781:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  782:             if (grep(/^\Q$role\E$/,@{$roles})) {
  783:                 $refused = 0;
  784:             }
  785:         }
  786:         if ($refused) {
  787:             &logthis("<font color=\"blue\">WARNING: ".
  788:                      "Attempt to delete from environment ".$delthis);
  789:             return 'error';
  790:         }
  791:     }
  792:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  793:     if ($opened
  794: 	&& &timed_flock($env_file,LOCK_EX)
  795: 	&&
  796: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  797: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  798: 	foreach my $key (keys(%disk_env)) {
  799: 	    if ($regexp) {
  800:                 if ($key=~/^$delthis/) {
  801:                     delete($env{$key});
  802:                     delete($disk_env{$key});
  803:                 } 
  804:             } else {
  805:                 if ($key=~/^\Q$delthis\E/) {
  806: 		    delete($env{$key});
  807: 		    delete($disk_env{$key});
  808: 	        }
  809:             }
  810: 	}
  811: 	untie(%disk_env);
  812:     }
  813:     return 'ok';
  814: }
  815: 
  816: sub get_env_multiple {
  817:     my ($name) = @_;
  818:     my @values;
  819:     if (defined($env{$name})) {
  820:         # exists is it an array
  821:         if (ref($env{$name})) {
  822:             @values=@{ $env{$name} };
  823:         } else {
  824:             $values[0]=$env{$name};
  825:         }
  826:     }
  827:     return(@values);
  828: }
  829: 
  830: # ------------------------------------------------------------------- Locking
  831: 
  832: sub set_lock {
  833:     my ($text)=@_;
  834:     $locknum++;
  835:     my $id=$$.'-'.$locknum;
  836:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  837:              'session.lock.'.$id => $text});
  838:     return $id;
  839: }
  840: 
  841: sub get_locks {
  842:     my $num=0;
  843:     my %texts=();
  844:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  845:        if ($lock=~/\w/) {
  846:           $num++;
  847:           $texts{$lock}=$env{'session.lock.'.$lock};
  848:        }
  849:    }
  850:    return ($num,%texts);
  851: }
  852: 
  853: sub remove_lock {
  854:     my ($id)=@_;
  855:     my $newlocks='';
  856:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  857:        if (($lock=~/\w/) && ($lock ne $id)) {
  858:           $newlocks.=','.$lock;
  859:        }
  860:     }
  861:     &appenv({'session.locks' => $newlocks});
  862:     &delenv('session.lock.'.$id);
  863: }
  864: 
  865: sub remove_all_locks {
  866:     my $activelocks=$env{'session.locks'};
  867:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  868:        if ($lock=~/\w/) {
  869:           &remove_lock($lock);
  870:        }
  871:     }
  872: }
  873: 
  874: 
  875: # ------------------------------------------ Find out current server userload
  876: sub userload {
  877:     my $numusers=0;
  878:     {
  879: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  880: 	my $filename;
  881: 	my $curtime=time;
  882: 	while ($filename=readdir(LONIDS)) {
  883: 	    next if ($filename eq '.' || $filename eq '..');
  884: 	    next if ($filename =~ /publicuser_\d+\.id/);
  885: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  886: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  887: 	}
  888: 	closedir(LONIDS);
  889:     }
  890:     my $userloadpercent=0;
  891:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  892:     if ($maxuserload) {
  893: 	$userloadpercent=100*$numusers/$maxuserload;
  894:     }
  895:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  896:     return $userloadpercent;
  897: }
  898: 
  899: # ------------------------------ Find server with least workload from spare.tab
  900: 
  901: sub spareserver {
  902:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  903:     my $spare_server;
  904:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  905:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  906:                                                      :  $userloadpercent;
  907:     my ($uint_dom,$remotesessions);
  908:     if (($udom ne '') && (&domain($udom) ne '')) {
  909:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  910:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  911:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  912:         $remotesessions = $udomdefaults{'remotesessions'};
  913:     }
  914:     my $spareshash = &this_host_spares($udom);
  915:     if (ref($spareshash) eq 'HASH') {
  916:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  917:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  918:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  919:                                              $try_server));
  920: 	        ($spare_server, $lowest_load) =
  921: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  922:             }
  923:         }
  924: 
  925:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  926: 
  927:         if (!$found_server) {
  928:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  929: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  930:                     next unless (&spare_can_host($udom,$uint_dom,
  931:                                                  $remotesessions,$try_server));
  932: 	            ($spare_server, $lowest_load) =
  933: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  934:                 }
  935: 	    }
  936:         }
  937:     }
  938: 
  939:     if (!$want_server_name) {
  940:         my $protocol = 'http';
  941:         if ($protocol{$spare_server} eq 'https') {
  942:             $protocol = $protocol{$spare_server};
  943:         }
  944:         if (defined($spare_server)) {
  945:             my $hostname = &hostname($spare_server);
  946:             if (defined($hostname)) {
  947: 	        $spare_server = $protocol.'://'.$hostname;
  948:             }
  949:         }
  950:     }
  951:     return $spare_server;
  952: }
  953: 
  954: sub compare_server_load {
  955:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  956: 
  957:     if ($required) {
  958:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  959:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  960:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  961:         if (($major eq '' && $minor eq '') ||
  962:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  963:             return ($spare_server,$lowest_load);
  964:         }
  965:     }
  966: 
  967:     my $loadans     = &reply('load',    $try_server);
  968:     my $userloadans = &reply('userload',$try_server);
  969: 
  970:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  971: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  972:     }
  973: 
  974:     my $load;
  975:     if ($loadans =~ /\d/) {
  976: 	if ($userloadans =~ /\d/) {
  977: 	    #both are numbers, pick the bigger one
  978: 	    $load = ($loadans > $userloadans) ? $loadans 
  979: 		                              : $userloadans;
  980: 	} else {
  981: 	    $load = $loadans;
  982: 	}
  983:     } else {
  984: 	$load = $userloadans;
  985:     }
  986: 
  987:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  988: 	$spare_server = $try_server;
  989: 	$lowest_load  = $load;
  990:     }
  991:     return ($spare_server,$lowest_load);
  992: }
  993: 
  994: # --------------------------- ask offload servers if user already has a session
  995: sub find_existing_session {
  996:     my ($udom,$uname) = @_;
  997:     my $spareshash = &this_host_spares($udom);
  998:     if (ref($spareshash) eq 'HASH') {
  999:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1000:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1001:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1002:             }
 1003:         }
 1004:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1005:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1006:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1007:             }
 1008:         }
 1009:     }
 1010:     return;
 1011: }
 1012: 
 1013: # -------------------------------- ask if server already has a session for user
 1014: sub has_user_session {
 1015:     my ($lonid,$udom,$uname) = @_;
 1016:     my $result = &reply(join(':','userhassession',
 1017: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1018:     return 1 if ($result eq 'ok');
 1019: 
 1020:     return 0;
 1021: }
 1022: 
 1023: # --------- determine least loaded server in a user's domain which allows login
 1024: 
 1025: sub choose_server {
 1026:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1027:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1028:     my %servers = &get_servers($udom);
 1029:     my $lowest_load = 30000;
 1030:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1031:     if ($skiploadbal) {
 1032:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1033:         unless (defined($cached)) {
 1034:             my $cachetime = 60*60*24;
 1035:             my %domconfig =
 1036:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1037:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1038:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1039:                                            $cachetime);
 1040:             }
 1041:         }
 1042:     }
 1043:     foreach my $lonhost (keys(%servers)) {
 1044:         if ($skiploadbal) {
 1045:             if (ref($balancers) eq 'HASH') {
 1046:                 next if (exists($balancers->{$lonhost}));
 1047:             }
 1048:         }   
 1049:         my $loginvia;
 1050:         if ($checkloginvia) {
 1051:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1052:             if ($loginvia) {
 1053:                 my ($server,$path) = split(/:/,$loginvia);
 1054:                 ($login_host, $lowest_load) =
 1055:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1056:                 if ($login_host eq $server) {
 1057:                     $portal_path = $path;
 1058:                     $isredirect = 1;
 1059:                 }
 1060:             } else {
 1061:                 ($login_host, $lowest_load) =
 1062:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1063:                 if ($login_host eq $lonhost) {
 1064:                     $portal_path = '';
 1065:                     $isredirect = ''; 
 1066:                 }
 1067:             }
 1068:         } else {
 1069:             ($login_host, $lowest_load) =
 1070:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1071:         }
 1072:     }
 1073:     if ($login_host ne '') {
 1074:         $hostname = &hostname($login_host);
 1075:     }
 1076:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1077: }
 1078: 
 1079: # --------------------------------------------- Try to change a user's password
 1080: 
 1081: sub changepass {
 1082:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1083:     $currentpass = &escape($currentpass);
 1084:     $newpass     = &escape($newpass);
 1085:     my $lonhost = $perlvar{'lonHostID'};
 1086:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1087: 		       $server);
 1088:     if (! $answer) {
 1089: 	&logthis("No reply on password change request to $server ".
 1090: 		 "by $uname in domain $udom.");
 1091:     } elsif ($answer =~ "^ok") {
 1092:         &logthis("$uname in $udom successfully changed their password ".
 1093: 		 "on $server.");
 1094:     } elsif ($answer =~ "^pwchange_failure") {
 1095: 	&logthis("$uname in $udom was unable to change their password ".
 1096: 		 "on $server.  The action was blocked by either lcpasswd ".
 1097: 		 "or pwchange");
 1098:     } elsif ($answer =~ "^non_authorized") {
 1099:         &logthis("$uname in $udom did not get their password correct when ".
 1100: 		 "attempting to change it on $server.");
 1101:     } elsif ($answer =~ "^auth_mode_error") {
 1102:         &logthis("$uname in $udom attempted to change their password despite ".
 1103: 		 "not being locally or internally authenticated on $server.");
 1104:     } elsif ($answer =~ "^unknown_user") {
 1105:         &logthis("$uname in $udom attempted to change their password ".
 1106: 		 "on $server but were unable to because $server is not ".
 1107: 		 "their home server.");
 1108:     } elsif ($answer =~ "^refused") {
 1109: 	&logthis("$server refused to change $uname in $udom password because ".
 1110: 		 "it was sent an unencrypted request to change the password.");
 1111:     } elsif ($answer =~ "invalid_client") {
 1112:         &logthis("$server refused to change $uname in $udom password because ".
 1113:                  "it was a reset by e-mail originating from an invalid server.");
 1114:     }
 1115:     return $answer;
 1116: }
 1117: 
 1118: # ----------------------- Try to determine user's current authentication scheme
 1119: 
 1120: sub queryauthenticate {
 1121:     my ($uname,$udom)=@_;
 1122:     my $uhome=&homeserver($uname,$udom);
 1123:     if (!$uhome) {
 1124: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1125: 	return 'no_host';
 1126:     }
 1127:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1128:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1129: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1130:     }
 1131:     return $answer;
 1132: }
 1133: 
 1134: # --------- Try to authenticate user from domain's lib servers (first this one)
 1135: 
 1136: sub authenticate {
 1137:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1138:     $upass=&escape($upass);
 1139:     $uname= &LONCAPA::clean_username($uname);
 1140:     my $uhome=&homeserver($uname,$udom,1);
 1141:     my $newhome;
 1142:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1143: # Maybe the machine was offline and only re-appeared again recently?
 1144:         &reconlonc();
 1145: # One more
 1146: 	$uhome=&homeserver($uname,$udom,1);
 1147:         if (($uhome eq 'no_host') && $checkdefauth) {
 1148:             if (defined(&domain($udom,'primary'))) {
 1149:                 $newhome=&domain($udom,'primary');
 1150:             }
 1151:             if ($newhome ne '') {
 1152:                 $uhome = $newhome;
 1153:             }
 1154:         }
 1155: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1156: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1157: 	    return 'no_host';
 1158:         }
 1159:     }
 1160:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1161:     if ($answer eq 'authorized') {
 1162:         if ($newhome) {
 1163:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1164:             return 'no_account_on_host'; 
 1165:         } else {
 1166:             &logthis("User $uname at $udom authorized by $uhome");
 1167:             return $uhome;
 1168:         }
 1169:     }
 1170:     if ($answer eq 'non_authorized') {
 1171: 	&logthis("User $uname at $udom rejected by $uhome");
 1172: 	return 'no_host'; 
 1173:     }
 1174:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1175:     return 'no_host';
 1176: }
 1177: 
 1178: sub can_host_session {
 1179:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1180:     my $canhost = 1;
 1181:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1182:     if (ref($remotesessions) eq 'HASH') {
 1183:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1184:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1185:                 $canhost = 0;
 1186:             } else {
 1187:                 $canhost = 1;
 1188:             }
 1189:         }
 1190:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1191:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1192:                 $canhost = 1;
 1193:             } else {
 1194:                 $canhost = 0;
 1195:             }
 1196:         }
 1197:         if ($canhost) {
 1198:             if ($remotesessions->{'version'} ne '') {
 1199:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1200:                 if ($reqmajor ne '' && $reqminor ne '') {
 1201:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1202:                         my $major = $1;
 1203:                         my $minor = $2;
 1204:                         if (($major < $reqmajor ) ||
 1205:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1206:                             $canhost = 0;
 1207:                         }
 1208:                     } else {
 1209:                         $canhost = 0;
 1210:                     }
 1211:                 }
 1212:             }
 1213:         }
 1214:     }
 1215:     if ($canhost) {
 1216:         if (ref($hostedsessions) eq 'HASH') {
 1217:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1218:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1219:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1220:                 if (($uint_dom ne '') && 
 1221:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1222:                     $canhost = 0;
 1223:                 } else {
 1224:                     $canhost = 1;
 1225:                 }
 1226:             }
 1227:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1228:                 if (($uint_dom ne '') && 
 1229:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1230:                     $canhost = 1;
 1231:                 } else {
 1232:                     $canhost = 0;
 1233:                 }
 1234:             }
 1235:         }
 1236:     }
 1237:     return $canhost;
 1238: }
 1239: 
 1240: sub spare_can_host {
 1241:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1242:     my $canhost=1;
 1243:     my $try_server_hostname = &hostname($try_server);
 1244:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1245:     my $serverhomedom = &host_domain($serverhomeID);
 1246:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1247:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1248:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1249:             $canhost = 0;
 1250:         }
 1251:     }
 1252:     if (($canhost) && ($uint_dom)) {
 1253:         my @intdoms;
 1254:         my $internet_names = &get_internet_names($try_server);
 1255:         if (ref($internet_names) eq 'ARRAY') {
 1256:             @intdoms = @{$internet_names};
 1257:         }
 1258:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1259:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1260:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1261:                                          $remotesessions,
 1262:                                          $defdomdefaults{'hostedsessions'});
 1263:         }
 1264:     }
 1265:     return $canhost;
 1266: }
 1267: 
 1268: sub this_host_spares {
 1269:     my ($dom) = @_;
 1270:     my ($dom_in_use,$lonhost_in_use,$result);
 1271:     my @hosts = &current_machine_ids();
 1272:     foreach my $lonhost (@hosts) {
 1273:         if (&host_domain($lonhost) eq $dom) {
 1274:             $dom_in_use = $dom;
 1275:             $lonhost_in_use = $lonhost;
 1276:             last;
 1277:         }
 1278:     }
 1279:     if ($dom_in_use ne '') {
 1280:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1281:     }
 1282:     if (ref($result) ne 'HASH') {
 1283:         $lonhost_in_use = $perlvar{'lonHostID'};
 1284:         $dom_in_use = &host_domain($lonhost_in_use);
 1285:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1286:         if (ref($result) ne 'HASH') {
 1287:             $result = \%spareid;
 1288:         }
 1289:     }
 1290:     return $result;
 1291: }
 1292: 
 1293: sub spares_for_offload  {
 1294:     my ($dom_in_use,$lonhost_in_use) = @_;
 1295:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1296:     if (defined($cached)) {
 1297:         return $result;
 1298:     } else {
 1299:         my $cachetime = 60*60*24;
 1300:         my %domconfig =
 1301:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1302:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1303:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1304:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1305:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1306:                 }
 1307:             }
 1308:         }
 1309:     }
 1310:     return;
 1311: }
 1312: 
 1313: sub get_lonbalancer_config {
 1314:     my ($servers) = @_;
 1315:     my ($currbalancer,$currtargets);
 1316:     if (ref($servers) eq 'HASH') {
 1317:         foreach my $server (keys(%{$servers})) {
 1318:             my %what = (
 1319:                          spareid => 1,
 1320:                          perlvar => 1,
 1321:                        );
 1322:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1323:             if ($result eq 'ok') {
 1324:                 if (ref($returnhash) eq 'HASH') {
 1325:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1326:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1327:                             $currbalancer = $server;
 1328:                             $currtargets = {};
 1329:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1330:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1331:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1332:                                 }
 1333:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1334:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1335:                                 }
 1336:                             }
 1337:                             last;
 1338:                         }
 1339:                     }
 1340:                 }
 1341:             }
 1342:         }
 1343:     }
 1344:     return ($currbalancer,$currtargets);
 1345: }
 1346: 
 1347: sub check_loadbalancing {
 1348:     my ($uname,$udom,$caller) = @_;
 1349:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1350:         $rule_in_effect,$offloadto,$otherserver);
 1351:     my $lonhost = $perlvar{'lonHostID'};
 1352:     my @hosts = &current_machine_ids();
 1353:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1354:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1355:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1356:     my $serverhomedom = &host_domain($lonhost);
 1357:     my $domneedscache;
 1358:     my $cachetime = 60*60*24;
 1359: 
 1360:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1361:         $dom_in_use = $udom;
 1362:         $homeintdom = 1;
 1363:     } else {
 1364:         $dom_in_use = $serverhomedom;
 1365:     }
 1366:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1367:     unless (defined($cached)) {
 1368:         my %domconfig =
 1369:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1370:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1371:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1372:         } else {
 1373:             $domneedscache = $dom_in_use;
 1374:         }
 1375:     }
 1376:     if (ref($result) eq 'HASH') {
 1377:         ($is_balancer,$currtargets,$currrules) = 
 1378:             &check_balancer_result($result,@hosts);
 1379:         if ($is_balancer) {
 1380:             if (ref($currrules) eq 'HASH') {
 1381:                 if ($homeintdom) {
 1382:                     if ($uname ne '') {
 1383:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1384:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1385:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1386:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1387:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1388:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1389:                             }
 1390:                         }
 1391:                         if ($rule_in_effect eq '') {
 1392:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1393:                             if ($userenv{'inststatus'} ne '') {
 1394:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1395:                                 my ($othertitle,$usertypes,$types) =
 1396:                                     &Apache::loncommon::sorted_inst_types($udom);
 1397:                                 if (ref($types) eq 'ARRAY') {
 1398:                                     foreach my $type (@{$types}) {
 1399:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1400:                                             if (exists($currrules->{$type})) {
 1401:                                                 $rule_in_effect = $currrules->{$type};
 1402:                                             }
 1403:                                         }
 1404:                                     }
 1405:                                 }
 1406:                             } else {
 1407:                                 if (exists($currrules->{'default'})) {
 1408:                                     $rule_in_effect = $currrules->{'default'};
 1409:                                 }
 1410:                             }
 1411:                         }
 1412:                     } else {
 1413:                         if (exists($currrules->{'default'})) {
 1414:                             $rule_in_effect = $currrules->{'default'};
 1415:                         }
 1416:                     }
 1417:                 } else {
 1418:                     if ($currrules->{'_LC_external'} ne '') {
 1419:                         $rule_in_effect = $currrules->{'_LC_external'};
 1420:                     }
 1421:                 }
 1422:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1423:                                                        $uname,$udom);
 1424:             }
 1425:         }
 1426:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1427:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1428:         unless (defined($cached)) {
 1429:             my %domconfig =
 1430:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1431:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1432:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1433:             } else {
 1434:                 $domneedscache = $serverhomedom;
 1435:             }
 1436:         }
 1437:         if (ref($result) eq 'HASH') {
 1438:             ($is_balancer,$currtargets,$currrules) = 
 1439:                 &check_balancer_result($result,@hosts);
 1440:             if ($is_balancer) {
 1441:                 if (ref($currrules) eq 'HASH') {
 1442:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1443:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1444:                     }
 1445:                 }
 1446:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1447:                                                        $uname,$udom);
 1448:             }
 1449:         } else {
 1450:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1451:                 $is_balancer = 1;
 1452:                 $offloadto = &this_host_spares($dom_in_use);
 1453:             }
 1454:             unless (defined($cached)) {
 1455:                 $domneedscache = $serverhomedom;
 1456:             }
 1457:         }
 1458:     } else {
 1459:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1460:             $is_balancer = 1;
 1461:             $offloadto = &this_host_spares($dom_in_use);
 1462:         }
 1463:         unless (defined($cached)) {
 1464:             $domneedscache = $serverhomedom;
 1465:         }
 1466:     }
 1467:     if ($domneedscache) {
 1468:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1469:     }
 1470:     if ($is_balancer) {
 1471:         my $lowest_load = 30000;
 1472:         if (ref($offloadto) eq 'HASH') {
 1473:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1474:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1475:                     ($otherserver,$lowest_load) =
 1476:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1477:                 }
 1478:             }
 1479:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1480: 
 1481:             if (!$found_server) {
 1482:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1483:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1484:                         ($otherserver,$lowest_load) =
 1485:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1486:                     }
 1487:                 }
 1488:             }
 1489:         } elsif (ref($offloadto) eq 'ARRAY') {
 1490:             if (@{$offloadto} == 1) {
 1491:                 $otherserver = $offloadto->[0];
 1492:             } elsif (@{$offloadto} > 1) {
 1493:                 foreach my $try_server (@{$offloadto}) {
 1494:                     ($otherserver,$lowest_load) =
 1495:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1496:                 }
 1497:             }
 1498:         }
 1499:         unless ($caller eq 'login') {
 1500:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1501:                 $is_balancer = 0;
 1502:                 if ($uname ne '' && $udom ne '') {
 1503:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1504:                     
 1505:                         &appenv({'user.loadbalexempt'     => $lonhost,  
 1506:                                  'user.loadbalcheck.time' => time});
 1507:                     }
 1508:                 }
 1509:             }
 1510:         }
 1511:     }
 1512:     return ($is_balancer,$otherserver);
 1513: }
 1514: 
 1515: sub check_balancer_result {
 1516:     my ($result,@hosts) = @_;
 1517:     my ($is_balancer,$currtargets,$currrules);
 1518:     if (ref($result) eq 'HASH') {
 1519:         if ($result->{'lonhost'} ne '') {
 1520:             my $currbalancer = $result->{'lonhost'};
 1521:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1522:                 $is_balancer = 1;
 1523:                 $currtargets = $result->{'targets'};
 1524:                 $currrules = $result->{'rules'};
 1525:             }
 1526:         } else {
 1527:             foreach my $key (keys(%{$result})) {
 1528:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1529:                     (ref($result->{$key}) eq 'HASH')) {
 1530:                     $is_balancer = 1;
 1531:                     $currrules = $result->{$key}{'rules'};
 1532:                     $currtargets = $result->{$key}{'targets'};
 1533:                     last;
 1534:                 }
 1535:             }
 1536:         }
 1537:     }
 1538:     return ($is_balancer,$currtargets,$currrules);
 1539: }
 1540: 
 1541: sub get_loadbalancer_targets {
 1542:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1543:     my $offloadto;
 1544:     if ($rule_in_effect eq 'none') {
 1545:         return [$perlvar{'lonHostID'}];
 1546:     } elsif ($rule_in_effect eq '') {
 1547:         $offloadto = $currtargets;
 1548:     } else {
 1549:         if ($rule_in_effect eq 'homeserver') {
 1550:             my $homeserver = &homeserver($uname,$udom);
 1551:             if ($homeserver ne 'no_host') {
 1552:                 $offloadto = [$homeserver];
 1553:             }
 1554:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1555:             my %domconfig =
 1556:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1557:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1558:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1559:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1560:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1561:                     }
 1562:                 }
 1563:             } else {
 1564:                 my %servers = &internet_dom_servers($udom);
 1565:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1566:                 if (&hostname($remotebalancer) ne '') {
 1567:                     $offloadto = [$remotebalancer];
 1568:                 }
 1569:             }
 1570:         } elsif (&hostname($rule_in_effect) ne '') {
 1571:             $offloadto = [$rule_in_effect];
 1572:         }
 1573:     }
 1574:     return $offloadto;
 1575: }
 1576: 
 1577: sub internet_dom_servers {
 1578:     my ($dom) = @_;
 1579:     my (%uniqservers,%servers);
 1580:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1581:     my @machinedoms = &machine_domains($primaryserver);
 1582:     foreach my $mdom (@machinedoms) {
 1583:         my %currservers = %servers;
 1584:         my %server = &get_servers($mdom);
 1585:         %servers = (%currservers,%server);
 1586:     }
 1587:     my %by_hostname;
 1588:     foreach my $id (keys(%servers)) {
 1589:         push(@{$by_hostname{$servers{$id}}},$id);
 1590:     }
 1591:     foreach my $hostname (sort(keys(%by_hostname))) {
 1592:         if (@{$by_hostname{$hostname}} > 1) {
 1593:             my $match = 0;
 1594:             foreach my $id (@{$by_hostname{$hostname}}) {
 1595:                 if (&host_domain($id) eq $dom) {
 1596:                     $uniqservers{$id} = $hostname;
 1597:                     $match = 1;
 1598:                 }
 1599:             }
 1600:             unless ($match) {
 1601:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1602:             }
 1603:         } else {
 1604:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1605:         }
 1606:     }
 1607:     return %uniqservers;
 1608: }
 1609: 
 1610: sub trusted_domains {
 1611:     my ($cmdtype,$calldom) = @_;
 1612:     my ($trusted,$untrusted);
 1613:     if (&domain($calldom) eq '') {
 1614:         return ($trusted,$untrusted);
 1615:     }
 1616:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1617:         return ($trusted,$untrusted);
 1618:     }
 1619:     my $callprimary = &domain($calldom,'primary');
 1620:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1621:     if ($intcalldom eq '') {
 1622:         return ($trusted,$untrusted);
 1623:     }
 1624: 
 1625:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1626:     unless (defined($cached)) {
 1627:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1628:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1629:         $trustconfig = $domconfig{'trust'};
 1630:     }
 1631:     if (ref($trustconfig)) {
 1632:         my (%possexc,%possinc,@allexc,@allinc); 
 1633:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1634:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1635:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1636:             }
 1637:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1638:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1639:             }
 1640:         }
 1641:         if (keys(%possexc)) {
 1642:             if (keys(%possinc)) {
 1643:                 foreach my $key (sort(keys(%possexc))) {
 1644:                     next if ($key eq $intcalldom);
 1645:                     unless ($possinc{$key}) {
 1646:                         push(@allexc,$key);
 1647:                     }
 1648:                 }
 1649:             } else {
 1650:                 @allexc = sort(keys(%possexc));
 1651:             }
 1652:         }
 1653:         if (keys(%possinc)) {
 1654:             $possinc{$intcalldom} = 1;
 1655:             @allinc = sort(keys(%possinc));
 1656:         }
 1657:         if ((@allexc > 0) || (@allinc > 0)) {
 1658:             my %doms_by_intdom;
 1659:             my %allintdoms = &all_host_intdom();
 1660:             my %alldoms = &all_host_domain();
 1661:             foreach my $key (%allintdoms) {
 1662:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1663:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1664:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1665:                     }
 1666:                 } else {
 1667:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1668:                 }
 1669:             }
 1670:             foreach my $exc (@allexc) {
 1671:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1672:                     $untrusted = $doms_by_intdom{$exc};
 1673:                 }
 1674:             }
 1675:             foreach my $inc (@allinc) {
 1676:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1677:                     $trusted = $doms_by_intdom{$inc};
 1678:                 }
 1679:             }
 1680:         }
 1681:     }
 1682:     return ($trusted,$untrusted);
 1683: }
 1684: 
 1685: sub will_trust {
 1686:     my ($cmdtype,$domain,$possdom) = @_;
 1687:     return 1 if ($domain eq $possdom);
 1688:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1689:     my $willtrust; 
 1690:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1691:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1692:             $willtrust = 1;
 1693:         }
 1694:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1695:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1696:             $willtrust = 1;
 1697:         }
 1698:     } else {
 1699:         $willtrust = 1;
 1700:     }
 1701:     return $willtrust;
 1702: }
 1703: 
 1704: # ---------------------- Find the homebase for a user from domain's lib servers
 1705: 
 1706: my %homecache;
 1707: sub homeserver {
 1708:     my ($uname,$udom,$ignoreBadCache)=@_;
 1709:     my $index="$uname:$udom";
 1710: 
 1711:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1712: 
 1713:     my %servers = &get_servers($udom,'library');
 1714:     foreach my $tryserver (keys(%servers)) {
 1715:         next if ($ignoreBadCache ne 'true' && 
 1716: 		 exists($badServerCache{$tryserver}));
 1717: 
 1718: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1719: 	if ($answer eq 'found') {
 1720: 	    delete($badServerCache{$tryserver}); 
 1721: 	    return $homecache{$index}=$tryserver;
 1722: 	} elsif ($answer eq 'no_host') {
 1723: 	    $badServerCache{$tryserver}=1;
 1724: 	}
 1725:     }    
 1726:     return 'no_host';
 1727: }
 1728: 
 1729: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1730: 
 1731: sub idget {
 1732:     my ($udom,$idsref,$namespace)=@_;
 1733:     my %returnhash=();
 1734:     my @ids=(); 
 1735:     if (ref($idsref) eq 'ARRAY') {
 1736:         @ids = @{$idsref};
 1737:     } else {
 1738:         return %returnhash; 
 1739:     }
 1740:     if ($namespace eq '') {
 1741:         $namespace = 'ids';
 1742:     }
 1743:     
 1744:     my %servers = &get_servers($udom,'library');
 1745:     foreach my $tryserver (keys(%servers)) {
 1746: 	my $idlist=join('&', map { &escape($_); } @ids);
 1747: 	if ($namespace eq 'ids') {
 1748: 	    $idlist=~tr/A-Z/a-z/;
 1749: 	}
 1750: 	my $reply;
 1751: 	if ($namespace eq 'ids') {
 1752: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1753: 	} else {
 1754: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1755: 	}
 1756: 	my @answer=();
 1757: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1758: 	    @answer=split(/\&/,$reply);
 1759: 	}                    ;
 1760: 	my $i;
 1761: 	for ($i=0;$i<=$#ids;$i++) {
 1762: 	    if ($answer[$i]) {
 1763: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1764: 	    }
 1765: 	}
 1766:     }
 1767:     return %returnhash;
 1768: }
 1769: 
 1770: # ------------------------------------- Find the IDs behind a list of usernames
 1771: 
 1772: sub idrget {
 1773:     my ($udom,@unames)=@_;
 1774:     my %returnhash=();
 1775:     foreach my $uname (@unames) {
 1776:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1777:     }
 1778:     return %returnhash;
 1779: }
 1780: 
 1781: # Store away a list of names and associated student/employee IDs or clicker IDs
 1782: 
 1783: sub idput {
 1784:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1785:     my %servers=();
 1786:     my %ids=();
 1787:     my %byid = ();
 1788:     if (ref($idsref) eq 'HASH') {
 1789:         %ids=%{$idsref};
 1790:     }
 1791:     if ($namespace eq '') {
 1792:         $namespace = 'ids'; 
 1793:     }
 1794:     foreach my $uname (keys(%ids)) {
 1795: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1796:         if ($uhom eq '') {
 1797:             $uhom=&homeserver($uname,$udom);
 1798:         }
 1799:         if ($uhom ne 'no_host') {
 1800:             my $esc_unam=&escape($uname);
 1801:             if ($namespace eq 'ids') {
 1802:                 my $id=&escape($ids{$uname});
 1803:                 $id=~tr/A-Z/a-z/;
 1804:                 my $esc_unam=&escape($uname);
 1805:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1806:             } else {
 1807:                 my @currids = split(/,/,$ids{$uname});
 1808:                 foreach my $id (@currids) {
 1809:                     $byid{$uhom}{$id} .= $uname.',';
 1810:                 }
 1811:             }
 1812:         }
 1813:     }
 1814:     if ($namespace eq 'clickers') {
 1815:         foreach my $server (keys(%byid)) {
 1816:             if (ref($byid{$server}) eq 'HASH') {
 1817:                 foreach my $id (keys(%{$byid{$server}})) {
 1818:                     $byid{$server} =~ s/,$//;
 1819:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1820:                 }
 1821:             }
 1822:         }
 1823:     }
 1824:     foreach my $server (keys(%servers)) {
 1825:         $servers{$server} =~ s/\&$//;
 1826:         if ($namespace eq 'ids') {     
 1827:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1828:         } else {
 1829:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1830:         }
 1831:     }
 1832: }
 1833: 
 1834: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1835: 
 1836: sub iddel {
 1837:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1838:     my %result=();
 1839:     my %ids=();
 1840:     my %byid = ();
 1841:     if (ref($idshashref) eq 'HASH') {
 1842:         %ids=%{$idshashref};
 1843:     } else {
 1844:         return %result;
 1845:     }
 1846:     if ($namespace eq '') {
 1847:         $namespace = 'ids';
 1848:     }
 1849:     my %servers=();
 1850:     while (my ($id,$unamestr) = each(%ids)) {
 1851:         if ($namespace eq 'ids') {
 1852:             my $uhom = $uhome;
 1853:             if ($uhom eq '') { 
 1854:                 $uhom=&homeserver($unamestr,$udom);
 1855:             }
 1856:             if ($uhom ne 'no_host') {
 1857:                 $servers{$uhom}.='&'.&escape($id);
 1858:             }
 1859:          } else {
 1860:             my @curritems = split(/,/,$ids{$id});
 1861:             foreach my $uname (@curritems) {
 1862:                 my $uhom = $uhome;
 1863:                 if ($uhom eq '') {
 1864:                     $uhom=&homeserver($uname,$udom);
 1865:                 }
 1866:                 if ($uhom ne 'no_host') { 
 1867:                     $byid{$uhom}{$id} .= $uname.',';
 1868:                 }
 1869:             }
 1870:         }
 1871:     }
 1872:     if ($namespace eq 'clickers') {
 1873:         foreach my $server (keys(%byid)) {
 1874:             if (ref($byid{$server}) eq 'HASH') {
 1875:                 foreach my $id (keys(%{$byid{$server}})) {
 1876:                     $byid{$server}{$id} =~ s/,$//;
 1877:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1878:                 }
 1879:             }
 1880:         }
 1881:     }
 1882:     foreach my $server (keys(%servers)) {
 1883:         $servers{$server} =~ s/\&$//;
 1884:         if ($namespace eq 'ids') {
 1885:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1886:         } elsif ($namespace eq 'clickers') {
 1887:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1888:         }
 1889:     }
 1890:     return %result;
 1891: }
 1892: 
 1893: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1894: 
 1895: sub updateclickers {
 1896:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1897:     my %clickers;
 1898:     if (ref($idshashref) eq 'HASH') {
 1899:         %clickers=%{$idshashref};
 1900:     } else {
 1901:         return;
 1902:     }
 1903:     my $items='';
 1904:     foreach my $item (keys(%clickers)) {
 1905:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1906:     }
 1907:     $items=~s/\&$//;
 1908:     my $request = "updateclickers:$udom:$action:$items";
 1909:     if ($critical) {
 1910:         return &critical($request,$uhome);
 1911:     } else {
 1912:         return &reply($request,$uhome);
 1913:     }
 1914: }
 1915: 
 1916: # ------------------------------dump from db file owned by domainconfig user
 1917: sub dump_dom {
 1918:     my ($namespace, $udom, $regexp) = @_;
 1919: 
 1920:     $udom ||= $env{'user.domain'};
 1921: 
 1922:     return () unless $udom;
 1923: 
 1924:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1925: }
 1926: 
 1927: # ------------------------------------------ get items from domain db files   
 1928: 
 1929: sub get_dom {
 1930:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1931:     return if ($udom eq 'public');
 1932:     my $items='';
 1933:     foreach my $item (@$storearr) {
 1934:         $items.=&escape($item).'&';
 1935:     }
 1936:     $items=~s/\&$//;
 1937:     if (!$udom) {
 1938:         $udom=$env{'user.domain'};
 1939:         return if ($udom eq 'public');
 1940:         if (defined(&domain($udom,'primary'))) {
 1941:             $uhome=&domain($udom,'primary');
 1942:         } else {
 1943:             undef($uhome);
 1944:         }
 1945:     } else {
 1946:         if (!$uhome) {
 1947:             if (defined(&domain($udom,'primary'))) {
 1948:                 $uhome=&domain($udom,'primary');
 1949:             }
 1950:         }
 1951:     }
 1952:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1953:         my $rep;
 1954:         if ($namespace =~ /^enc/) {
 1955:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1956:         } else {
 1957:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1958:         }
 1959:         my %returnhash;
 1960:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1961:             return %returnhash;
 1962:         }
 1963:         my @pairs=split(/\&/,$rep);
 1964:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1965:             return @pairs;
 1966:         }
 1967:         my $i=0;
 1968:         foreach my $item (@$storearr) {
 1969:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1970:             $i++;
 1971:         }
 1972:         return %returnhash;
 1973:     } else {
 1974:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1975:     }
 1976: }
 1977: 
 1978: # -------------------------------------------- put items in domain db files 
 1979: 
 1980: sub put_dom {
 1981:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1982:     if (!$udom) {
 1983:         $udom=$env{'user.domain'};
 1984:         if (defined(&domain($udom,'primary'))) {
 1985:             $uhome=&domain($udom,'primary');
 1986:         } else {
 1987:             undef($uhome);
 1988:         }
 1989:     } else {
 1990:         if (!$uhome) {
 1991:             if (defined(&domain($udom,'primary'))) {
 1992:                 $uhome=&domain($udom,'primary');
 1993:             }
 1994:         }
 1995:     } 
 1996:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1997:         my $items='';
 1998:         foreach my $item (keys(%$storehash)) {
 1999:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2000:         }
 2001:         $items=~s/\&$//;
 2002:         if ($namespace =~ /^enc/) {
 2003:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2004:         } else {
 2005:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2006:         }
 2007:     } else {
 2008:         &logthis("put_dom failed - no homeserver and/or domain");
 2009:     }
 2010: }
 2011: 
 2012: # --------------------- newput for items in db file owned by domainconfig user
 2013: sub newput_dom {
 2014:     my ($namespace,$storehash,$udom) = @_;
 2015:     my $result;
 2016:     if (!$udom) {
 2017:         $udom=$env{'user.domain'};
 2018:     }
 2019:     if ($udom) {
 2020:         my $uname = &get_domainconfiguser($udom);
 2021:         $result = &newput($namespace,$storehash,$udom,$uname);
 2022:     }
 2023:     return $result;
 2024: }
 2025: 
 2026: # --------------------- delete for items in db file owned by domainconfig user
 2027: sub del_dom {
 2028:     my ($namespace,$storearr,$udom)=@_;
 2029:     if (ref($storearr) eq 'ARRAY') {
 2030:         if (!$udom) {
 2031:             $udom=$env{'user.domain'};
 2032:         }
 2033:         if ($udom) {
 2034:             my $uname = &get_domainconfiguser($udom); 
 2035:             return &del($namespace,$storearr,$udom,$uname);
 2036:         }
 2037:     }
 2038: }
 2039: 
 2040: # ----------------------------------construct domainconfig user for a domain 
 2041: sub get_domainconfiguser {
 2042:     my ($udom) = @_;
 2043:     return $udom.'-domainconfig';
 2044: }
 2045: 
 2046: sub retrieve_inst_usertypes {
 2047:     my ($udom) = @_;
 2048:     my (%returnhash,@order);
 2049:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2050:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2051:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2052:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2053:     } else {
 2054:         if (defined(&domain($udom,'primary'))) {
 2055:             my $uhome=&domain($udom,'primary');
 2056:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2057:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2058:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2059:                 return (\%returnhash,\@order);
 2060:             }
 2061:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2062:             my @pairs=split(/\&/,$hashitems);
 2063:             foreach my $item (@pairs) {
 2064:                 my ($key,$value)=split(/=/,$item,2);
 2065:                 $key = &unescape($key);
 2066:                 next if ($key =~ /^error: 2 /);
 2067:                 $returnhash{$key}=&thaw_unescape($value);
 2068:             }
 2069:             my @esc_order = split(/\&/,$orderitems);
 2070:             foreach my $item (@esc_order) {
 2071:                 push(@order,&unescape($item));
 2072:             }
 2073:         } else {
 2074:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2075:         }
 2076:         return (\%returnhash,\@order);
 2077:     }
 2078: }
 2079: 
 2080: sub is_domainimage {
 2081:     my ($url) = @_;
 2082:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2083:         if (&domain($1) ne '') {
 2084:             return '1';
 2085:         }
 2086:     }
 2087:     return;
 2088: }
 2089: 
 2090: sub inst_directory_query {
 2091:     my ($srch) = @_;
 2092:     my $udom = $srch->{'srchdomain'};
 2093:     my %results;
 2094:     my $homeserver = &domain($udom,'primary');
 2095:     my $outcome;
 2096:     if ($homeserver ne '') {
 2097: 	my $queryid=&reply("querysend:instdirsearch:".
 2098: 			   &escape($srch->{'srchby'}).':'.
 2099: 			   &escape($srch->{'srchterm'}).':'.
 2100: 			   &escape($srch->{'srchtype'}),$homeserver);
 2101: 	my $host=&hostname($homeserver);
 2102: 	if ($queryid !~/^\Q$host\E\_/) {
 2103: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2104: 	    return;
 2105: 	}
 2106: 	my $response = &get_query_reply($queryid);
 2107: 	my $maxtries = 5;
 2108: 	my $tries = 1;
 2109: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2110: 	    $response = &get_query_reply($queryid);
 2111: 	    $tries ++;
 2112: 	}
 2113: 
 2114:         if (!&error($response) && $response ne 'refused') {
 2115:             if ($response eq 'unavailable') {
 2116:                 $outcome = $response;
 2117:             } else {
 2118:                 $outcome = 'ok';
 2119:                 my @matches = split(/\n/,$response);
 2120:                 foreach my $match (@matches) {
 2121:                     my ($key,$value) = split(/=/,$match);
 2122:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2123:                 }
 2124:             }
 2125:         }
 2126:     }
 2127:     return ($outcome,%results);
 2128: }
 2129: 
 2130: sub usersearch {
 2131:     my ($srch) = @_;
 2132:     my $dom = $srch->{'srchdomain'};
 2133:     my %results;
 2134:     my %libserv = &all_library();
 2135:     my $query = 'usersearch';
 2136:     foreach my $tryserver (keys(%libserv)) {
 2137:         if (&host_domain($tryserver) eq $dom) {
 2138:             my $host=&hostname($tryserver);
 2139:             my $queryid=
 2140:                 &reply("querysend:".&escape($query).':'.
 2141:                        &escape($srch->{'srchby'}).':'.
 2142:                        &escape($srch->{'srchtype'}).':'.
 2143:                        &escape($srch->{'srchterm'}),$tryserver);
 2144:             if ($queryid !~/^\Q$host\E\_/) {
 2145:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2146:                 next;
 2147:             }
 2148:             my $reply = &get_query_reply($queryid);
 2149:             my $maxtries = 1;
 2150:             my $tries = 1;
 2151:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2152:                 $reply = &get_query_reply($queryid);
 2153:                 $tries ++;
 2154:             }
 2155:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2156:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2157:             } else {
 2158:                 my @matches;
 2159:                 if ($reply =~ /\n/) {
 2160:                     @matches = split(/\n/,$reply);
 2161:                 } else {
 2162:                     @matches = split(/\&/,$reply);
 2163:                 }
 2164:                 foreach my $match (@matches) {
 2165:                     my ($uname,$udom,%userhash);
 2166:                     foreach my $entry (split(/:/,$match)) {
 2167:                         my ($key,$value) =
 2168:                             map {&unescape($_);} split(/=/,$entry);
 2169:                         $userhash{$key} = $value;
 2170:                         if ($key eq 'username') {
 2171:                             $uname = $value;
 2172:                         } elsif ($key eq 'domain') {
 2173:                             $udom = $value;
 2174:                         }
 2175:                     }
 2176:                     $results{$uname.':'.$udom} = \%userhash;
 2177:                 }
 2178:             }
 2179:         }
 2180:     }
 2181:     return %results;
 2182: }
 2183: 
 2184: sub get_instuser {
 2185:     my ($udom,$uname,$id) = @_;
 2186:     my $homeserver = &domain($udom,'primary');
 2187:     my ($outcome,%results);
 2188:     if ($homeserver ne '') {
 2189:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2190:                            &escape($id).':'.&escape($udom),$homeserver);
 2191:         my $host=&hostname($homeserver);
 2192:         if ($queryid !~/^\Q$host\E\_/) {
 2193:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2194:             return;
 2195:         }
 2196:         my $response = &get_query_reply($queryid);
 2197:         my $maxtries = 5;
 2198:         my $tries = 1;
 2199:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2200:             $response = &get_query_reply($queryid);
 2201:             $tries ++;
 2202:         }
 2203:         if (!&error($response) && $response ne 'refused') {
 2204:             if ($response eq 'unavailable') {
 2205:                 $outcome = $response;
 2206:             } else {
 2207:                 $outcome = 'ok';
 2208:                 my @matches = split(/\n/,$response);
 2209:                 foreach my $match (@matches) {
 2210:                     my ($key,$value) = split(/=/,$match);
 2211:                     $results{&unescape($key)} = &thaw_unescape($value);
 2212:                 }
 2213:             }
 2214:         }
 2215:     }
 2216:     my %userinfo;
 2217:     if (ref($results{$uname}) eq 'HASH') {
 2218:         %userinfo = %{$results{$uname}};
 2219:     } 
 2220:     return ($outcome,%userinfo);
 2221: }
 2222: 
 2223: sub get_multiple_instusers {
 2224:     my ($udom,$users,$caller) = @_;
 2225:     my ($outcome,$results);
 2226:     if (ref($users) eq 'HASH') {
 2227:         my $count = keys(%{$users}); 
 2228:         my $requested = &freeze_escape($users);
 2229:         my $homeserver = &domain($udom,'primary');
 2230:         if ($homeserver ne '') {
 2231:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2232:             my $host=&hostname($homeserver);
 2233:             if ($queryid !~/^\Q$host\E\_/) {
 2234:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2235:                          ' for host: '.$homeserver.'in domain '.$udom);
 2236:                 return ($outcome,$results);
 2237:             }
 2238:             my $response = &get_query_reply($queryid);
 2239:             my $maxtries = 5;
 2240:             if ($count > 100) {
 2241:                 $maxtries = 1+int($count/20);
 2242:             }
 2243:             my $tries = 1;
 2244:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2245:                 $response = &get_query_reply($queryid);
 2246:                 $tries ++;
 2247:             }
 2248:             if ($response eq '') {
 2249:                 $results = {};
 2250:                 foreach my $key (keys(%{$users})) {
 2251:                     my ($uname,$id);
 2252:                     if ($caller eq 'id') {
 2253:                         $id = $key;
 2254:                     } else {
 2255:                         $uname = $key;
 2256:                     }
 2257:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2258:                     $outcome = $resp;
 2259:                     if ($resp eq 'ok') {
 2260:                         %{$results} = (%{$results}, %info);
 2261:                     } else {
 2262:                         last;
 2263:                     }
 2264:                 }
 2265:             } elsif(!&error($response) && ($response ne 'refused')) {
 2266:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2267:                     $outcome = $response;
 2268:                 } else {
 2269:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2270:                     if ($outcome eq 'ok') {
 2271:                         $results = &thaw_unescape($userdata); 
 2272:                     }
 2273:                 }
 2274:             }
 2275:         }
 2276:     }
 2277:     return ($outcome,$results);
 2278: }
 2279: 
 2280: sub inst_rulecheck {
 2281:     my ($udom,$uname,$id,$item,$rules) = @_;
 2282:     my %returnhash;
 2283:     if ($udom ne '') {
 2284:         if (ref($rules) eq 'ARRAY') {
 2285:             @{$rules} = map {&escape($_);} (@{$rules});
 2286:             my $rulestr = join(':',@{$rules});
 2287:             my $homeserver=&domain($udom,'primary');
 2288:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2289:                 my $response;
 2290:                 if ($item eq 'username') {                
 2291:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2292:                                               ':'.&escape($uname).':'.$rulestr,
 2293:                                               $homeserver));
 2294:                 } elsif ($item eq 'id') {
 2295:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2296:                                               ':'.&escape($id).':'.$rulestr,
 2297:                                               $homeserver));
 2298:                 } elsif ($item eq 'selfcreate') {
 2299:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2300:                                                &escape($udom).':'.&escape($uname).
 2301:                                               ':'.$rulestr,$homeserver));
 2302:                 }
 2303:                 if ($response ne 'refused') {
 2304:                     my @pairs=split(/\&/,$response);
 2305:                     foreach my $item (@pairs) {
 2306:                         my ($key,$value)=split(/=/,$item,2);
 2307:                         $key = &unescape($key);
 2308:                         next if ($key =~ /^error: 2 /);
 2309:                         $returnhash{$key}=&thaw_unescape($value);
 2310:                     }
 2311:                 }
 2312:             }
 2313:         }
 2314:     }
 2315:     return %returnhash;
 2316: }
 2317: 
 2318: sub inst_userrules {
 2319:     my ($udom,$check) = @_;
 2320:     my (%ruleshash,@ruleorder);
 2321:     if ($udom ne '') {
 2322:         my $homeserver=&domain($udom,'primary');
 2323:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2324:             my $response;
 2325:             if ($check eq 'id') {
 2326:                 $response=&reply('instidrules:'.&escape($udom),
 2327:                                  $homeserver);
 2328:             } elsif ($check eq 'email') {
 2329:                 $response=&reply('instemailrules:'.&escape($udom),
 2330:                                  $homeserver);
 2331:             } else {
 2332:                 $response=&reply('instuserrules:'.&escape($udom),
 2333:                                  $homeserver);
 2334:             }
 2335:             if (($response ne 'refused') && ($response ne 'error') && 
 2336:                 ($response ne 'unknown_cmd') && 
 2337:                 ($response ne 'no_such_host')) {
 2338:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2339:                 my @pairs=split(/\&/,$hashitems);
 2340:                 foreach my $item (@pairs) {
 2341:                     my ($key,$value)=split(/=/,$item,2);
 2342:                     $key = &unescape($key);
 2343:                     next if ($key =~ /^error: 2 /);
 2344:                     $ruleshash{$key}=&thaw_unescape($value);
 2345:                 }
 2346:                 my @esc_order = split(/\&/,$orderitems);
 2347:                 foreach my $item (@esc_order) {
 2348:                     push(@ruleorder,&unescape($item));
 2349:                 }
 2350:             }
 2351:         }
 2352:     }
 2353:     return (\%ruleshash,\@ruleorder);
 2354: }
 2355: 
 2356: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2357: 
 2358: sub get_domain_defaults {
 2359:     my ($domain,$ignore_cache) = @_;
 2360:     return if (($domain eq '') || ($domain eq 'public'));
 2361:     my $cachetime = 60*60*24;
 2362:     unless ($ignore_cache) {
 2363:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2364:         if (defined($cached)) {
 2365:             if (ref($result) eq 'HASH') {
 2366:                 return %{$result};
 2367:             }
 2368:         }
 2369:     }
 2370:     my %domdefaults;
 2371:     my %domconfig =
 2372:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2373:                                   'requestcourses','inststatus',
 2374:                                   'coursedefaults','usersessions',
 2375:                                   'requestauthor','selfenrollment',
 2376:                                   'coursecategories','ssl','autoenroll',
 2377:                                   'trust','helpsettings'],$domain);
 2378:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2379:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2380:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2381:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2382:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2383:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2384:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2385:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2386:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2387:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2388:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2389:     } else {
 2390:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2391:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2392:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2393:     }
 2394:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2395:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2396:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2397:         } else {
 2398:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2399:         }
 2400:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2401:         foreach my $item (@usertools) {
 2402:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2403:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2404:             }
 2405:         }
 2406:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2407:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2408:         }
 2409:     }
 2410:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2411:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2412:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2413:         }
 2414:     }
 2415:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2416:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2417:     }
 2418:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2419:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2420:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2421:         }
 2422:     }
 2423:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2424:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2425:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2426:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2427:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2428:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2429:         }
 2430:         foreach my $type (@coursetypes) {
 2431:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2432:                 unless ($type eq 'community') {
 2433:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2434:                 }
 2435:             }
 2436:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2437:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2438:             }
 2439:             if ($domdefaults{'postsubmit'} eq 'on') {
 2440:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2441:                     $domdefaults{$type.'postsubtimeout'} = 
 2442:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2443:                 }
 2444:             }
 2445:         }
 2446:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2447:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2448:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2449:                 if (@clonecodes) {
 2450:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2451:                 }
 2452:             }
 2453:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2454:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2455:         }
 2456:     }
 2457:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2458:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2459:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2460:         }
 2461:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2462:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2463:         }
 2464:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2465:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2466:         }
 2467:     }
 2468:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2469:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2470:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2471:                             'approval','limit');
 2472:             foreach my $type (@coursetypes) {
 2473:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2474:                     my @mgrdc = ();
 2475:                     foreach my $item (@settings) {
 2476:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2477:                             push(@mgrdc,$item);
 2478:                         }
 2479:                     }
 2480:                     if (@mgrdc) {
 2481:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2482:                     }
 2483:                 }
 2484:             }
 2485:         }
 2486:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2487:             foreach my $type (@coursetypes) {
 2488:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2489:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2490:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2491:                     }
 2492:                 }
 2493:             }
 2494:         }
 2495:     }
 2496:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2497:         $domdefaults{'catauth'} = 'std';
 2498:         $domdefaults{'catunauth'} = 'std';
 2499:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2500:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2501:         }
 2502:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2503:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2504:         }
 2505:     }
 2506:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2507:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2508:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2509:         }
 2510:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2511:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2512:         }
 2513:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2514:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2515:         }
 2516:     }
 2517:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2518:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2519:         foreach my $prefix (@prefixes) {
 2520:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2521:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2522:             }
 2523:         }
 2524:     }
 2525:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2526:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2527:     }
 2528:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2529:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2530:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2531:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2532:         }
 2533:     }
 2534:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2535:     return %domdefaults;
 2536: }
 2537: 
 2538: sub course_portal_url {
 2539:     my ($cnum,$cdom) = @_;
 2540:     my $chome = &homeserver($cnum,$cdom);
 2541:     my $hostname = &hostname($chome);
 2542:     my $protocol = $protocol{$chome};
 2543:     $protocol = 'http' if ($protocol ne 'https');
 2544:     my %domdefaults = &get_domain_defaults($cdom);
 2545:     my $firsturl;
 2546:     if ($domdefaults{'portal_def'}) {
 2547:         $firsturl = $domdefaults{'portal_def'};
 2548:     } else {
 2549:         $firsturl = $protocol.'://'.$hostname;
 2550:     }
 2551:     return $firsturl;
 2552: }
 2553: 
 2554: # --------------------------------------------------- Assign a key to a student
 2555: 
 2556: sub assign_access_key {
 2557: #
 2558: # a valid key looks like uname:udom#comments
 2559: # comments are being appended
 2560: #
 2561:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2562:     $kdom=
 2563:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2564:     $knum=
 2565:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2566:     $cdom=
 2567:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2568:     $cnum=
 2569:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2570:     $udom=$env{'user.name'} unless (defined($udom));
 2571:     $uname=$env{'user.domain'} unless (defined($uname));
 2572:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2573:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2574:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2575:                                                   # assigned to this person
 2576:                                                   # - this should not happen,
 2577:                                                   # unless something went wrong
 2578:                                                   # the first time around
 2579: # ready to assign
 2580:         $logentry=$1.'; '.$logentry;
 2581:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2582:                                                  $kdom,$knum) eq 'ok') {
 2583: # key now belongs to user
 2584: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2585:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2586:                 &appenv({'environment.'.$envkey => $ckey});
 2587:                 return 'ok';
 2588:             } else {
 2589:                 return 
 2590:   'error: Count not permanently assign key, will need to be re-entered later.';
 2591: 	    }
 2592:         } else {
 2593:             return 'error: Could not assign key, try again later.';
 2594:         }
 2595:     } elsif (!$existing{$ckey}) {
 2596: # the key does not exist
 2597: 	return 'error: The key does not exist';
 2598:     } else {
 2599: # the key is somebody else's
 2600: 	return 'error: The key is already in use';
 2601:     }
 2602: }
 2603: 
 2604: # ------------------------------------------ put an additional comment on a key
 2605: 
 2606: sub comment_access_key {
 2607: #
 2608: # a valid key looks like uname:udom#comments
 2609: # comments are being appended
 2610: #
 2611:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2612:     $cdom=
 2613:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2614:     $cnum=
 2615:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2616:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2617:     if ($existing{$ckey}) {
 2618:         $existing{$ckey}.='; '.$logentry;
 2619: # ready to assign
 2620:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2621:                                                  $cdom,$cnum) eq 'ok') {
 2622: 	    return 'ok';
 2623:         } else {
 2624: 	    return 'error: Count not store comment.';
 2625:         }
 2626:     } else {
 2627: # the key does not exist
 2628: 	return 'error: The key does not exist';
 2629:     }
 2630: }
 2631: 
 2632: # ------------------------------------------------------ Generate a set of keys
 2633: 
 2634: sub generate_access_keys {
 2635:     my ($number,$cdom,$cnum,$logentry)=@_;
 2636:     $cdom=
 2637:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2638:     $cnum=
 2639:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2640:     unless (&allowed('mky',$cdom)) { return 0; }
 2641:     unless (($cdom) && ($cnum)) { return 0; }
 2642:     if ($number>10000) { return 0; }
 2643:     sleep(2); # make sure don't get same seed twice
 2644:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2645:     my $total=0;
 2646:     for (my $i=1;$i<=$number;$i++) {
 2647:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2648:                   sprintf("%lx",int(100000*rand)).'-'.
 2649:                   sprintf("%lx",int(100000*rand));
 2650:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2651:        $newkey=~s/0/h/g; # and also 0 and O
 2652:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2653:        if ($existing{$newkey}) {
 2654:            $i--;
 2655:        } else {
 2656: 	  if (&put('accesskeys',
 2657:               { $newkey => '# generated '.localtime().
 2658:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2659:                            '; '.$logentry },
 2660: 		   $cdom,$cnum) eq 'ok') {
 2661:               $total++;
 2662: 	  }
 2663:        }
 2664:     }
 2665:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2666:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2667:     return $total;
 2668: }
 2669: 
 2670: # ------------------------------------------------------- Validate an accesskey
 2671: 
 2672: sub validate_access_key {
 2673:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2674:     $cdom=
 2675:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2676:     $cnum=
 2677:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2678:     $udom=$env{'user.domain'} unless (defined($udom));
 2679:     $uname=$env{'user.name'} unless (defined($uname));
 2680:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2681:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2682: }
 2683: 
 2684: # ------------------------------------- Find the section of student in a course
 2685: sub devalidate_getsection_cache {
 2686:     my ($udom,$unam,$courseid)=@_;
 2687:     my $hashid="$udom:$unam:$courseid";
 2688:     &devalidate_cache_new('getsection',$hashid);
 2689: }
 2690: 
 2691: sub courseid_to_courseurl {
 2692:     my ($courseid) = @_;
 2693:     #already url style courseid
 2694:     return $courseid if ($courseid =~ m{^/});
 2695: 
 2696:     if (exists($env{'course.'.$courseid.'.num'})) {
 2697: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2698: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2699: 	return "/$cdom/$cnum";
 2700:     }
 2701: 
 2702:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2703:     if (exists($courseinfo{'num'})) {
 2704: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2705:     }
 2706: 
 2707:     return undef;
 2708: }
 2709: 
 2710: sub getsection {
 2711:     my ($udom,$unam,$courseid)=@_;
 2712:     my $cachetime=1800;
 2713: 
 2714:     my $hashid="$udom:$unam:$courseid";
 2715:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2716:     if (defined($cached)) { return $result; }
 2717: 
 2718:     my %Pending; 
 2719:     my %Expired;
 2720:     #
 2721:     # Each role can either have not started yet (pending), be active, 
 2722:     #    or have expired.
 2723:     #
 2724:     # If there is an active role, we are done.
 2725:     #
 2726:     # If there is more than one role which has not started yet, 
 2727:     #     choose the one which will start sooner
 2728:     # If there is one role which has not started yet, return it.
 2729:     #
 2730:     # If there is more than one expired role, choose the one which ended last.
 2731:     # If there is a role which has expired, return it.
 2732:     #
 2733:     $courseid = &courseid_to_courseurl($courseid);
 2734:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2735:     foreach my $key (keys(%roleshash)) {
 2736:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2737:         my $section=$1;
 2738:         if ($key eq $courseid.'_st') { $section=''; }
 2739:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2740:         my $now=time;
 2741:         if (defined($end) && $end && ($now > $end)) {
 2742:             $Expired{$end}=$section;
 2743:             next;
 2744:         }
 2745:         if (defined($start) && $start && ($now < $start)) {
 2746:             $Pending{$start}=$section;
 2747:             next;
 2748:         }
 2749:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2750:     }
 2751:     #
 2752:     # Presumedly there will be few matching roles from the above
 2753:     # loop and the sorting time will be negligible.
 2754:     if (scalar(keys(%Pending))) {
 2755:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2756:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2757:     } 
 2758:     if (scalar(keys(%Expired))) {
 2759:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2760:         my $time = pop(@sorted);
 2761:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2762:     }
 2763:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2764: }
 2765: 
 2766: sub save_cache {
 2767:     &purge_remembered();
 2768:     #&Apache::loncommon::validate_page();
 2769:     undef(%env);
 2770:     undef($env_loaded);
 2771: }
 2772: 
 2773: my $to_remember=-1;
 2774: my %remembered;
 2775: my %accessed;
 2776: my $kicks=0;
 2777: my $hits=0;
 2778: sub make_key {
 2779:     my ($name,$id) = @_;
 2780:     if (length($id) > 65 
 2781: 	&& length(&escape($id)) > 200) {
 2782: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2783:     }
 2784:     return &escape($name.':'.$id);
 2785: }
 2786: 
 2787: sub devalidate_cache_new {
 2788:     my ($name,$id,$debug) = @_;
 2789:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2790:     my $remembered_id=$name.':'.$id;
 2791:     $id=&make_key($name,$id);
 2792:     $memcache->delete($id);
 2793:     delete($remembered{$remembered_id});
 2794:     delete($accessed{$remembered_id});
 2795: }
 2796: 
 2797: sub is_cached_new {
 2798:     my ($name,$id,$debug) = @_;
 2799:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2800:     if (exists($remembered{$remembered_id})) {
 2801: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2802: 	$accessed{$remembered_id}=[&gettimeofday()];
 2803: 	$hits++;
 2804: 	return ($remembered{$remembered_id},1);
 2805:     }
 2806:     $id=&make_key($name,$id);
 2807:     my $value = $memcache->get($id);
 2808:     if (!(defined($value))) {
 2809: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2810: 	return (undef,undef);
 2811:     }
 2812:     if ($value eq '__undef__') {
 2813: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2814: 	$value=undef;
 2815:     }
 2816:     &make_room($remembered_id,$value,$debug);
 2817:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2818:     return ($value,1);
 2819: }
 2820: 
 2821: sub do_cache_new {
 2822:     my ($name,$id,$value,$time,$debug) = @_;
 2823:     my $remembered_id=$name.':'.$id;
 2824:     $id=&make_key($name,$id);
 2825:     my $setvalue=$value;
 2826:     if (!defined($setvalue)) {
 2827: 	$setvalue='__undef__';
 2828:     }
 2829:     if (!defined($time) ) {
 2830: 	$time=600;
 2831:     }
 2832:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2833:     my $result = $memcache->set($id,$setvalue,$time);
 2834:     if (! $result) {
 2835: 	&logthis("caching of id -> $id  failed");
 2836: 	$memcache->disconnect_all();
 2837:     }
 2838:     # need to make a copy of $value
 2839:     &make_room($remembered_id,$value,$debug);
 2840:     return $value;
 2841: }
 2842: 
 2843: sub make_room {
 2844:     my ($remembered_id,$value,$debug)=@_;
 2845: 
 2846:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2847:                                     : $value;
 2848:     if ($to_remember<0) { return; }
 2849:     $accessed{$remembered_id}=[&gettimeofday()];
 2850:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2851:     my $to_kick;
 2852:     my $max_time=0;
 2853:     foreach my $other (keys(%accessed)) {
 2854: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2855: 	    $to_kick=$other;
 2856: 	    $max_time=&tv_interval($accessed{$other});
 2857: 	}
 2858:     }
 2859:     delete($remembered{$to_kick});
 2860:     delete($accessed{$to_kick});
 2861:     $kicks++;
 2862:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2863:     return;
 2864: }
 2865: 
 2866: sub purge_remembered {
 2867:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2868:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2869:     undef(%remembered);
 2870:     undef(%accessed);
 2871: }
 2872: # ------------------------------------- Read an entry from a user's environment
 2873: 
 2874: sub userenvironment {
 2875:     my ($udom,$unam,@what)=@_;
 2876:     my $items;
 2877:     foreach my $item (@what) {
 2878:         $items.=&escape($item).'&';
 2879:     }
 2880:     $items=~s/\&$//;
 2881:     my %returnhash=();
 2882:     my $uhome = &homeserver($unam,$udom);
 2883:     unless ($uhome eq 'no_host') {
 2884:         my @answer=split(/\&/, 
 2885:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2886:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2887:             return %returnhash;
 2888:         }
 2889:         my $i;
 2890:         for ($i=0;$i<=$#what;$i++) {
 2891: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2892:         }
 2893:     }
 2894:     return %returnhash;
 2895: }
 2896: 
 2897: # ---------------------------------------------------------- Get a studentphoto
 2898: sub studentphoto {
 2899:     my ($udom,$unam,$ext) = @_;
 2900:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2901:     if (defined($env{'request.course.id'})) {
 2902:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2903:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2904:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2905:             } else {
 2906:                 my ($result,$perm_reqd)=
 2907: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2908:                 if ($result eq 'ok') {
 2909:                     if (!($perm_reqd eq 'yes')) {
 2910:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2911:                     }
 2912:                 }
 2913:             }
 2914:         }
 2915:     } else {
 2916:         my ($result,$perm_reqd) = 
 2917: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2918:         if ($result eq 'ok') {
 2919:             if (!($perm_reqd eq 'yes')) {
 2920:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2921:             }
 2922:         }
 2923:     }
 2924:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2925: }
 2926: 
 2927: sub retrievestudentphoto {
 2928:     my ($udom,$unam,$ext,$type) = @_;
 2929:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2930:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2931:     if ($ret eq 'ok') {
 2932:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2933:         if ($type eq 'thumbnail') {
 2934:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2935:         }
 2936:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2937:         return $tokenurl;
 2938:     } else {
 2939:         if ($type eq 'thumbnail') {
 2940:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2941:         } else { 
 2942:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2943:         }
 2944:     }
 2945: }
 2946: 
 2947: # -------------------------------------------------------------------- New chat
 2948: 
 2949: sub chatsend {
 2950:     my ($newentry,$anon,$group)=@_;
 2951:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2952:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2953:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2954:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2955: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2956: 		   &escape($newentry)).':'.$group,$chome);
 2957: }
 2958: 
 2959: # ------------------------------------------ Find current version of a resource
 2960: 
 2961: sub getversion {
 2962:     my $fname=&clutter(shift);
 2963:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2964:     return &currentversion(&filelocation('',$fname));
 2965: }
 2966: 
 2967: sub currentversion {
 2968:     my $fname=shift;
 2969:     my $author=$fname;
 2970:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2971:     my ($udom,$uname)=split(/\//,$author);
 2972:     my $home=&homeserver($uname,$udom);
 2973:     if ($home eq 'no_host') { 
 2974:         return -1; 
 2975:     }
 2976:     my $answer=&reply("currentversion:$fname",$home);
 2977:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2978: 	return -1;
 2979:     }
 2980:     return $answer;
 2981: }
 2982: 
 2983: #
 2984: # Return special version number of resource if set by override, empty otherwise
 2985: #
 2986: sub usedversion {
 2987:     my $fname=shift;
 2988:     unless ($fname) { $fname=$env{'request.uri'}; }
 2989:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2990:     if ($urlversion) { return $urlversion; }
 2991:     return '';
 2992: }
 2993: 
 2994: # ----------------------------- Subscribe to a resource, return URL if possible
 2995: 
 2996: sub subscribe {
 2997:     my $fname=shift;
 2998:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2999:     $fname=~s/[\n\r]//g;
 3000:     my $author=$fname;
 3001:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3002:     my ($udom,$uname)=split(/\//,$author);
 3003:     my $home=homeserver($uname,$udom);
 3004:     if ($home eq 'no_host') {
 3005:         return 'not_found';
 3006:     }
 3007:     my $answer=reply("sub:$fname",$home);
 3008:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3009: 	$answer.=' by '.$home;
 3010:     }
 3011:     return $answer;
 3012: }
 3013:     
 3014: # -------------------------------------------------------------- Replicate file
 3015: 
 3016: sub repcopy {
 3017:     my $filename=shift;
 3018:     $filename=~s/\/+/\//g;
 3019:     my $londocroot = $perlvar{'lonDocRoot'};
 3020:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3021:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3022:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3023: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3024: 	return &repcopy_userfile($filename);
 3025:     }
 3026:     $filename=~s/[\n\r]//g;
 3027:     my $transname="$filename.in.transfer";
 3028: # FIXME: this should flock
 3029:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3030:     my $remoteurl=subscribe($filename);
 3031:     if ($remoteurl =~ /^con_lost by/) {
 3032: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3033:            return 'unavailable';
 3034:     } elsif ($remoteurl eq 'not_found') {
 3035: 	   #&logthis("Subscribe returned not_found: $filename");
 3036: 	   return 'not_found';
 3037:     } elsif ($remoteurl =~ /^rejected by/) {
 3038: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3039:            return 'forbidden';
 3040:     } elsif ($remoteurl eq 'directory') {
 3041:            return 'ok';
 3042:     } else {
 3043:         my $author=$filename;
 3044:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3045:         my ($udom,$uname)=split(/\//,$author);
 3046:         my $home=homeserver($uname,$udom);
 3047:         unless ($home eq $perlvar{'lonHostID'}) {
 3048:            my @parts=split(/\//,$filename);
 3049:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3050:            if ($path ne "$londocroot/res") {
 3051:                &logthis("Malconfiguration for replication: $filename");
 3052: 	       return 'bad_request';
 3053:            }
 3054:            my $count;
 3055:            for ($count=5;$count<$#parts;$count++) {
 3056:                $path.="/$parts[$count]";
 3057:                if ((-e $path)!=1) {
 3058: 		   mkdir($path,0777);
 3059:                }
 3060:            }
 3061:            my $request=new HTTP::Request('GET',"$remoteurl");
 3062:            my $response;
 3063:            if ($remoteurl =~ m{/raw/}) {
 3064:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3065:            } else {
 3066:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3067:            }
 3068:            if ($response->is_error()) {
 3069: 	       unlink($transname);
 3070:                my $message=$response->status_line;
 3071:                &logthis("<font color=\"blue\">WARNING:"
 3072:                        ." LWP get: $message: $filename</font>");
 3073:                return 'unavailable';
 3074:            } else {
 3075: 	       if ($remoteurl!~/\.meta$/) {
 3076:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3077:                   my $mresponse;
 3078:                   if ($remoteurl =~ m{/raw/}) {
 3079:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3080:                   } else {
 3081:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3082:                   }
 3083:                   if ($mresponse->is_error()) {
 3084: 		      unlink($filename.'.meta');
 3085:                       &logthis(
 3086:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3087:                   }
 3088: 	       }
 3089:                rename($transname,$filename);
 3090:                return 'ok';
 3091:            }
 3092:        }
 3093:     }
 3094: }
 3095: 
 3096: # ------------------------------------------------ Get server side include body
 3097: sub ssi_body {
 3098:     my ($filelink,%form)=@_;
 3099:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3100:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3101:     }
 3102:     my $output='';
 3103:     my $response;
 3104:     if ($filelink=~/^https?\:/) {
 3105:        ($output,$response)=&externalssi($filelink);
 3106:     } else {
 3107:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3108:        $filelink .= 'inhibitmenu=yes';
 3109:        ($output,$response)=&ssi($filelink,%form);
 3110:     }
 3111:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3112:     $output=~s/^.*?\<body[^\>]*\>//si;
 3113:     $output=~s/\<\/body\s*\>.*?$//si;
 3114:     if (wantarray) {
 3115:         return ($output, $response);
 3116:     } else {
 3117:         return $output;
 3118:     }
 3119: }
 3120: 
 3121: # --------------------------------------------------------- Server Side Include
 3122: 
 3123: sub absolute_url {
 3124:     my ($host_name) = @_;
 3125:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3126:     if ($host_name eq '') {
 3127: 	$host_name = $ENV{'SERVER_NAME'};
 3128:     }
 3129:     return $protocol.$host_name;
 3130: }
 3131: 
 3132: #
 3133: #   Server side include.
 3134: # Parameters:
 3135: #  fn     Possibly encrypted resource name/id.
 3136: #  form   Hash that describes how the rendering should be done
 3137: #         and other things.
 3138: # Returns:
 3139: #   Scalar context: The content of the response.
 3140: #   Array context:  2 element list of the content and the full response object.
 3141: #     
 3142: sub ssi {
 3143: 
 3144:     my ($fn,%form)=@_;
 3145:     my $request;
 3146: 
 3147:     $form{'no_update_last_known'}=1;
 3148:     &Apache::lonenc::check_encrypt(\$fn);
 3149:     if (%form) {
 3150:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3151:       $request->content(join('&',map { 
 3152:             my $name = escape($_);
 3153:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3154:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3155:             : &escape($form{$_}) );    
 3156:         } keys(%form)));
 3157:     } else {
 3158:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3159:     }
 3160: 
 3161:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3162:     my $lonhost = $perlvar{'lonHostID'};
 3163:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
 3164: 
 3165:     if (wantarray) {
 3166: 	return ($response->content, $response);
 3167:     } else {
 3168: 	return $response->content;
 3169:     }
 3170: }
 3171: 
 3172: sub externalssi {
 3173:     my ($url)=@_;
 3174:     my $request=new HTTP::Request('GET',$url);
 3175:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3176:     if (wantarray) {
 3177:         return ($response->content, $response);
 3178:     } else {
 3179:         return $response->content;
 3180:     }
 3181: }
 3182: 
 3183: 
 3184: # If the local copy of a replicated resource is outdated, trigger a  
 3185: # connection from the homeserver to flush the delayed queue. If no update 
 3186: # happens, remove local copies of outdated resource (and corresponding
 3187: # metadata file).
 3188: 
 3189: sub remove_stale_resfile {
 3190:     my ($url) = @_;
 3191:     my $removed;
 3192:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3193:         my $audom = $1;
 3194:         my $auname = $2;
 3195:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3196:             my $homeserver = &homeserver($auname,$audom);
 3197:             unless (($homeserver eq 'no_host') ||
 3198:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3199:                 my $fname = &filelocation('',$url);
 3200:                 if (-e $fname) {
 3201:                     my $protocol = $protocol{$homeserver};
 3202:                     $protocol = 'http' if ($protocol ne 'https');
 3203:                     my $hostname = &hostname($homeserver);
 3204:                     if ($hostname) {
 3205:                         my $uri = &declutter($url);
 3206:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3207:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3208:                         if ($response->is_success()) {
 3209:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3210:                             my $locmodtime = (stat($fname))[9];
 3211:                             if ($locmodtime < $remmodtime) {
 3212:                                 my $stale;
 3213:                                 my $answer = &reply('pong',$homeserver);
 3214:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3215:                                     sleep(0.2);
 3216:                                     $locmodtime = (stat($fname))[9];
 3217:                                     if ($locmodtime < $remmodtime) {
 3218:                                         my $posstransfer = $fname.'.in.transfer';
 3219:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3220:                                             $removed = 1;
 3221:                                         } else {
 3222:                                             $stale = 1;
 3223:                                         }
 3224:                                     } else {
 3225:                                         $removed = 1;
 3226:                                     }
 3227:                                 } else {
 3228:                                     $stale = 1;
 3229:                                 }
 3230:                                 if ($stale) {
 3231:                                     unlink($fname);
 3232:                                     if ($uri!~/\.meta$/) {
 3233:                                         unlink($fname.'.meta');
 3234:                                     }
 3235:                                     &reply("unsub:$fname",$homeserver);
 3236:                                     $removed = 1;
 3237:                                 }
 3238:                             }
 3239:                         }
 3240:                     }
 3241:                 }
 3242:             }
 3243:         }
 3244:     }
 3245:     return $removed;
 3246: }
 3247: 
 3248: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3249: 
 3250: sub allowuploaded {
 3251:     my ($srcurl,$url)=@_;
 3252:     $url=&clutter(&declutter($url));
 3253:     my $dir=$url;
 3254:     $dir=~s/\/[^\/]+$//;
 3255:     my %httpref=();
 3256:     my $httpurl=&hreflocation('',$url);
 3257:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3258:     &Apache::lonnet::appenv(\%httpref);
 3259: }
 3260: 
 3261: #
 3262: # Determine if the current user should be able to edit a particular resource,
 3263: # when viewing in course context.
 3264: # (a) When viewing resource used to determine if "Edit" item is included in 
 3265: #     Functions.
 3266: # (b) When displaying folder contents in course editor, used to determine if
 3267: #     "Edit" link will be displayed alongside resource.
 3268: #
 3269: #  input: six args -- filename (decluttered), course number, course domain,
 3270: #                   url, symb (if registered) and group (if this is a group
 3271: #                   item -- e.g., bulletin board, group page etc.).
 3272: #  output: array of five scalars -- 
 3273: #          $cfile -- url for file editing if editable on current server
 3274: #          $home -- homeserver of resource (i.e., for author if published,
 3275: #                                           or course if uploaded.).
 3276: #          $switchserver --  1 if server switch will be needed.
 3277: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3278: #          $forceview -- 1 if icon/link should be to go to view mode
 3279: #
 3280: 
 3281: sub can_edit_resource {
 3282:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3283:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3284: #
 3285: # For aboutme pages user can only edit his/her own.
 3286: #
 3287:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3288:         my ($sdom,$sname) = ($1,$2);
 3289:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3290:             $home = $env{'user.home'};
 3291:             $cfile = $resurl;
 3292:             if ($env{'form.forceedit'}) {
 3293:                 $forceview = 1;
 3294:             } else {
 3295:                 $forceedit = 1;
 3296:             }
 3297:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3298:         } else {
 3299:             return;
 3300:         }
 3301:     }
 3302: 
 3303:     if ($env{'request.course.id'}) {
 3304:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3305:         if ($group ne '') {
 3306: # if this is a group homepage or group bulletin board, check group privs
 3307:             my $allowed = 0;
 3308:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3309:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3310:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3311:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3312:                     $allowed = 1;
 3313:                 }
 3314:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3315:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3316:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3317:                     $allowed = 1;
 3318:                 }
 3319:             }
 3320:             if ($allowed) {
 3321:                 $home=&homeserver($cnum,$cdom);
 3322:                 if ($env{'form.forceedit'}) {
 3323:                     $forceview = 1;
 3324:                 } else {
 3325:                     $forceedit = 1;
 3326:                 }
 3327:                 $cfile = $resurl;
 3328:             } else {
 3329:                 return;
 3330:             }
 3331:         } else {
 3332:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3333:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3334:                     return;
 3335:                 }
 3336:             } elsif (!$crsedit) {
 3337: #
 3338: # No edit allowed where CC has switched to student role.
 3339: #
 3340:                 return;
 3341:             }
 3342:         }
 3343:     }
 3344: 
 3345:     if ($file ne '') {
 3346:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3347:             if (&is_course_upload($file,$cnum,$cdom)) {
 3348:                 $uploaded = 1;
 3349:                 $incourse = 1;
 3350:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3351:                     $cfile = &hreflocation('',$file);
 3352:                     if ($env{'form.forceedit'}) {
 3353:                         $forceview = 1;
 3354:                     } else {
 3355:                         $forceedit = 1;
 3356:                     }
 3357:                 }
 3358:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3359:                 $incourse = 1;
 3360:                 if ($env{'form.forceedit'}) {
 3361:                     $forceview = 1;
 3362:                 } else {
 3363:                     $forceedit = 1;
 3364:                 }
 3365:                 $cfile = $resurl;
 3366:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3367:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3368:                     $incourse = 1;
 3369:                     if ($env{'form.forceedit'}) {
 3370:                         $forceview = 1;
 3371:                     } else {
 3372:                         $forceedit = 1;
 3373:                     }
 3374:                     $cfile = $resurl;
 3375:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3376:                     $incourse = 1;
 3377:                     $cfile = $resurl.'/smpedit';
 3378:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3379:                     $incourse = 1;
 3380:                     if ($env{'form.forceedit'}) {
 3381:                         $forceview = 1;
 3382:                     } else {
 3383:                         $forceedit = 1;
 3384:                     }
 3385:                     $cfile = $resurl;
 3386:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3387:                     $incourse = 1;
 3388:                     if ($env{'form.forceedit'}) {
 3389:                         $forceview = 1;
 3390:                     } else {
 3391:                         $forceedit = 1;
 3392:                     }
 3393:                     $cfile = $resurl;
 3394:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3395:                     $incourse = 1;
 3396:                     if ($env{'form.forceedit'}) {
 3397:                         $forceview = 1;
 3398:                     } else {
 3399:                         $forceedit = 1;
 3400:                     }
 3401:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3402:                 }
 3403:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3404:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3405:                 if (&is_on_map($template)) { 
 3406:                     $incourse = 1;
 3407:                     $forceview = 1;
 3408:                     $cfile = $template;
 3409:                 }
 3410:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3411:                     $incourse = 1;
 3412:                     if ($env{'form.forceedit'}) {
 3413:                         $forceview = 1;
 3414:                     } else {
 3415:                         $forceedit = 1;
 3416:                     }
 3417:                     $cfile = $resurl;
 3418:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3419:                 $incourse = 1;
 3420:                 if ($env{'form.forceedit'}) {
 3421:                     $forceview = 1;
 3422:                 } else {
 3423:                     $forceedit = 1;
 3424:                 }
 3425:                 $cfile = $resurl;
 3426:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3427:                 $incourse = 1;
 3428:                 $forceview = 1;
 3429:                 if ($symb) {
 3430:                     my ($map,$id,$res)=&decode_symb($symb);
 3431:                     $env{'request.symb'} = $symb;
 3432:                     $cfile = &clutter($res);
 3433:                 } else {
 3434:                     $cfile = $env{'form.suppurl'};
 3435:                     my $escfile = &unescape($cfile);
 3436:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3437:                         $cfile = '/adm/wrapper'.$escfile;
 3438:                     } else {
 3439:                         $escfile =~ s{^http://}{};
 3440:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3441:                     }
 3442:                 }
 3443:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3444:                 if ($env{'form.forceedit'}) {
 3445:                     $forceview = 1;
 3446:                 } else {
 3447:                     $forceedit = 1;
 3448:                 }
 3449:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3450:             }
 3451:         }
 3452:         if ($uploaded || $incourse) {
 3453:             $home=&homeserver($cnum,$cdom);
 3454:         } elsif ($file !~ m{/$}) {
 3455:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3456:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3457:             # Check that the user has permission to edit this resource
 3458:             my $setpriv = 1;
 3459:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3460:             if (defined($cfudom)) {
 3461:                 $home=&homeserver($cfuname,$cfudom);
 3462:                 $cfile=$file;
 3463:             }
 3464:         }
 3465:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3466:             (($home ne '') && ($home ne 'no_host'))) {
 3467:             my @ids=&current_machine_ids();
 3468:             unless (grep(/^\Q$home\E$/,@ids)) {
 3469:                 $switchserver=1;
 3470:             }
 3471:         }
 3472:     }
 3473:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3474: }
 3475: 
 3476: sub is_course_upload {
 3477:     my ($file,$cnum,$cdom) = @_;
 3478:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3479:     $uploadpath =~ s{^\/}{};
 3480:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3481:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3482:         return 1;
 3483:     }
 3484:     return;
 3485: }
 3486: 
 3487: sub in_course {
 3488:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3489:     if ($hideprivileged) {
 3490:         my $skipuser;
 3491:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3492:         my @possdoms = ($cdom);  
 3493:         if ($coursehash{'checkforpriv'}) { 
 3494:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3495:         }
 3496:         if (&privileged($uname,$udom,\@possdoms)) {
 3497:             $skipuser = 1;
 3498:             if ($coursehash{'nothideprivileged'}) {
 3499:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3500:                     my $user;
 3501:                     if ($item =~ /:/) {
 3502:                         $user = $item;
 3503:                     } else {
 3504:                         $user = join(':',split(/[\@]/,$item));
 3505:                     }
 3506:                     if ($user eq $uname.':'.$udom) {
 3507:                         undef($skipuser);
 3508:                         last;
 3509:                     }
 3510:                 }
 3511:             }
 3512:             if ($skipuser) {
 3513:                 return 0;
 3514:             }
 3515:         }
 3516:     }
 3517:     $type ||= 'any';
 3518:     if (!defined($cdom) || !defined($cnum)) {
 3519:         my $cid  = $env{'request.course.id'};
 3520:         $cdom = $env{'course.'.$cid.'.domain'};
 3521:         $cnum = $env{'course.'.$cid.'.num'};
 3522:     }
 3523:     my $typesref;
 3524:     if (($type eq 'any') || ($type eq 'all')) {
 3525:         $typesref = ['active','previous','future'];
 3526:     } elsif ($type eq 'previous' || $type eq 'future') {
 3527:         $typesref = [$type];
 3528:     }
 3529:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3530:                               $typesref,undef,[$cdom]);
 3531:     my ($tmp) = keys(%roles);
 3532:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3533:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3534:     if (@course_roles > 0) {
 3535:         return 1;
 3536:     }
 3537:     return 0;
 3538: }
 3539: 
 3540: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3541: # input: action, courseID, current domain, intended
 3542: #        path to file, source of file, instruction to parse file for objects,
 3543: #        ref to hash for embedded objects,
 3544: #        ref to hash for codebase of java objects.
 3545: #        reference to scalar to accommodate mime type determined
 3546: #          from File::MMagic if $parser = parse.
 3547: #
 3548: # output: url to file (if action was uploaddoc), 
 3549: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3550: #
 3551: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3552: # course.
 3553: #
 3554: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3555: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3556: #          course's home server.
 3557: #
 3558: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3559: #          be copied from $source (current location) to 
 3560: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3561: #         and will then be copied to
 3562: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3563: #         course's home server.
 3564: #
 3565: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3566: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3567: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3568: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3569: #         in course's home server.
 3570: #
 3571: 
 3572: sub process_coursefile {
 3573:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3574:         $mimetype)=@_;
 3575:     my $fetchresult;
 3576:     my $home=&homeserver($docuname,$docudom);
 3577:     if ($action eq 'propagate') {
 3578:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3579: 			     $home);
 3580:     } else {
 3581:         my $fpath = '';
 3582:         my $fname = $file;
 3583:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3584:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3585:         my $filepath = &build_filepath($fpath);
 3586:         if ($action eq 'copy') {
 3587:             if ($source eq '') {
 3588:                 $fetchresult = 'no source file';
 3589:                 return $fetchresult;
 3590:             } else {
 3591:                 my $destination = $filepath.'/'.$fname;
 3592:                 rename($source,$destination);
 3593:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3594:                                  $home);
 3595:             }
 3596:         } elsif ($action eq 'uploaddoc') {
 3597:             open(my $fh,'>'.$filepath.'/'.$fname);
 3598:             print $fh $env{'form.'.$source};
 3599:             close($fh);
 3600:             if ($parser eq 'parse') {
 3601:                 my $mm = new File::MMagic;
 3602:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3603:                 if ($type eq 'text/html') {
 3604:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3605:                     unless ($parse_result eq 'ok') {
 3606:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3607:                     }
 3608:                 }
 3609:                 if (ref($mimetype)) {
 3610:                     $$mimetype = $type;
 3611:                 } 
 3612:             }
 3613:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3614:                                  $home);
 3615:             if ($fetchresult eq 'ok') {
 3616:                 return '/uploaded/'.$fpath.'/'.$fname;
 3617:             } else {
 3618:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3619:                         ' to host '.$home.': '.$fetchresult);
 3620:                 return '/adm/notfound.html';
 3621:             }
 3622:         }
 3623:     }
 3624:     unless ( $fetchresult eq 'ok') {
 3625:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3626:              ' to host '.$home.': '.$fetchresult);
 3627:     }
 3628:     return $fetchresult;
 3629: }
 3630: 
 3631: sub build_filepath {
 3632:     my ($fpath) = @_;
 3633:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3634:     unless ($fpath eq '') {
 3635:         my @parts=split('/',$fpath);
 3636:         foreach my $part (@parts) {
 3637:             $filepath.= '/'.$part;
 3638:             if ((-e $filepath)!=1) {
 3639:                 mkdir($filepath,0777);
 3640:             }
 3641:         }
 3642:     }
 3643:     return $filepath;
 3644: }
 3645: 
 3646: sub store_edited_file {
 3647:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3648:     my $file = $primary_url;
 3649:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3650:     my $fpath = '';
 3651:     my $fname = $file;
 3652:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3653:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3654:     my $filepath = &build_filepath($fpath);
 3655:     open(my $fh,'>'.$filepath.'/'.$fname);
 3656:     print $fh $content;
 3657:     close($fh);
 3658:     my $home=&homeserver($docuname,$docudom);
 3659:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3660: 			  $home);
 3661:     if ($$fetchresult eq 'ok') {
 3662:         return '/uploaded/'.$fpath.'/'.$fname;
 3663:     } else {
 3664:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3665: 		 ' to host '.$home.': '.$$fetchresult);
 3666:         return '/adm/notfound.html';
 3667:     }
 3668: }
 3669: 
 3670: sub clean_filename {
 3671:     my ($fname,$args)=@_;
 3672: # Replace Windows backslashes by forward slashes
 3673:     $fname=~s/\\/\//g;
 3674:     if (!$args->{'keep_path'}) {
 3675:         # Get rid of everything but the actual filename
 3676: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3677:     }
 3678: # Replace spaces by underscores
 3679:     $fname=~s/\s+/\_/g;
 3680: # Replace all other weird characters by nothing
 3681:     $fname=~s{[^/\w\.\-]}{}g;
 3682: # Replace all .\d. sequences with _\d. so they no longer look like version
 3683: # numbers
 3684:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3685:     return $fname;
 3686: }
 3687: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3688: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3689: # image with the same aspect ratio as the original, but with dimensions which do 
 3690: # not exceed $resizewidth and $resizeheight.
 3691:  
 3692: sub resizeImage {
 3693:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3694:     my $ima = Image::Magick->new;
 3695:     my $resized;
 3696:     if (-e $img_path) {
 3697:         $ima->Read($img_path);
 3698:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3699:             my $width = $ima->Get('width');
 3700:             my $height = $ima->Get('height');
 3701:             if ($width > $resizewidth) {
 3702: 	        my $factor = $width/$resizewidth;
 3703:                 my $newheight = $height/$factor;
 3704:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3705:                 $resized = 1;
 3706:             }
 3707:         }
 3708:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3709:             my $width = $ima->Get('width');
 3710:             my $height = $ima->Get('height');
 3711:             if ($height > $resizeheight) {
 3712:                 my $factor = $height/$resizeheight;
 3713:                 my $newwidth = $width/$factor;
 3714:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3715:                 $resized = 1;
 3716:             }
 3717:         }
 3718:         if ($resized) {
 3719:             $ima->Write($img_path);
 3720:         }
 3721:     }
 3722:     return;
 3723: }
 3724: 
 3725: # --------------- Take an uploaded file and put it into the userfiles directory
 3726: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3727: #                    the desired filename is in $env{"form.$formname.filename"}
 3728: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3729: #                                    canceloverwrite, or ''. 
 3730: #                   if 'coursedoc': upload to the current course
 3731: #                   if 'existingfile': write file to tmp/overwrites directory 
 3732: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3733: #                   $context is passed as argument to &finishuserfileupload
 3734: #        $subdir - directory in userfile to store the file into
 3735: #        $parser - instruction to parse file for objects ($parser = parse)    
 3736: #        $allfiles - reference to hash for embedded objects
 3737: #        $codebase - reference to hash for codebase of java objects
 3738: #        $desuname - username for permanent storage of uploaded file
 3739: #        $dsetudom - domain for permanaent storage of uploaded file
 3740: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3741: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3742: #        $resizewidth - width (pixels) to which to resize uploaded image
 3743: #        $resizeheight - height (pixels) to which to resize uploaded image
 3744: #        $mimetype - reference to scalar to accommodate mime type determined
 3745: #                    from File::MMagic.
 3746: # 
 3747: # output: url of file in userspace, or error: <message> 
 3748: #             or /adm/notfound.html if failure to upload occurse
 3749: 
 3750: sub userfileupload {
 3751:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3752:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3753:     if (!defined($subdir)) { $subdir='unknown'; }
 3754:     my $fname=$env{'form.'.$formname.'.filename'};
 3755:     $fname=&clean_filename($fname);
 3756:     # See if there is anything left
 3757:     unless ($fname) { return 'error: no uploaded file'; }
 3758:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3759:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3760:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3761:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3762:         my $now = time;
 3763:         my $filepath;
 3764:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3765:              $filepath = 'tmp/helprequests/'.$now;
 3766:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3767:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3768:                          '_'.$env{'user.domain'}.'/pending';
 3769:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3770:             my ($docuname,$docudom);
 3771:             if ($destudom =~ /^$match_domain$/) {
 3772:                 $docudom = $destudom;
 3773:             } else {
 3774:                 $docudom = $env{'user.domain'};
 3775:             }
 3776:             if ($destuname =~ /^$match_username$/) {
 3777:                 $docuname = $destuname;
 3778:             } else {
 3779:                 $docuname = $env{'user.name'};
 3780:             }
 3781:             if (exists($env{'form.group'})) {
 3782:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3783:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3784:             }
 3785:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3786:             if ($context eq 'canceloverwrite') {
 3787:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3788:                 if (-e  $tempfile) {
 3789:                     my @info = stat($tempfile);
 3790:                     if ($info[9] eq $env{'form.timestamp'}) {
 3791:                         unlink($tempfile);
 3792:                     }
 3793:                 }
 3794:                 return;
 3795:             }
 3796:         }
 3797:         # Create the directory if not present
 3798:         my @parts=split(/\//,$filepath);
 3799:         my $fullpath = $perlvar{'lonDaemons'};
 3800:         for (my $i=0;$i<@parts;$i++) {
 3801:             $fullpath .= '/'.$parts[$i];
 3802:             if ((-e $fullpath)!=1) {
 3803:                 mkdir($fullpath,0777);
 3804:             }
 3805:         }
 3806:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3807:         print $fh $env{'form.'.$formname};
 3808:         close($fh);
 3809:         if ($context eq 'existingfile') {
 3810:             my @info = stat($fullpath.'/'.$fname);
 3811:             return ($fullpath.'/'.$fname,$info[9]);
 3812:         } else {
 3813:             return $fullpath.'/'.$fname;
 3814:         }
 3815:     }
 3816:     if ($subdir eq 'scantron') {
 3817:         $fname = 'scantron_orig_'.$fname;
 3818:     } else {
 3819:         $fname="$subdir/$fname";
 3820:     }
 3821:     if ($context eq 'coursedoc') {
 3822: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3823: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3824:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3825:             return &finishuserfileupload($docuname,$docudom,
 3826: 					 $formname,$fname,$parser,$allfiles,
 3827: 					 $codebase,$thumbwidth,$thumbheight,
 3828:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3829:         } else {
 3830:             if ($env{'form.folder'}) {
 3831:                 $fname=$env{'form.folder'}.'/'.$fname;
 3832:             }
 3833:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3834: 				       $fname,$formname,$parser,
 3835: 				       $allfiles,$codebase,$mimetype);
 3836:         }
 3837:     } elsif (defined($destuname)) {
 3838:         my $docuname=$destuname;
 3839:         my $docudom=$destudom;
 3840: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3841: 				     $parser,$allfiles,$codebase,
 3842:                                      $thumbwidth,$thumbheight,
 3843:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3844:     } else {
 3845:         my $docuname=$env{'user.name'};
 3846:         my $docudom=$env{'user.domain'};
 3847:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3848:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3849:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3850:         }
 3851: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3852: 				     $parser,$allfiles,$codebase,
 3853:                                      $thumbwidth,$thumbheight,
 3854:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3855:     }
 3856: }
 3857: 
 3858: sub finishuserfileupload {
 3859:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3860:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3861:     my $path=$docudom.'/'.$docuname.'/';
 3862:     my $filepath=$perlvar{'lonDocRoot'};
 3863:   
 3864:     my ($fnamepath,$file,$fetchthumb);
 3865:     $file=$fname;
 3866:     if ($fname=~m|/|) {
 3867:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3868: 	$path.=$fnamepath.'/';
 3869:     }
 3870:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3871:     my $count;
 3872:     for ($count=4;$count<=$#parts;$count++) {
 3873:         $filepath.="/$parts[$count]";
 3874:         if ((-e $filepath)!=1) {
 3875: 	    mkdir($filepath,0777);
 3876:         }
 3877:     }
 3878: 
 3879: # Save the file
 3880:     {
 3881: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3882: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3883: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3884: 	    return '/adm/notfound.html';
 3885: 	}
 3886:         if ($context eq 'overwrite') {
 3887:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3888:             my $target = $filepath.'/'.$file;
 3889:             if (-e $source) {
 3890:                 my @info = stat($source);
 3891:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3892:                     unless (&File::Copy::move($source,$target)) {
 3893:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3894:                         return "Moving from $source failed";
 3895:                     }
 3896:                 } else {
 3897:                     return "Temporary file: $source had unexpected date/time for last modification";
 3898:                 }
 3899:             } else {
 3900:                 return "Temporary file: $source missing";
 3901:             }
 3902:         } elsif (!print FH ($env{'form.'.$formname})) {
 3903: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3904: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3905: 	    return '/adm/notfound.html';
 3906: 	}
 3907: 	close(FH);
 3908:         if ($resizewidth && $resizeheight) {
 3909:             my $mm = new File::MMagic;
 3910:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3911:             if ($mime_type =~ m{^image/}) {
 3912: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3913:             }  
 3914: 	}
 3915:     }
 3916:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3917:         if (ref($mimetype)) {
 3918:             if ($$mimetype eq '') {
 3919:                 my $mm = new File::MMagic;
 3920:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3921:                 $$mimetype = $type;
 3922:             }
 3923:         }
 3924:     }
 3925:     if ($parser eq 'parse') {
 3926:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3927:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3928:                                                        $allfiles,$codebase);
 3929:             unless ($parse_result eq 'ok') {
 3930:                 &logthis('Failed to parse '.$filepath.$file.
 3931: 	   	         ' for embedded media: '.$parse_result); 
 3932:             }
 3933:         }
 3934:     }
 3935:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3936:         my $input = $filepath.'/'.$file;
 3937:         my $output = $filepath.'/'.'tn-'.$file;
 3938:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3939:         system("convert -sample $thumbsize $input $output");
 3940:         if (-e $filepath.'/'.'tn-'.$file) {
 3941:             $fetchthumb  = 1; 
 3942:         }
 3943:     }
 3944:  
 3945: # Notify homeserver to grep it
 3946: #
 3947:     my $docuhome=&homeserver($docuname,$docudom);	
 3948:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3949:     if ($fetchresult eq 'ok') {
 3950:         if ($fetchthumb) {
 3951:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3952:             if ($thumbresult ne 'ok') {
 3953:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3954:                          $docuhome.': '.$thumbresult);
 3955:             }
 3956:         }
 3957: #
 3958: # Return the URL to it
 3959:         return '/uploaded/'.$path.$file;
 3960:     } else {
 3961:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3962: 		 ': '.$fetchresult);
 3963:         return '/adm/notfound.html';
 3964:     }
 3965: }
 3966: 
 3967: sub extract_embedded_items {
 3968:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3969:     my @state = ();
 3970:     my (%lastids,%related,%shockwave,%flashvars);
 3971:     my %javafiles = (
 3972:                       codebase => '',
 3973:                       code => '',
 3974:                       archive => ''
 3975:                     );
 3976:     my %mediafiles = (
 3977:                       src => '',
 3978:                       movie => '',
 3979:                      );
 3980:     my $p;
 3981:     if ($content) {
 3982:         $p = HTML::LCParser->new($content);
 3983:     } else {
 3984:         $p = HTML::LCParser->new($fullpath);
 3985:     }
 3986:     while (my $t=$p->get_token()) {
 3987: 	if ($t->[0] eq 'S') {
 3988: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3989: 	    push(@state, $tagname);
 3990:             if (lc($tagname) eq 'allow') {
 3991:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3992:             }
 3993: 	    if (lc($tagname) eq 'img') {
 3994: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3995: 	    }
 3996: 	    if (lc($tagname) eq 'a') {
 3997:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3998:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3999:                 }
 4000: 	    }
 4001:             if (lc($tagname) eq 'script') {
 4002:                 my $src;
 4003:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4004:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4005:                 } else {
 4006:                     if ($attr->{'src'} ne '') {
 4007:                         $src = $attr->{'src'};
 4008:                         &add_filetype($allfiles,$src,'src');
 4009:                     }
 4010:                 }
 4011:                 my $text = $p->get_trimmed_text();
 4012:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4013:                     my @swfargs = split(/,/,$1);
 4014:                     foreach my $item (@swfargs) {
 4015:                         $item =~ s/["']//g;
 4016:                         $item =~ s/^\s+//;
 4017:                         $item =~ s/\s+$//;
 4018:                     }
 4019:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4020:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4021:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4022:                         } else {
 4023:                             $related{$swfargs[0]} = [$swfargs[2]];
 4024:                         }
 4025:                     }
 4026:                 }
 4027:             }
 4028:             if (lc($tagname) eq 'link') {
 4029:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4030:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4031:                 }
 4032:             }
 4033: 	    if (lc($tagname) eq 'object' ||
 4034: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4035: 		foreach my $item (keys(%javafiles)) {
 4036: 		    $javafiles{$item} = '';
 4037: 		}
 4038:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4039:                     $lastids{lc($tagname)} = $attr->{'id'};
 4040:                 }
 4041: 	    }
 4042: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4043: 		my $name = lc($attr->{'name'});
 4044: 		foreach my $item (keys(%javafiles)) {
 4045: 		    if ($name eq $item) {
 4046: 			$javafiles{$item} = $attr->{'value'};
 4047: 			last;
 4048: 		    }
 4049: 		}
 4050:                 my $pathfrom;
 4051: 		foreach my $item (keys(%mediafiles)) {
 4052: 		    if ($name eq $item) {
 4053:                         $pathfrom = $attr->{'value'};
 4054:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4055: 			&add_filetype($allfiles,$pathfrom,$name);
 4056: 			last;
 4057: 		    }
 4058: 		}
 4059:                 if ($name eq 'flashvars') {
 4060:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4061:                 }
 4062:                 if ($pathfrom ne '') {
 4063:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4064:                                          $pathfrom);
 4065:                 }
 4066: 	    }
 4067: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4068: 		foreach my $item (keys(%javafiles)) {
 4069: 		    if ($attr->{$item}) {
 4070: 			$javafiles{$item} = $attr->{$item};
 4071: 			last;
 4072: 		    }
 4073: 		}
 4074: 		foreach my $item (keys(%mediafiles)) {
 4075: 		    if ($attr->{$item}) {
 4076: 			&add_filetype($allfiles,$attr->{$item},$item);
 4077: 			last;
 4078: 		    }
 4079: 		}
 4080:                 if (lc($tagname) eq 'embed') {
 4081:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4082:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4083:                                              $attr->{'src'});
 4084:                     }
 4085:                 }
 4086: 	    }
 4087:             if (lc($tagname) eq 'iframe') {
 4088:                 my $src = $attr->{'src'} ;
 4089:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4090:                     &add_filetype($allfiles,$src,'src');
 4091:                 } elsif ($src =~ m{^/}) {
 4092:                     if ($env{'request.course.id'}) {
 4093:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4094:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4095:                         my $url = &hreflocation('',$fullpath);
 4096:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4097:                             my $relpath = $1;
 4098:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4099:                                 &add_filetype($allfiles,$1,'src');
 4100:                             }
 4101:                         }
 4102:                     }
 4103:                 }
 4104:             }
 4105:             if ($t->[4] =~ m{/>$}) {
 4106:                 pop(@state);
 4107:             }
 4108: 	} elsif ($t->[0] eq 'E') {
 4109: 	    my ($tagname) = ($t->[1]);
 4110: 	    if ($javafiles{'codebase'} ne '') {
 4111: 		$javafiles{'codebase'} .= '/';
 4112: 	    }  
 4113: 	    if (lc($tagname) eq 'applet' ||
 4114: 		lc($tagname) eq 'object' ||
 4115: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4116: 		) {
 4117: 		foreach my $item (keys(%javafiles)) {
 4118: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4119: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4120: 			&add_filetype($allfiles,$file,$item);
 4121: 		    }
 4122: 		}
 4123: 	    } 
 4124: 	    pop @state;
 4125: 	}
 4126:     }
 4127:     foreach my $id (sort(keys(%flashvars))) {
 4128:         if ($shockwave{$id} ne '') {
 4129:             my @pairs = split(/\&/,$flashvars{$id});
 4130:             foreach my $pair (@pairs) {
 4131:                 my ($key,$value) = split(/\=/,$pair);
 4132:                 if ($key eq 'thumb') {
 4133:                     &add_filetype($allfiles,$value,$key);
 4134:                 } elsif ($key eq 'content') {
 4135:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4136:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4137:                     if ($ext ne '') {
 4138:                         &add_filetype($allfiles,$path.$value,$ext);
 4139:                     }
 4140:                 }
 4141:             }
 4142:         }
 4143:     }
 4144:     return 'ok';
 4145: }
 4146: 
 4147: sub add_filetype {
 4148:     my ($allfiles,$file,$type)=@_;
 4149:     if (exists($allfiles->{$file})) {
 4150: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4151: 	    push(@{$allfiles->{$file}}, &escape($type));
 4152: 	}
 4153:     } else {
 4154: 	@{$allfiles->{$file}} = (&escape($type));
 4155:     }
 4156: }
 4157: 
 4158: sub embedded_dependency {
 4159:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4160:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4161:         if (($identifier ne '') &&
 4162:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4163:             ($pathfrom ne '')) {
 4164:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4165:             foreach my $dep (@{$related->{$identifier}}) {
 4166:                 &add_filetype($allfiles,$path.$dep,'object');
 4167:             }
 4168:         }
 4169:     }
 4170:     return;
 4171: }
 4172: 
 4173: sub removeuploadedurl {
 4174:     my ($url)=@_;	
 4175:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4176:     return &removeuserfile($uname,$udom,$fname);
 4177: }
 4178: 
 4179: sub removeuserfile {
 4180:     my ($docuname,$docudom,$fname)=@_;
 4181:     my $home=&homeserver($docuname,$docudom);    
 4182:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4183:     if ($result eq 'ok') {	
 4184:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4185:             my $metafile = $fname.'.meta';
 4186:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4187: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4188:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4189:             my $sqlresult = 
 4190:                 &update_portfolio_table($docuname,$docudom,$file,
 4191:                                         'portfolio_metadata',$group,
 4192:                                         'delete');
 4193:         }
 4194:     }
 4195:     return $result;
 4196: }
 4197: 
 4198: sub mkdiruserfile {
 4199:     my ($docuname,$docudom,$dir)=@_;
 4200:     my $home=&homeserver($docuname,$docudom);
 4201:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4202: }
 4203: 
 4204: sub renameuserfile {
 4205:     my ($docuname,$docudom,$old,$new)=@_;
 4206:     my $home=&homeserver($docuname,$docudom);
 4207:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4208:                         &escape("$old").':'.&escape("$new"),$home);
 4209:     if ($result eq 'ok') {
 4210:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4211:             my $oldmeta = $old.'.meta';
 4212:             my $newmeta = $new.'.meta';
 4213:             my $metaresult = 
 4214:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4215: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4216:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4217:             my $sqlresult = 
 4218:                 &update_portfolio_table($docuname,$docudom,$file,
 4219:                                         'portfolio_metadata',$group,
 4220:                                         'delete');
 4221:         }
 4222:     }
 4223:     return $result;
 4224: }
 4225: 
 4226: # ------------------------------------------------------------------------- Log
 4227: 
 4228: sub log {
 4229:     my ($dom,$nam,$hom,$what)=@_;
 4230:     return critical("log:$dom:$nam:$what",$hom);
 4231: }
 4232: 
 4233: # ------------------------------------------------------------------ Course Log
 4234: #
 4235: # This routine flushes several buffers of non-mission-critical nature
 4236: #
 4237: 
 4238: sub flushcourselogs {
 4239:     &logthis('Flushing log buffers');
 4240: #
 4241: # course logs
 4242: # This is a log of all transactions in a course, which can be used
 4243: # for data mining purposes
 4244: #
 4245: # It also collects the courseid database, which lists last transaction
 4246: # times and course titles for all courseids
 4247: #
 4248:     my %courseidbuffer=();
 4249:     foreach my $crsid (keys(%courselogs)) {
 4250:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4251: 		          &escape($courselogs{$crsid}),
 4252: 		          $coursehombuf{$crsid}) eq 'ok') {
 4253: 	    delete $courselogs{$crsid};
 4254:         } else {
 4255:             &logthis('Failed to flush log buffer for '.$crsid);
 4256:             if (length($courselogs{$crsid})>40000) {
 4257:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4258:                         " exceeded maximum size, deleting.</font>");
 4259:                delete $courselogs{$crsid};
 4260:             }
 4261:         }
 4262:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4263:             'description' => $coursedescrbuf{$crsid},
 4264:             'inst_code'    => $courseinstcodebuf{$crsid},
 4265:             'type'        => $coursetypebuf{$crsid},
 4266:             'owner'       => $courseownerbuf{$crsid},
 4267:         };
 4268:     }
 4269: #
 4270: # Write course id database (reverse lookup) to homeserver of courses 
 4271: # Is used in pickcourse
 4272: #
 4273:     foreach my $crs_home (keys(%courseidbuffer)) {
 4274:         my $response = &courseidput(&host_domain($crs_home),
 4275:                                     $courseidbuffer{$crs_home},
 4276:                                     $crs_home,'timeonly');
 4277:     }
 4278: #
 4279: # File accesses
 4280: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4281: #
 4282:     foreach my $entry (keys(%accesshash)) {
 4283:         if ($entry =~ /___count$/) {
 4284:             my ($dom,$name);
 4285:             ($dom,$name,undef)=
 4286: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4287:             if (! defined($dom) || $dom eq '' || 
 4288:                 ! defined($name) || $name eq '') {
 4289:                 my $cid = $env{'request.course.id'};
 4290:                 $dom  = $env{'request.'.$cid.'.domain'};
 4291:                 $name = $env{'request.'.$cid.'.num'};
 4292:             }
 4293:             my $value = $accesshash{$entry};
 4294:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4295:             my %temphash=($url => $value);
 4296:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4297:             if ($result eq 'ok') {
 4298:                 delete $accesshash{$entry};
 4299:             }
 4300:         } else {
 4301:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4302:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4303:             my %temphash=($entry => $accesshash{$entry});
 4304:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4305:                 delete $accesshash{$entry};
 4306:             }
 4307:         }
 4308:     }
 4309: #
 4310: # Roles
 4311: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4312: #
 4313:     foreach my $entry (keys(%userrolehash)) {
 4314:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4315: 	    split(/\:/,$entry);
 4316:         if (&Apache::lonnet::put('nohist_userroles',
 4317:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4318:                 $rudom,$runame) eq 'ok') {
 4319: 	    delete $userrolehash{$entry};
 4320:         }
 4321:     }
 4322: #
 4323: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4324: #
 4325:     my %domrolebuffer = ();
 4326:     foreach my $entry (keys(%domainrolehash)) {
 4327:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4328:         if ($domrolebuffer{$rudom}) {
 4329:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4330:                       '='.&escape($domainrolehash{$entry});
 4331:         } else {
 4332:             $domrolebuffer{$rudom}.=&escape($entry).
 4333:                       '='.&escape($domainrolehash{$entry});
 4334:         }
 4335:         delete $domainrolehash{$entry};
 4336:     }
 4337:     foreach my $dom (keys(%domrolebuffer)) {
 4338: 	my %servers;
 4339: 	if (defined(&domain($dom,'primary'))) {
 4340: 	    my $primary=&domain($dom,'primary');
 4341: 	    my $hostname=&hostname($primary);
 4342: 	    $servers{$primary} = $hostname;
 4343: 	} else { 
 4344: 	    %servers = &get_servers($dom,'library');
 4345: 	}
 4346: 	foreach my $tryserver (keys(%servers)) {
 4347: 	    if (&reply('domroleput:'.$dom.':'.
 4348: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4349: 		last;
 4350: 	    } else {  
 4351: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4352: 	    }
 4353:         }
 4354:     }
 4355:     $dumpcount++;
 4356: }
 4357: 
 4358: sub courselog {
 4359:     my $what=shift;
 4360:     $what=time.':'.$what;
 4361:     unless ($env{'request.course.id'}) { return ''; }
 4362:     $coursedombuf{$env{'request.course.id'}}=
 4363:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4364:     $coursenumbuf{$env{'request.course.id'}}=
 4365:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4366:     $coursehombuf{$env{'request.course.id'}}=
 4367:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4368:     $coursedescrbuf{$env{'request.course.id'}}=
 4369:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4370:     $courseinstcodebuf{$env{'request.course.id'}}=
 4371:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4372:     $courseownerbuf{$env{'request.course.id'}}=
 4373:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4374:     $coursetypebuf{$env{'request.course.id'}}=
 4375:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4376:     if (defined $courselogs{$env{'request.course.id'}}) {
 4377: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4378:     } else {
 4379: 	$courselogs{$env{'request.course.id'}}.=$what;
 4380:     }
 4381:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4382: 	&flushcourselogs();
 4383:     }
 4384: }
 4385: 
 4386: sub courseacclog {
 4387:     my $fnsymb=shift;
 4388:     unless ($env{'request.course.id'}) { return ''; }
 4389:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4390:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4391:         $what.=':POST';
 4392:         # FIXME: Probably ought to escape things....
 4393: 	foreach my $key (keys(%env)) {
 4394:             if ($key=~/^form\.(.*)/) {
 4395:                 my $formitem = $1;
 4396:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4397:                     $what.=':'.$formitem.'='.$env{$key};
 4398:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4399:                     $what.=':'.$formitem.'='.$env{$key};
 4400:                 }
 4401:             }
 4402:         }
 4403:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4404:         # FIXME: We should not be depending on a form parameter that someone
 4405:         # editing lonsearchcat.pm might change in the future.
 4406:         if ($env{'form.phase'} eq 'course_search') {
 4407:             $what.= ':POST';
 4408:             # FIXME: Probably ought to escape things....
 4409:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4410:                                  'crsdiscuss') {
 4411:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4412:             }
 4413:         }
 4414:     }
 4415:     &courselog($what);
 4416: }
 4417: 
 4418: sub countacc {
 4419:     my $url=&declutter(shift);
 4420:     return if (! defined($url) || $url eq '');
 4421:     unless ($env{'request.course.id'}) { return ''; }
 4422: #
 4423: # Mark that this url was used in this course
 4424: #
 4425:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4426: #
 4427: # Increase the access count for this resource in this child process
 4428: #
 4429:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4430:     $accesshash{$key}++;
 4431: }
 4432: 
 4433: sub linklog {
 4434:     my ($from,$to)=@_;
 4435:     $from=&declutter($from);
 4436:     $to=&declutter($to);
 4437:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4438:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4439: }
 4440: 
 4441: sub statslog {
 4442:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4443:     if ($users<2) { return; }
 4444:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4445:             'course'       => $env{'request.course.id'},
 4446:             'sections'     => '"all"',
 4447:             'num_students' => $users,
 4448:             'part'         => $part,
 4449:             'symb'         => $symb,
 4450:             'mean_tries'   => $av_attempts,
 4451:             'deg_of_diff'  => $degdiff});
 4452:     foreach my $key (keys(%dynstore)) {
 4453:         $accesshash{$key}=$dynstore{$key};
 4454:     }
 4455: }
 4456:   
 4457: sub userrolelog {
 4458:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4459:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4460:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4461:        $userrolehash
 4462:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4463:                     =$tend.':'.$tstart;
 4464:     }
 4465:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4466:        $userrolehash
 4467:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4468:                     =$tend.':'.$tstart;
 4469:     }
 4470:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4471:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4472:        $domainrolehash
 4473:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4474:                     = $tend.':'.$tstart;
 4475:     }
 4476: }
 4477: 
 4478: sub courserolelog {
 4479:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4480:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4481:         my $cdom = $1;
 4482:         my $cnum = $2;
 4483:         my $sec = $3;
 4484:         my $namespace = 'rolelog';
 4485:         my %storehash = (
 4486:                            role    => $trole,
 4487:                            start   => $tstart,
 4488:                            end     => $tend,
 4489:                            selfenroll => $selfenroll,
 4490:                            context    => $context,
 4491:                         );
 4492:         if ($trole eq 'gr') {
 4493:             $namespace = 'groupslog';
 4494:             $storehash{'group'} = $sec;
 4495:         } else {
 4496:             $storehash{'section'} = $sec;
 4497:         }
 4498:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4499:                    $domain,$cnum,$cdom);
 4500:         if (($trole ne 'st') || ($sec ne '')) {
 4501:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4502:         }
 4503:     }
 4504:     return;
 4505: }
 4506: 
 4507: sub domainrolelog {
 4508:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4509:     if ($area =~ m{^/($match_domain)/$}) {
 4510:         my $cdom = $1;
 4511:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4512:         my $namespace = 'rolelog';
 4513:         my %storehash = (
 4514:                            role    => $trole,
 4515:                            start   => $tstart,
 4516:                            end     => $tend,
 4517:                            context => $context,
 4518:                         );
 4519:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4520:                    $domain,$domconfiguser,$cdom);
 4521:     }
 4522:     return;
 4523: 
 4524: }
 4525: 
 4526: sub coauthorrolelog {
 4527:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4528:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4529:         my $audom = $1;
 4530:         my $auname = $2;
 4531:         my $namespace = 'rolelog';
 4532:         my %storehash = (
 4533:                            role    => $trole,
 4534:                            start   => $tstart,
 4535:                            end     => $tend,
 4536:                            context => $context,
 4537:                         );
 4538:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4539:                    $domain,$auname,$audom);
 4540:     }
 4541:     return;
 4542: }
 4543: 
 4544: sub get_course_adv_roles {
 4545:     my ($cid,$codes) = @_;
 4546:     $cid=$env{'request.course.id'} unless (defined($cid));
 4547:     my %coursehash=&coursedescription($cid);
 4548:     my $crstype = &Apache::loncommon::course_type($cid);
 4549:     my %nothide=();
 4550:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4551:         if ($user !~ /:/) {
 4552: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4553:         } else {
 4554:             $nothide{$user}=1;
 4555:         }
 4556:     }
 4557:     my @possdoms = ($coursehash{'domain'});
 4558:     if ($coursehash{'checkforpriv'}) {
 4559:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4560:     }
 4561:     my %returnhash=();
 4562:     my %dumphash=
 4563:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4564:     my $now=time;
 4565:     my %privileged;
 4566:     foreach my $entry (keys(%dumphash)) {
 4567: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4568:         if (($tstart) && ($tstart<0)) { next; }
 4569:         if (($tend) && ($tend<$now)) { next; }
 4570:         if (($tstart) && ($now<$tstart)) { next; }
 4571:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4572: 	if ($username eq '' || $domain eq '') { next; }
 4573:         if ((&privileged($username,$domain,\@possdoms)) &&
 4574:             (!$nothide{$username.':'.$domain})) { next; }
 4575: 	if ($role eq 'cr') { next; }
 4576:         if ($codes) {
 4577:             if ($section) { $role .= ':'.$section; }
 4578:             if ($returnhash{$role}) {
 4579:                 $returnhash{$role}.=','.$username.':'.$domain;
 4580:             } else {
 4581:                 $returnhash{$role}=$username.':'.$domain;
 4582:             }
 4583:         } else {
 4584:             my $key=&plaintext($role,$crstype);
 4585:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4586:             if ($returnhash{$key}) {
 4587: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4588:             } else {
 4589:                 $returnhash{$key}=$username.':'.$domain;
 4590:             }
 4591:         }
 4592:     }
 4593:     return %returnhash;
 4594: }
 4595: 
 4596: sub get_my_roles {
 4597:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4598:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4599:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4600:     my (%dumphash,%nothide);
 4601:     if ($context eq 'userroles') {
 4602:         %dumphash = &dump('roles',$udom,$uname);
 4603:     } else {
 4604:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4605:         if ($hidepriv) {
 4606:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4607:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4608:                 if ($user !~ /:/) {
 4609:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4610:                 } else {
 4611:                     $nothide{$user} = 1;
 4612:                 }
 4613:             }
 4614:         }
 4615:     }
 4616:     my %returnhash=();
 4617:     my $now=time;
 4618:     my %privileged;
 4619:     foreach my $entry (keys(%dumphash)) {
 4620:         my ($role,$tend,$tstart);
 4621:         if ($context eq 'userroles') {
 4622:             next if ($entry =~ /^rolesdef/);
 4623: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4624:         } else {
 4625:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4626:         }
 4627:         if (($tstart) && ($tstart<0)) { next; }
 4628:         my $status = 'active';
 4629:         if (($tend) && ($tend<=$now)) {
 4630:             $status = 'previous';
 4631:         } 
 4632:         if (($tstart) && ($now<$tstart)) {
 4633:             $status = 'future';
 4634:         }
 4635:         if (ref($types) eq 'ARRAY') {
 4636:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4637:                 next;
 4638:             } 
 4639:         } else {
 4640:             if ($status ne 'active') {
 4641:                 next;
 4642:             }
 4643:         }
 4644:         my ($rolecode,$username,$domain,$section,$area);
 4645:         if ($context eq 'userroles') {
 4646:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4647:             (undef,$domain,$username,$section) = split(/\//,$area);
 4648:         } else {
 4649:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4650:         }
 4651:         if (ref($roledoms) eq 'ARRAY') {
 4652:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4653:                 next;
 4654:             }
 4655:         }
 4656:         if (ref($roles) eq 'ARRAY') {
 4657:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4658:                 if ($role =~ /^cr\//) {
 4659:                     if (!grep(/^cr$/,@{$roles})) {
 4660:                         next;
 4661:                     }
 4662:                 } elsif ($role =~ /^gr\//) {
 4663:                     if (!grep(/^gr$/,@{$roles})) {
 4664:                         next;
 4665:                     }
 4666:                 } else {
 4667:                     next;
 4668:                 }
 4669:             }
 4670:         }
 4671:         if ($hidepriv) {
 4672:             my @privroles = ('dc','su');
 4673:             if ($context eq 'userroles') {
 4674:                 next if (grep(/^\Q$role\E$/,@privroles));
 4675:             } else {
 4676:                 my $possdoms = [$domain];
 4677:                 if (ref($roledoms) eq 'ARRAY') {
 4678:                    push(@{$possdoms},@{$roledoms}); 
 4679:                 }
 4680:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4681:                     if (!$nothide{$username.':'.$domain}) {
 4682:                         next;
 4683:                     }
 4684:                 }
 4685:             }
 4686:         }
 4687:         if ($withsec) {
 4688:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4689:                 $tstart.':'.$tend;
 4690:         } else {
 4691:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4692:         }
 4693:     }
 4694:     return %returnhash;
 4695: }
 4696: 
 4697: sub get_all_adhocroles {
 4698:     my ($dom) = @_;
 4699:     my @roles_by_num = ();
 4700:     my %domdefaults = &get_domain_defaults($dom);
 4701:     my (%description,%access_in_dom,%access_info);
 4702:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4703:         my $count = 0;
 4704:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4705:         my %ordered;
 4706:         foreach my $role (sort(keys(%domcurrent))) {
 4707:             my ($order,$desc,$access_in_dom);
 4708:             if (ref($domcurrent{$role}) eq 'HASH') {
 4709:                 $order = $domcurrent{$role}{'order'};
 4710:                 $desc = $domcurrent{$role}{'desc'};
 4711:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4712:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4713:             }
 4714:             if ($order eq '') {
 4715:                 $order = $count;
 4716:             }
 4717:             $ordered{$order} = $role;
 4718:             if ($desc ne '') {
 4719:                 $description{$role} = $desc;
 4720:             } else {
 4721:                 $description{$role}= $role;
 4722:             }
 4723:             $count++;
 4724:         }
 4725:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4726:             push(@roles_by_num,$ordered{$item});
 4727:         }
 4728:     }
 4729:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4730: }
 4731: 
 4732: sub get_my_adhocroles {
 4733:     my ($cid,$checkreg) = @_;
 4734:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4735:     if ($env{'request.course.id'} eq $cid) {
 4736:         $cdom = $env{'course.'.$cid.'.domain'};
 4737:         $cnum = $env{'course.'.$cid.'.num'};
 4738:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4739:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4740:         $cdom = $1;
 4741:         $cnum = $2;
 4742:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4743:                                      $cdom,$cnum);
 4744:     }
 4745:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4746:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4747:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4748:         if ($rosterhash{$user} ne '') {
 4749:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4750:             return ([],{}) if ($type eq 'auto');
 4751:         }
 4752:     }
 4753:     if (($cdom ne '') && ($cnum ne ''))  {
 4754:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4755:             my $then=$env{'user.login.time'};
 4756:             my $update=$env{'user.update.time'};
 4757:             if (!$update) {
 4758:                 $update = $then;
 4759:             }
 4760:             my @liveroles;
 4761:             foreach my $role ('dh','da') {
 4762:                 if ($env{"user.role.$role./$cdom/"}) {
 4763:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4764:                     my $limit = $update;
 4765:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4766:                         $limit = $then;
 4767:                     }
 4768:                     my $activerole = 1;
 4769:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4770:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4771:                     if ($activerole) {
 4772:                         push(@liveroles,$role);
 4773:                     }
 4774:                 }
 4775:             }
 4776:             if (@liveroles) {
 4777:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4778:                     my ($accessref,$accessinfo,%access_in_dom);
 4779:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4780:                     if (ref($roles_by_num) eq 'ARRAY') {
 4781:                         if (@{$roles_by_num}) {
 4782:                             my %settings;
 4783:                             if ($env{'request.course.id'} eq $cid) {
 4784:                                 foreach my $envkey (keys(%env)) {
 4785:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4786:                                         $settings{$1} = $env{$envkey};
 4787:                                     }
 4788:                                 }
 4789:                             } else {
 4790:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4791:                             }
 4792:                             my %setincrs;
 4793:                             if ($settings{'internal.adhocaccess'}) {
 4794:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4795:                             }
 4796:                             my @statuses;
 4797:                             if ($env{'environment.inststatus'}) {
 4798:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4799:                             }
 4800:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4801:                             if (ref($accessref) eq 'HASH') {
 4802:                                 %access_in_dom = %{$accessref};
 4803:                             }
 4804:                             foreach my $role (@{$roles_by_num}) {
 4805:                                 my ($curraccess,@okstatus,@personnel);
 4806:                                 if ($setincrs{$role}) {
 4807:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4808:                                     if ($curraccess eq 'status') {
 4809:                                         @okstatus = split(/\&/,$rest);
 4810:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4811:                                         @personnel = split(/\&/,$rest);
 4812:                                     }
 4813:                                 } else {
 4814:                                     $curraccess = $access_in_dom{$role};
 4815:                                     if (ref($accessinfo) eq 'HASH') {
 4816:                                         if ($curraccess eq 'status') {
 4817:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4818:                                                 @okstatus = @{$accessinfo->{$role}};
 4819:                                             }
 4820:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4821:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4822:                                                 @personnel = @{$accessinfo->{$role}};
 4823:                                             }
 4824:                                         }
 4825:                                     }
 4826:                                 }
 4827:                                 if ($curraccess eq 'none') {
 4828:                                     next;
 4829:                                 } elsif ($curraccess eq 'all') {
 4830:                                     push(@possroles,$role);
 4831:                                 } elsif ($curraccess eq 'dh') {
 4832:                                     if (grep(/^dh$/,@liveroles)) {
 4833:                                         push(@possroles,$role);
 4834:                                     } else {
 4835:                                         next;
 4836:                                     }
 4837:                                 } elsif ($curraccess eq 'da') {
 4838:                                     if (grep(/^da$/,@liveroles)) {
 4839:                                         push(@possroles,$role);
 4840:                                     } else {
 4841:                                         next;
 4842:                                     }
 4843:                                 } elsif ($curraccess eq 'status') {
 4844:                                     if (@okstatus) {
 4845:                                         if (!@statuses) {
 4846:                                             if (grep(/^default$/,@okstatus)) {
 4847:                                                 push(@possroles,$role);
 4848:                                             }
 4849:                                         } else {
 4850:                                             foreach my $status (@okstatus) {
 4851:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4852:                                                     push(@possroles,$role);
 4853:                                                     last;
 4854:                                                 }
 4855:                                             }
 4856:                                         }
 4857:                                     }
 4858:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4859:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4860:                                         if ($curraccess eq 'exc') {
 4861:                                             push(@possroles,$role);
 4862:                                         }
 4863:                                     } elsif ($curraccess eq 'inc') {
 4864:                                         push(@possroles,$role);
 4865:                                     }
 4866:                                 }
 4867:                             }
 4868:                         }
 4869:                     }
 4870:                 }
 4871:             }
 4872:         }
 4873:     }
 4874:     unless (ref($description) eq 'HASH') {
 4875:         if (ref($roles_by_num) eq 'ARRAY') {
 4876:             my %desc;
 4877:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4878:             $description = \%desc;
 4879:         } else {
 4880:             $description = {};
 4881:         }
 4882:     }
 4883:     return (\@possroles,$description);
 4884: }
 4885: 
 4886: # ----------------------------------------------------- Frontpage Announcements
 4887: #
 4888: #
 4889: 
 4890: sub postannounce {
 4891:     my ($server,$text)=@_;
 4892:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4893:     unless ($text=~/\w/) { $text=''; }
 4894:     return &reply('setannounce:'.&escape($text),$server);
 4895: }
 4896: 
 4897: sub getannounce {
 4898: 
 4899:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4900: 	my $announcement='';
 4901: 	while (my $line = <$fh>) { $announcement .= $line; }
 4902: 	close($fh);
 4903: 	if ($announcement=~/\w/) { 
 4904: 	    return 
 4905:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4906:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4907: 	} else {
 4908: 	    return '';
 4909: 	}
 4910:     } else {
 4911: 	return '';
 4912:     }
 4913: }
 4914: 
 4915: # ---------------------------------------------------------- Course ID routines
 4916: # Deal with domain's nohist_courseid.db files
 4917: #
 4918: 
 4919: sub courseidput {
 4920:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4921:     return unless (ref($storehash) eq 'HASH');
 4922:     my $outcome;
 4923:     if ($caller eq 'timeonly') {
 4924:         my $cids = '';
 4925:         foreach my $item (keys(%$storehash)) {
 4926:             $cids.=&escape($item).'&';
 4927:         }
 4928:         $cids=~s/\&$//;
 4929:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4930:                           $coursehome);       
 4931:     } else {
 4932:         my $items = '';
 4933:         foreach my $item (keys(%$storehash)) {
 4934:             $items.= &escape($item).'='.
 4935:                      &freeze_escape($$storehash{$item}).'&';
 4936:         }
 4937:         $items=~s/\&$//;
 4938:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4939:                           $coursehome);
 4940:     }
 4941:     if ($outcome eq 'unknown_cmd') {
 4942:         my $what;
 4943:         foreach my $cid (keys(%$storehash)) {
 4944:             $what .= &escape($cid).'=';
 4945:             foreach my $item ('description','inst_code','owner','type') {
 4946:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4947:             }
 4948:             $what =~ s/\:$/&/;
 4949:         }
 4950:         $what =~ s/\&$//;  
 4951:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4952:     } else {
 4953:         return $outcome;
 4954:     }
 4955: }
 4956: 
 4957: sub courseiddump {
 4958:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4959:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4960:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4961:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4962:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4963:     my $as_hash = 1;
 4964:     my %returnhash;
 4965:     if (!$domfilter) { $domfilter=''; }
 4966:     my %libserv = &all_library();
 4967:     foreach my $tryserver (keys(%libserv)) {
 4968:         if ( (  $hostidflag == 1 
 4969: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4970: 	     || (!defined($hostidflag)) ) {
 4971: 
 4972: 	    if (($domfilter eq '') ||
 4973: 		(&host_domain($tryserver) eq $domfilter)) {
 4974:                 my $rep;
 4975:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4976:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4977:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4978:                                 &escape($descfilter), &escape($instcodefilter), 
 4979:                                 &escape($ownerfilter), &escape($coursefilter),
 4980:                                 &escape($typefilter), &escape($regexp_ok), 
 4981:                                 $as_hash, &escape($selfenrollonly), 
 4982:                                 &escape($catfilter), $showhidden, $caller, 
 4983:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4984:                                 &escape($createdbefore), &escape($createdafter), 
 4985:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 4986:                                 $reqcrsdom,&escape($reqinstcode))));
 4987:                 } else {
 4988:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4989:                              $sincefilter.':'.&escape($descfilter).':'.
 4990:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4991:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4992:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4993:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4994:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4995:                              &escape($cc_clone).':'.$cloneonly.':'.
 4996:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4997:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 4998:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 4999:                 }
 5000:                      
 5001:                 my @pairs=split(/\&/,$rep);
 5002:                 foreach my $item (@pairs) {
 5003:                     my ($key,$value)=split(/\=/,$item,2);
 5004:                     $key = &unescape($key);
 5005:                     next if ($key =~ /^error: 2 /);
 5006:                     my $result = &thaw_unescape($value);
 5007:                     if (ref($result) eq 'HASH') {
 5008:                         $returnhash{$key}=$result;
 5009:                     } else {
 5010:                         my @responses = split(/:/,$value);
 5011:                         my @items = ('description','inst_code','owner','type');
 5012:                         for (my $i=0; $i<@responses; $i++) {
 5013:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5014:                         }
 5015:                     }
 5016:                 }
 5017:             }
 5018:         }
 5019:     }
 5020:     return %returnhash;
 5021: }
 5022: 
 5023: sub courselastaccess {
 5024:     my ($cdom,$cnum,$hostidref) = @_;
 5025:     my %returnhash;
 5026:     if ($cdom && $cnum) {
 5027:         my $chome = &homeserver($cnum,$cdom);
 5028:         if ($chome ne 'no_host') {
 5029:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5030:             &extract_lastaccess(\%returnhash,$rep);
 5031:         }
 5032:     } else {
 5033:         if (!$cdom) { $cdom=''; }
 5034:         my %libserv = &all_library();
 5035:         foreach my $tryserver (keys(%libserv)) {
 5036:             if (ref($hostidref) eq 'ARRAY') {
 5037:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5038:             } 
 5039:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5040:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5041:                 &extract_lastaccess(\%returnhash,$rep);
 5042:             }
 5043:         }
 5044:     }
 5045:     return %returnhash;
 5046: }
 5047: 
 5048: sub extract_lastaccess {
 5049:     my ($returnhash,$rep) = @_;
 5050:     if (ref($returnhash) eq 'HASH') {
 5051:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5052:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5053:                  $rep eq '') {
 5054:             my @pairs=split(/\&/,$rep);
 5055:             foreach my $item (@pairs) {
 5056:                 my ($key,$value)=split(/\=/,$item,2);
 5057:                 $key = &unescape($key);
 5058:                 next if ($key =~ /^error: 2 /);
 5059:                 $returnhash->{$key} = &thaw_unescape($value);
 5060:             }
 5061:         }
 5062:     }
 5063:     return;
 5064: }
 5065: 
 5066: # ---------------------------------------------------------- DC e-mail
 5067: 
 5068: sub dcmailput {
 5069:     my ($domain,$msgid,$message,$server)=@_;
 5070:     my $status = &Apache::lonnet::critical(
 5071:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5072:        &escape($message),$server);
 5073:     return $status;
 5074: }
 5075: 
 5076: sub dcmaildump {
 5077:     my ($dom,$startdate,$enddate,$senders) = @_;
 5078:     my %returnhash=();
 5079: 
 5080:     if (defined(&domain($dom,'primary'))) {
 5081:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5082:                                                          &escape($enddate).':';
 5083: 	my @esc_senders=map { &escape($_)} @$senders;
 5084: 	$cmd.=&escape(join('&',@esc_senders));
 5085: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5086:             my ($key,$value) = split(/\=/,$line,2);
 5087:             if (($key) && ($value)) {
 5088:                 $returnhash{&unescape($key)} = &unescape($value);
 5089:             }
 5090:         }
 5091:     }
 5092:     return %returnhash;
 5093: }
 5094: # ---------------------------------------------------------- Domain roles
 5095: 
 5096: sub get_domain_roles {
 5097:     my ($dom,$roles,$startdate,$enddate)=@_;
 5098:     if ((!defined($startdate)) || ($startdate eq '')) {
 5099:         $startdate = '.';
 5100:     }
 5101:     if ((!defined($enddate)) || ($enddate eq '')) {
 5102:         $enddate = '.';
 5103:     }
 5104:     my $rolelist;
 5105:     if (ref($roles) eq 'ARRAY') {
 5106:         $rolelist = join('&',@{$roles});
 5107:     }
 5108:     my %personnel = ();
 5109: 
 5110:     my %servers = &get_servers($dom,'library');
 5111:     foreach my $tryserver (keys(%servers)) {
 5112: 	%{$personnel{$tryserver}}=();
 5113: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5114: 					    &escape($startdate).':'.
 5115: 					    &escape($enddate).':'.
 5116: 					    &escape($rolelist), $tryserver))) {
 5117: 	    my ($key,$value) = split(/\=/,$line,2);
 5118: 	    if (($key) && ($value)) {
 5119: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5120: 	    }
 5121: 	}
 5122:     }
 5123:     return %personnel;
 5124: }
 5125: 
 5126: sub get_active_domroles {
 5127:     my ($dom,$roles) = @_;
 5128:     return () unless (ref($roles) eq 'ARRAY');
 5129:     my $now = time;
 5130:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5131:     my %domroles;
 5132:     foreach my $server (keys(%dompersonnel)) {
 5133:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5134:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5135:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5136:         }
 5137:     }
 5138:     return %domroles;
 5139: }
 5140: 
 5141: # ----------------------------------------------------------- Interval timing 
 5142: 
 5143: {
 5144: # Caches needed for speedup of navmaps
 5145: # We don't want to cache this for very long at all (5 seconds at most)
 5146: # 
 5147: # The user for whom we cache
 5148: my $cachedkey='';
 5149: # The cached times for this user
 5150: my %cachedtimes=();
 5151: # When this was last done
 5152: my $cachedtime='';
 5153: 
 5154: sub load_all_first_access {
 5155:     my ($uname,$udom,$ignorecache)=@_;
 5156:     if (($cachedkey eq $uname.':'.$udom) &&
 5157:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5158:         (!$ignorecache)) {
 5159:         return;
 5160:     }
 5161:     $cachedtime=time;
 5162:     $cachedkey=$uname.':'.$udom;
 5163:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5164: }
 5165: 
 5166: sub get_first_access {
 5167:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5168:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5169:     if ($argsymb) { $symb=$argsymb; }
 5170:     my ($map,$id,$res)=&decode_symb($symb);
 5171:     if ($argmap) { $map = $argmap; }
 5172:     if ($type eq 'course') {
 5173: 	$res='course';
 5174:     } elsif ($type eq 'map') {
 5175: 	$res=&symbread($map);
 5176:     } else {
 5177: 	$res=$symb;
 5178:     }
 5179:     &load_all_first_access($uname,$udom,$ignorecache);
 5180:     return $cachedtimes{"$courseid\0$res"};
 5181: }
 5182: 
 5183: sub set_first_access {
 5184:     my ($type,$interval)=@_;
 5185:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5186:     my ($map,$id,$res)=&decode_symb($symb);
 5187:     if ($type eq 'course') {
 5188: 	$res='course';
 5189:     } elsif ($type eq 'map') {
 5190: 	$res=&symbread($map);
 5191:     } else {
 5192: 	$res=$symb;
 5193:     }
 5194:     $cachedkey='';
 5195:     my $firstaccess=&get_first_access($type,$symb,$map);
 5196:     if (!$firstaccess) {
 5197:         my $start = time;
 5198: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5199:                           $udom,$uname);
 5200:         if ($putres eq 'ok') {
 5201:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5202:                  $udom,$uname); 
 5203:             &appenv(
 5204:                      {
 5205:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5206:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5207:                      }
 5208:                   );
 5209:         }
 5210:         return $putres;
 5211:     }
 5212:     return 'already_set';
 5213: }
 5214: }
 5215: 
 5216: # --------------------------------------------- Set Expire Date for Spreadsheet
 5217: 
 5218: sub expirespread {
 5219:     my ($uname,$udom,$stype,$usymb)=@_;
 5220:     my $cid=$env{'request.course.id'}; 
 5221:     if ($cid) {
 5222:        my $now=time;
 5223:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5224:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5225:                             $env{'course.'.$cid.'.num'}.
 5226: 	        	    ':nohist_expirationdates:'.
 5227:                             &escape($key).'='.$now,
 5228:                             $env{'course.'.$cid.'.home'})
 5229:     }
 5230:     return 'ok';
 5231: }
 5232: 
 5233: # ----------------------------------------------------- Devalidate Spreadsheets
 5234: 
 5235: sub devalidate {
 5236:     my ($symb,$uname,$udom)=@_;
 5237:     my $cid=$env{'request.course.id'}; 
 5238:     if ($cid) {
 5239:         # delete the stored spreadsheets for
 5240:         # - the student level sheet of this user in course's homespace
 5241:         # - the assessment level sheet for this resource 
 5242:         #   for this user in user's homespace
 5243: 	# - current conditional state info
 5244: 	my $key=$uname.':'.$udom.':';
 5245:         my $status=
 5246: 	    &del('nohist_calculatedsheets',
 5247: 		 [$key.'studentcalc:'],
 5248: 		 $env{'course.'.$cid.'.domain'},
 5249: 		 $env{'course.'.$cid.'.num'})
 5250: 		.' '.
 5251: 	    &del('nohist_calculatedsheets_'.$cid,
 5252: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5253:         unless ($status eq 'ok ok') {
 5254:            &logthis('Could not devalidate spreadsheet '.
 5255:                     $uname.' at '.$udom.' for '.
 5256: 		    $symb.': '.$status);
 5257:         }
 5258: 	&delenv('user.state.'.$cid);
 5259:     }
 5260: }
 5261: 
 5262: sub get_scalar {
 5263:     my ($string,$end) = @_;
 5264:     my $value;
 5265:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5266: 	$value = $1;
 5267:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5268: 	$value = $1;
 5269:     }
 5270:     return &unescape($value);
 5271: }
 5272: 
 5273: sub array2str {
 5274:   my (@array) = @_;
 5275:   my $result=&arrayref2str(\@array);
 5276:   $result=~s/^__ARRAY_REF__//;
 5277:   $result=~s/__END_ARRAY_REF__$//;
 5278:   return $result;
 5279: }
 5280: 
 5281: sub arrayref2str {
 5282:   my ($arrayref) = @_;
 5283:   my $result='__ARRAY_REF__';
 5284:   foreach my $elem (@$arrayref) {
 5285:     if(ref($elem) eq 'ARRAY') {
 5286:       $result.=&arrayref2str($elem).'&';
 5287:     } elsif(ref($elem) eq 'HASH') {
 5288:       $result.=&hashref2str($elem).'&';
 5289:     } elsif(ref($elem)) {
 5290:       #print("Got a ref of ".(ref($elem))." skipping.");
 5291:     } else {
 5292:       $result.=&escape($elem).'&';
 5293:     }
 5294:   }
 5295:   $result=~s/\&$//;
 5296:   $result .= '__END_ARRAY_REF__';
 5297:   return $result;
 5298: }
 5299: 
 5300: sub hash2str {
 5301:   my (%hash) = @_;
 5302:   my $result=&hashref2str(\%hash);
 5303:   $result=~s/^__HASH_REF__//;
 5304:   $result=~s/__END_HASH_REF__$//;
 5305:   return $result;
 5306: }
 5307: 
 5308: sub hashref2str {
 5309:   my ($hashref)=@_;
 5310:   my $result='__HASH_REF__';
 5311:   foreach my $key (sort(keys(%$hashref))) {
 5312:     if (ref($key) eq 'ARRAY') {
 5313:       $result.=&arrayref2str($key).'=';
 5314:     } elsif (ref($key) eq 'HASH') {
 5315:       $result.=&hashref2str($key).'=';
 5316:     } elsif (ref($key)) {
 5317:       $result.='=';
 5318:       #print("Got a ref of ".(ref($key))." skipping.");
 5319:     } else {
 5320: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5321:     }
 5322: 
 5323:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5324:       $result.=&arrayref2str($hashref->{$key}).'&';
 5325:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5326:       $result.=&hashref2str($hashref->{$key}).'&';
 5327:     } elsif(ref($hashref->{$key})) {
 5328:        $result.='&';
 5329:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5330:     } else {
 5331:       $result.=&escape($hashref->{$key}).'&';
 5332:     }
 5333:   }
 5334:   $result=~s/\&$//;
 5335:   $result .= '__END_HASH_REF__';
 5336:   return $result;
 5337: }
 5338: 
 5339: sub str2hash {
 5340:     my ($string)=@_;
 5341:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5342:     return %$hash;
 5343: }
 5344: 
 5345: sub str2hashref {
 5346:   my ($string) = @_;
 5347: 
 5348:   my %hash;
 5349: 
 5350:   if($string !~ /^__HASH_REF__/) {
 5351:       if (! ($string eq '' || !defined($string))) {
 5352: 	  $hash{'error'}='Not hash reference';
 5353:       }
 5354:       return (\%hash, $string);
 5355:   }
 5356: 
 5357:   $string =~ s/^__HASH_REF__//;
 5358: 
 5359:   while($string !~ /^__END_HASH_REF__/) {
 5360:       #key
 5361:       my $key='';
 5362:       if($string =~ /^__HASH_REF__/) {
 5363:           ($key, $string)=&str2hashref($string);
 5364:           if(defined($key->{'error'})) {
 5365:               $hash{'error'}='Bad data';
 5366:               return (\%hash, $string);
 5367:           }
 5368:       } elsif($string =~ /^__ARRAY_REF__/) {
 5369:           ($key, $string)=&str2arrayref($string);
 5370:           if($key->[0] eq 'Array reference error') {
 5371:               $hash{'error'}='Bad data';
 5372:               return (\%hash, $string);
 5373:           }
 5374:       } else {
 5375:           $string =~ s/^(.*?)=//;
 5376: 	  $key=&unescape($1);
 5377:       }
 5378:       $string =~ s/^=//;
 5379: 
 5380:       #value
 5381:       my $value='';
 5382:       if($string =~ /^__HASH_REF__/) {
 5383:           ($value, $string)=&str2hashref($string);
 5384:           if(defined($value->{'error'})) {
 5385:               $hash{'error'}='Bad data';
 5386:               return (\%hash, $string);
 5387:           }
 5388:       } elsif($string =~ /^__ARRAY_REF__/) {
 5389:           ($value, $string)=&str2arrayref($string);
 5390:           if($value->[0] eq 'Array reference error') {
 5391:               $hash{'error'}='Bad data';
 5392:               return (\%hash, $string);
 5393:           }
 5394:       } else {
 5395: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5396:       }
 5397:       $string =~ s/^&//;
 5398: 
 5399:       $hash{$key}=$value;
 5400:   }
 5401: 
 5402:   $string =~ s/^__END_HASH_REF__//;
 5403: 
 5404:   return (\%hash, $string);
 5405: }
 5406: 
 5407: sub str2array {
 5408:     my ($string)=@_;
 5409:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5410:     return @$array;
 5411: }
 5412: 
 5413: sub str2arrayref {
 5414:   my ($string) = @_;
 5415:   my @array;
 5416: 
 5417:   if($string !~ /^__ARRAY_REF__/) {
 5418:       if (! ($string eq '' || !defined($string))) {
 5419: 	  $array[0]='Array reference error';
 5420:       }
 5421:       return (\@array, $string);
 5422:   }
 5423: 
 5424:   $string =~ s/^__ARRAY_REF__//;
 5425: 
 5426:   while($string !~ /^__END_ARRAY_REF__/) {
 5427:       my $value='';
 5428:       if($string =~ /^__HASH_REF__/) {
 5429:           ($value, $string)=&str2hashref($string);
 5430:           if(defined($value->{'error'})) {
 5431:               $array[0] ='Array reference error';
 5432:               return (\@array, $string);
 5433:           }
 5434:       } elsif($string =~ /^__ARRAY_REF__/) {
 5435:           ($value, $string)=&str2arrayref($string);
 5436:           if($value->[0] eq 'Array reference error') {
 5437:               $array[0] ='Array reference error';
 5438:               return (\@array, $string);
 5439:           }
 5440:       } else {
 5441: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5442:       }
 5443:       $string =~ s/^&//;
 5444: 
 5445:       push(@array, $value);
 5446:   }
 5447: 
 5448:   $string =~ s/^__END_ARRAY_REF__//;
 5449: 
 5450:   return (\@array, $string);
 5451: }
 5452: 
 5453: # -------------------------------------------------------------------Temp Store
 5454: 
 5455: sub tmpreset {
 5456:   my ($symb,$namespace,$domain,$stuname) = @_;
 5457:   if (!$symb) {
 5458:     $symb=&symbread();
 5459:     if (!$symb) { $symb= $env{'request.url'}; }
 5460:   }
 5461:   $symb=escape($symb);
 5462: 
 5463:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5464:   $namespace=~s/\//\_/g;
 5465:   $namespace=~s/\W//g;
 5466: 
 5467:   if (!$domain) { $domain=$env{'user.domain'}; }
 5468:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5469:   if ($domain eq 'public' && $stuname eq 'public') {
 5470:       $stuname=$ENV{'REMOTE_ADDR'};
 5471:   }
 5472:   my $path=LONCAPA::tempdir();
 5473:   my %hash;
 5474:   if (tie(%hash,'GDBM_File',
 5475: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5476: 	  &GDBM_WRCREAT(),0640)) {
 5477:     foreach my $key (keys(%hash)) {
 5478:       if ($key=~ /:$symb/) {
 5479: 	delete($hash{$key});
 5480:       }
 5481:     }
 5482:   }
 5483: }
 5484: 
 5485: sub tmpstore {
 5486:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5487: 
 5488:   if (!$symb) {
 5489:     $symb=&symbread();
 5490:     if (!$symb) { $symb= $env{'request.url'}; }
 5491:   }
 5492:   $symb=escape($symb);
 5493: 
 5494:   if (!$namespace) {
 5495:     # I don't think we would ever want to store this for a course.
 5496:     # it seems this will only be used if we don't have a course.
 5497:     #$namespace=$env{'request.course.id'};
 5498:     #if (!$namespace) {
 5499:       $namespace=$env{'request.state'};
 5500:     #}
 5501:   }
 5502:   $namespace=~s/\//\_/g;
 5503:   $namespace=~s/\W//g;
 5504:   if (!$domain) { $domain=$env{'user.domain'}; }
 5505:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5506:   if ($domain eq 'public' && $stuname eq 'public') {
 5507:       $stuname=$ENV{'REMOTE_ADDR'};
 5508:   }
 5509:   my $now=time;
 5510:   my %hash;
 5511:   my $path=LONCAPA::tempdir();
 5512:   if (tie(%hash,'GDBM_File',
 5513: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5514: 	  &GDBM_WRCREAT(),0640)) {
 5515:     $hash{"version:$symb"}++;
 5516:     my $version=$hash{"version:$symb"};
 5517:     my $allkeys=''; 
 5518:     foreach my $key (keys(%$storehash)) {
 5519:       $allkeys.=$key.':';
 5520:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5521:     }
 5522:     $hash{"$version:$symb:timestamp"}=$now;
 5523:     $allkeys.='timestamp';
 5524:     $hash{"$version:keys:$symb"}=$allkeys;
 5525:     if (untie(%hash)) {
 5526:       return 'ok';
 5527:     } else {
 5528:       return "error:$!";
 5529:     }
 5530:   } else {
 5531:     return "error:$!";
 5532:   }
 5533: }
 5534: 
 5535: # -----------------------------------------------------------------Temp Restore
 5536: 
 5537: sub tmprestore {
 5538:   my ($symb,$namespace,$domain,$stuname) = @_;
 5539: 
 5540:   if (!$symb) {
 5541:     $symb=&symbread();
 5542:     if (!$symb) { $symb= $env{'request.url'}; }
 5543:   }
 5544:   $symb=escape($symb);
 5545: 
 5546:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5547: 
 5548:   if (!$domain) { $domain=$env{'user.domain'}; }
 5549:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5550:   if ($domain eq 'public' && $stuname eq 'public') {
 5551:       $stuname=$ENV{'REMOTE_ADDR'};
 5552:   }
 5553:   my %returnhash;
 5554:   $namespace=~s/\//\_/g;
 5555:   $namespace=~s/\W//g;
 5556:   my %hash;
 5557:   my $path=LONCAPA::tempdir();
 5558:   if (tie(%hash,'GDBM_File',
 5559: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5560: 	  &GDBM_READER(),0640)) {
 5561:     my $version=$hash{"version:$symb"};
 5562:     $returnhash{'version'}=$version;
 5563:     my $scope;
 5564:     for ($scope=1;$scope<=$version;$scope++) {
 5565:       my $vkeys=$hash{"$scope:keys:$symb"};
 5566:       my @keys=split(/:/,$vkeys);
 5567:       my $key;
 5568:       $returnhash{"$scope:keys"}=$vkeys;
 5569:       foreach $key (@keys) {
 5570: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5571: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5572:       }
 5573:     }
 5574:     if (!(untie(%hash))) {
 5575:       return "error:$!";
 5576:     }
 5577:   } else {
 5578:     return "error:$!";
 5579:   }
 5580:   return %returnhash;
 5581: }
 5582: 
 5583: # ----------------------------------------------------------------------- Store
 5584: 
 5585: sub store {
 5586:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5587:     my $home='';
 5588: 
 5589:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5590: 
 5591:     $symb=&symbclean($symb);
 5592:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5593: 
 5594:     if (!$domain) { $domain=$env{'user.domain'}; }
 5595:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5596: 
 5597:     &devalidate($symb,$stuname,$domain);
 5598: 
 5599:     $symb=escape($symb);
 5600:     if (!$namespace) { 
 5601:        unless ($namespace=$env{'request.course.id'}) { 
 5602:           return ''; 
 5603:        } 
 5604:     }
 5605:     if (!$home) { $home=$env{'user.home'}; }
 5606: 
 5607:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5608:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5609: 
 5610:     my $namevalue='';
 5611:     foreach my $key (keys(%$storehash)) {
 5612:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5613:     }
 5614:     $namevalue=~s/\&$//;
 5615:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5616:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5617: }
 5618: 
 5619: # -------------------------------------------------------------- Critical Store
 5620: 
 5621: sub cstore {
 5622:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5623:     my $home='';
 5624: 
 5625:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5626: 
 5627:     $symb=&symbclean($symb);
 5628:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5629: 
 5630:     if (!$domain) { $domain=$env{'user.domain'}; }
 5631:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5632: 
 5633:     &devalidate($symb,$stuname,$domain);
 5634: 
 5635:     $symb=escape($symb);
 5636:     if (!$namespace) { 
 5637:        unless ($namespace=$env{'request.course.id'}) { 
 5638:           return ''; 
 5639:        } 
 5640:     }
 5641:     if (!$home) { $home=$env{'user.home'}; }
 5642: 
 5643:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5644:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5645: 
 5646:     my $namevalue='';
 5647:     foreach my $key (keys(%$storehash)) {
 5648:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5649:     }
 5650:     $namevalue=~s/\&$//;
 5651:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5652:     return critical
 5653:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5654: }
 5655: 
 5656: # --------------------------------------------------------------------- Restore
 5657: 
 5658: sub restore {
 5659:     my ($symb,$namespace,$domain,$stuname) = @_;
 5660:     my $home='';
 5661: 
 5662:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5663: 
 5664:     if (!$symb) {
 5665:         return if ($namespace eq 'courserequests');
 5666:         unless ($symb=escape(&symbread())) { return ''; }
 5667:     } else {
 5668:         unless ($namespace eq 'courserequests') {
 5669:             $symb=&escape(&symbclean($symb));
 5670:         }
 5671:     }
 5672:     if (!$namespace) { 
 5673:        unless ($namespace=$env{'request.course.id'}) { 
 5674:           return ''; 
 5675:        } 
 5676:     }
 5677:     if (!$domain) { $domain=$env{'user.domain'}; }
 5678:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5679:     if (!$home) { $home=$env{'user.home'}; }
 5680:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5681: 
 5682:     my %returnhash=();
 5683:     foreach my $line (split(/\&/,$answer)) {
 5684: 	my ($name,$value)=split(/\=/,$line);
 5685:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5686:     }
 5687:     my $version;
 5688:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5689:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5690:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5691:        }
 5692:     }
 5693:     return %returnhash;
 5694: }
 5695: 
 5696: # ---------------------------------------------------------- Course Description
 5697: #
 5698: #  
 5699: 
 5700: sub coursedescription {
 5701:     my ($courseid,$args)=@_;
 5702:     $courseid=~s/^\///;
 5703:     $courseid=~s/\_/\//g;
 5704:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5705:     my $chome=&homeserver($cnum,$cdomain);
 5706:     my $normalid=$cdomain.'_'.$cnum;
 5707:     # need to always cache even if we get errors otherwise we keep 
 5708:     # trying and trying and trying to get the course description.
 5709:     my %envhash=();
 5710:     my %returnhash=();
 5711:     
 5712:     my $expiretime=600;
 5713:     if ($env{'request.course.id'} eq $normalid) {
 5714: 	$expiretime=120;
 5715:     }
 5716: 
 5717:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5718:     if (!$args->{'freshen_cache'}
 5719: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5720: 	foreach my $key (keys(%env)) {
 5721: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5722: 	    my ($setting) = $1;
 5723: 	    $returnhash{$setting} = $env{$key};
 5724: 	}
 5725: 	return %returnhash;
 5726:     }
 5727: 
 5728:     # get the data again
 5729: 
 5730:     if (!$args->{'one_time'}) {
 5731: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5732:     }
 5733: 
 5734:     if ($chome ne 'no_host') {
 5735:        %returnhash=&dump('environment',$cdomain,$cnum);
 5736:        if (!exists($returnhash{'con_lost'})) {
 5737: 	   my $username = $env{'user.name'}; # Defult username
 5738: 	   if(defined $args->{'user'}) {
 5739: 	       $username = $args->{'user'};
 5740: 	   }
 5741:            $returnhash{'home'}= $chome;
 5742: 	   $returnhash{'domain'} = $cdomain;
 5743: 	   $returnhash{'num'} = $cnum;
 5744:            if (!defined($returnhash{'type'})) {
 5745:                $returnhash{'type'} = 'Course';
 5746:            }
 5747:            while (my ($name,$value) = each %returnhash) {
 5748:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5749:            }
 5750:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5751:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5752: 	       $username.'_'.$cdomain.'_'.$cnum;
 5753:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5754:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5755:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5756:        }
 5757:     }
 5758:     if (!$args->{'one_time'}) {
 5759: 	&appenv(\%envhash);
 5760:     }
 5761:     return %returnhash;
 5762: }
 5763: 
 5764: sub update_released_required {
 5765:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5766:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5767:         $cid = $env{'request.course.id'};
 5768:         $cdom = $env{'course.'.$cid.'.domain'};
 5769:         $cnum = $env{'course.'.$cid.'.num'};
 5770:         $chome = $env{'course.'.$cid.'.home'};
 5771:     }
 5772:     if ($needsrelease) {
 5773:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5774:         my $needsupdate;
 5775:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5776:             $needsupdate = 1;
 5777:         } else {
 5778:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5779:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5780:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5781:                 $needsupdate = 1;
 5782:             }
 5783:         }
 5784:         if ($needsupdate) {
 5785:             my %needshash = (
 5786:                              'internal.releaserequired' => $needsrelease,
 5787:                             );
 5788:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5789:             if ($putresult eq 'ok') {
 5790:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5791:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5792:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5793:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5794:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5795:                 }
 5796:             }
 5797:         }
 5798:     }
 5799:     return;
 5800: }
 5801: 
 5802: # -------------------------------------------------See if a user is privileged
 5803: 
 5804: sub privileged {
 5805:     my ($username,$domain,$possdomains,$possroles)=@_;
 5806:     my $now = time;
 5807:     my $roles;
 5808:     if (ref($possroles) eq 'ARRAY') {
 5809:         $roles = $possroles; 
 5810:     } else {
 5811:         $roles = ['dc','su'];
 5812:     }
 5813:     if (ref($possdomains) eq 'ARRAY') {
 5814:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5815:         foreach my $dom (@{$possdomains}) {
 5816:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5817:                 (ref($privileged{$dom}) eq 'HASH')) {
 5818:                 foreach my $role (@{$roles}) {
 5819:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5820:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5821:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5822:                             return 1 unless (($end && $end < $now) ||
 5823:                                              ($start && $start > $now));
 5824:                         }
 5825:                     }
 5826:                 }
 5827:             }
 5828:         }
 5829:     } else {
 5830:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5831:         my $now = time;
 5832: 
 5833:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5834:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5835:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5836:                 return 1 unless ($tend && $tend < $now) 
 5837:                         or ($tstart && $tstart > $now);
 5838:             }
 5839:         }
 5840:     }
 5841:     return 0;
 5842: }
 5843: 
 5844: sub privileged_by_domain {
 5845:     my ($domains,$roles) = @_;
 5846:     my %privileged = ();
 5847:     my $cachetime = 60*60*24;
 5848:     my $now = time;
 5849:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5850:         return %privileged;
 5851:     }
 5852:     foreach my $dom (@{$domains}) {
 5853:         next if (ref($privileged{$dom}) eq 'HASH');
 5854:         my $needroles;
 5855:         foreach my $role (@{$roles}) {
 5856:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5857:             if (defined($cached)) {
 5858:                 if (ref($result) eq 'HASH') {
 5859:                     $privileged{$dom}{$role} = $result;
 5860:                 }
 5861:             } else {
 5862:                 $needroles = 1;
 5863:             }
 5864:         }
 5865:         if ($needroles) {
 5866:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5867:             $privileged{$dom} = {};
 5868:             foreach my $server (keys(%dompersonnel)) {
 5869:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5870:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5871:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5872:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5873:                         next if ($end && $end < $now);
 5874:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5875:                             $dompersonnel{$server}{$item};
 5876:                     }
 5877:                 }
 5878:             }
 5879:             if (ref($privileged{$dom}) eq 'HASH') {
 5880:                 foreach my $role (@{$roles}) {
 5881:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5882:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5883:                     } else {
 5884:                         my %hash = ();
 5885:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5886:                     }
 5887:                 }
 5888:             }
 5889:         }
 5890:     }
 5891:     return %privileged;
 5892: }
 5893: 
 5894: # -------------------------------------------------------- Get user privileges
 5895: 
 5896: sub rolesinit {
 5897:     my ($domain, $username) = @_;
 5898:     my %userroles = ('user.login.time' => time);
 5899:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5900: 
 5901:     # firstaccess and timerinterval are related to timed maps/resources. 
 5902:     # also, blocking can be triggered by an activating timer
 5903:     # it's saved in the user's %env.
 5904:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5905:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5906:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5907:         %timerintchk, %timerintenv);
 5908: 
 5909:     foreach my $key (keys(%firstaccess)) {
 5910:         my ($cid, $rest) = split(/\0/, $key);
 5911:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5912:     }
 5913: 
 5914:     foreach my $key (keys(%timerinterval)) {
 5915:         my ($cid,$rest) = split(/\0/,$key);
 5916:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5917:     }
 5918: 
 5919:     my %allroles=();
 5920:     my %allgroups=();
 5921: 
 5922:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5923:         my $role = $rolesdump{$area};
 5924:         $area =~ s/\_\w\w$//;
 5925: 
 5926:         my ($trole, $tend, $tstart, $group_privs);
 5927: 
 5928:         if ($role =~ /^cr/) {
 5929:         # Custom role, defined by a user 
 5930:         # e.g., user.role.cr/msu/smith/mynewrole
 5931:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5932:                 $trole = $1;
 5933:                 ($tend, $tstart) = split('_', $2);
 5934:             } else {
 5935:                 $trole = $role;
 5936:             }
 5937:         } elsif ($role =~ m|^gr/|) {
 5938:         # Role of member in a group, defined within a course/community
 5939:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5940:             ($trole, $tend, $tstart) = split(/_/, $role);
 5941:             next if $tstart eq '-1';
 5942:             ($trole, $group_privs) = split(/\//, $trole);
 5943:             $group_privs = &unescape($group_privs);
 5944:         } else {
 5945:         # Just a normal role, defined in roles.tab
 5946:             ($trole, $tend, $tstart) = split(/_/,$role);
 5947:         }
 5948: 
 5949:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5950:                  $username);
 5951:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5952: 
 5953:         # role expired or not available yet?
 5954:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5955:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5956: 
 5957:         next if $area eq '' or $trole eq '';
 5958: 
 5959:         my $spec = "$trole.$area";
 5960:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5961: 
 5962:         if ($trole =~ /^cr\//) {
 5963:         # Custom role, defined by a user
 5964:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5965:         } elsif ($trole eq 'gr') {
 5966:         # Role of a member in a group, defined within a course/community
 5967:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5968:             next;
 5969:         } else {
 5970:         # Normal role, defined in roles.tab
 5971:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5972:         }
 5973: 
 5974:         my $cid = $tdomain.'_'.$trest;
 5975:         unless ($firstaccchk{$cid}) {
 5976:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5977:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5978:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5979:                         $coursetimerstarts{$cid}{$item}; 
 5980:                 }
 5981:             }
 5982:             $firstaccchk{$cid} = 1;
 5983:         }
 5984:         unless ($timerintchk{$cid}) {
 5985:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5986:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5987:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5988:                        $coursetimerintervals{$cid}{$item};
 5989:                 }
 5990:             }
 5991:             $timerintchk{$cid} = 1;
 5992:         }
 5993:     }
 5994: 
 5995:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 5996:                                                           \%allroles, \%allgroups);
 5997:     $env{'user.adv'} = $userroles{'user.adv'};
 5998:     $env{'user.rar'} = $userroles{'user.rar'};
 5999: 
 6000:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6001: }
 6002: 
 6003: sub set_arearole {
 6004:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6005:     unless ($nolog) {
 6006: # log the associated role with the area
 6007:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6008:     }
 6009:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6010: }
 6011: 
 6012: sub custom_roleprivs {
 6013:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6014:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6015:     my $homsvr = &homeserver($rauthor,$rdomain);
 6016:     if (&hostname($homsvr) ne '') {
 6017:         my ($rdummy,$roledef)=
 6018:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6019:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6020:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6021:             if (defined($syspriv)) {
 6022:                 if ($trest =~ /^$match_community$/) {
 6023:                     $syspriv =~ s/bre\&S//; 
 6024:                 }
 6025:                 $$allroles{'cm./'}.=':'.$syspriv;
 6026:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6027:             }
 6028:             if ($tdomain ne '') {
 6029:                 if (defined($dompriv)) {
 6030:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6031:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6032:                 }
 6033:                 if (($trest ne '') && (defined($coursepriv))) {
 6034:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6035:                         my $rolename = $1;
 6036:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6037:                     }
 6038:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6039:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6040:                 }
 6041:             }
 6042:         }
 6043:     }
 6044: }
 6045: 
 6046: sub course_adhocrole_privs {
 6047:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6048:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6049:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6050:         my (%currprivs,%storeprivs);
 6051:         foreach my $item (split(/:/,$coursepriv)) {
 6052:             my ($priv,$restrict) = split(/\&/,$item);
 6053:             $currprivs{$priv} = $restrict;
 6054:         }
 6055:         my (%possadd,%possremove,%full);
 6056:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6057:             my ($priv,$restrict)=split(/\&/,$item);
 6058:             $full{$priv} = $restrict;
 6059:         }
 6060:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6061:              next if ($item eq '');
 6062:              my ($rule,$rest) = split(/=/,$item);
 6063:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6064:              foreach my $priv (split(/:/,$rest)) {
 6065:                  if ($priv ne '') {
 6066:                      if ($rule eq 'off') {
 6067:                          $possremove{$priv} = 1;
 6068:                      } else {
 6069:                          $possadd{$priv} = 1;
 6070:                      }
 6071:                  }
 6072:              }
 6073:          }
 6074:          foreach my $priv (sort(keys(%full))) {
 6075:              if (exists($currprivs{$priv})) {
 6076:                  unless (exists($possremove{$priv})) {
 6077:                      $storeprivs{$priv} = $currprivs{$priv};
 6078:                  }
 6079:              } elsif (exists($possadd{$priv})) {
 6080:                  $storeprivs{$priv} = $full{$priv};
 6081:              }
 6082:          }
 6083:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6084:      }
 6085:      return $coursepriv;
 6086: }
 6087: 
 6088: sub group_roleprivs {
 6089:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6090:     my $access = 1;
 6091:     my $now = time;
 6092:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6093:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6094:     if ($access) {
 6095:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6096:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6097:     }
 6098: }
 6099: 
 6100: sub standard_roleprivs {
 6101:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6102:     if (defined($pr{$trole.':s'})) {
 6103:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6104:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6105:     }
 6106:     if ($tdomain ne '') {
 6107:         if (defined($pr{$trole.':d'})) {
 6108:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6109:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6110:         }
 6111:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6112:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6113:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6114:         }
 6115:     }
 6116: }
 6117: 
 6118: sub set_userprivs {
 6119:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6120:     my $author=0;
 6121:     my $adv=0;
 6122:     my $rar=0;
 6123:     my %grouproles = ();
 6124:     if (keys(%{$allgroups}) > 0) {
 6125:         my @groupkeys; 
 6126:         foreach my $role (keys(%{$allroles})) {
 6127:             push(@groupkeys,$role);
 6128:         }
 6129:         if (ref($groups_roles) eq 'HASH') {
 6130:             foreach my $key (keys(%{$groups_roles})) {
 6131:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6132:                     push(@groupkeys,$key);
 6133:                 }
 6134:             }
 6135:         }
 6136:         if (@groupkeys > 0) {
 6137:             foreach my $role (@groupkeys) {
 6138:                 my ($trole,$area,$sec,$extendedarea);
 6139:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6140:                     $trole = $1;
 6141:                     $area = $2;
 6142:                     $sec = $3;
 6143:                     $extendedarea = $area.$sec;
 6144:                     if (exists($$allgroups{$area})) {
 6145:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6146:                             my $spec = $trole.'.'.$extendedarea;
 6147:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6148:                                                 $$allgroups{$area}{$group};
 6149:                         }
 6150:                     }
 6151:                 }
 6152:             }
 6153:         }
 6154:     }
 6155:     foreach my $group (keys(%grouproles)) {
 6156:         $$allroles{$group} = $grouproles{$group};
 6157:     }
 6158:     foreach my $role (keys(%{$allroles})) {
 6159:         my %thesepriv;
 6160:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6161:         foreach my $item (split(/:/,$$allroles{$role})) {
 6162:             if ($item ne '') {
 6163:                 my ($privilege,$restrictions)=split(/&/,$item);
 6164:                 if ($restrictions eq '') {
 6165:                     $thesepriv{$privilege}='F';
 6166:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6167:                     $thesepriv{$privilege}.=$restrictions;
 6168:                 }
 6169:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6170:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6171:             }
 6172:         }
 6173:         my $thesestr='';
 6174:         foreach my $priv (sort(keys(%thesepriv))) {
 6175: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6176: 	}
 6177:         $userroles->{'user.priv.'.$role} = $thesestr;
 6178:     }
 6179:     return ($author,$adv,$rar);
 6180: }
 6181: 
 6182: sub role_status {
 6183:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6184:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6185:         my ($one,$two) = split(m{\./},$rolekey,2);
 6186:         (undef,undef,$$role) = split(/\./,$one,3);
 6187:         unless (!defined($$role) || $$role eq '') {
 6188:             $$where = '/'.$two;
 6189:             $$trolecode=$$role.'.'.$$where;
 6190:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6191:             $$tstatus='is';
 6192:             if ($$tstart && $$tstart>$update) {
 6193:                 $$tstatus='future';
 6194:                 if ($$tstart<$now) {
 6195:                     if ($$tstart && $$tstart>$refresh) {
 6196:                         if (($$where ne '') && ($$role ne '')) {
 6197:                             my (%allroles,%allgroups,$group_privs,
 6198:                                 %groups_roles,@rolecodes);
 6199:                             my %userroles = (
 6200:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6201:                             );
 6202:                             @rolecodes = ('cm'); 
 6203:                             my $spec=$$role.'.'.$$where;
 6204:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6205:                             if ($$role =~ /^cr\//) {
 6206:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6207:                                 push(@rolecodes,'cr');
 6208:                             } elsif ($$role eq 'gr') {
 6209:                                 push(@rolecodes,$$role);
 6210:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6211:                                                     $env{'user.name'});
 6212:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6213:                                 (undef,my $group_privs) = split(/\//,$trole);
 6214:                                 $group_privs = &unescape($group_privs);
 6215:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6216:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6217:                                 &get_groups_roles($tdomain,$trest,
 6218:                                                   \%course_roles,\@rolecodes,
 6219:                                                   \%groups_roles);
 6220:                             } else {
 6221:                                 push(@rolecodes,$$role);
 6222:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6223:                             }
 6224:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6225:                                                                    \%groups_roles);
 6226:                             &appenv(\%userroles,\@rolecodes);
 6227:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6228:                         }
 6229:                     }
 6230:                     $$tstatus = 'is';
 6231:                 }
 6232:             }
 6233:             if ($$tend) {
 6234:                 if ($$tend<$update) {
 6235:                     $$tstatus='expired';
 6236:                 } elsif ($$tend<$now) {
 6237:                     $$tstatus='will_not';
 6238:                 }
 6239:             }
 6240:         }
 6241:     }
 6242: }
 6243: 
 6244: sub get_groups_roles {
 6245:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6246:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6247:                   (ref($rolecodes) eq 'ARRAY') && 
 6248:                   (ref($groups_roles) eq 'HASH')); 
 6249:     if (keys(%{$cdom_courseroles}) > 0) {
 6250:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6251:         if ($cdom ne '' && $cnum ne '') {
 6252:             foreach my $key (keys(%{$cdom_courseroles})) {
 6253:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6254:                     my $crsrole = $1;
 6255:                     my $crssec = $2;
 6256:                     if ($crsrole =~ /^cr/) {
 6257:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6258:                             push(@{$rolecodes},'cr');
 6259:                         }
 6260:                     } else {
 6261:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6262:                             push(@{$rolecodes},$crsrole);
 6263:                         }
 6264:                     }
 6265:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6266:                     if ($crssec ne '') {
 6267:                         $rolekey .= "/$crssec";
 6268:                     }
 6269:                     $rolekey .= './';
 6270:                     $groups_roles->{$rolekey} = $rolecodes;
 6271:                 }
 6272:             }
 6273:         }
 6274:     }
 6275:     return;
 6276: }
 6277: 
 6278: sub delete_env_groupprivs {
 6279:     my ($where,$courseroles,$possroles) = @_;
 6280:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6281:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6282:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6283:         %{$courseroles->{$udom}} =
 6284:             &get_my_roles('','','userroles',['active'],
 6285:                           $possroles,[$udom],1);
 6286:     }
 6287:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6288:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6289:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6290:             my $area = '/'.$cdom.'/'.$cnum;
 6291:             my $privkey = "user.priv.$crsrole.$area";
 6292:             if ($crssec ne '') {
 6293:                 $privkey .= '/'.$crssec;
 6294:             }
 6295:             $privkey .= ".$area/$group";
 6296:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6297:         }
 6298:     }
 6299:     return;
 6300: }
 6301: 
 6302: sub check_adhoc_privs {
 6303:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6304:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6305:     if ($sec) {
 6306:         $cckey .= '/'.$sec;
 6307:     } 
 6308:     my $setprivs;
 6309:     if ($env{$cckey}) {
 6310:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6311:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6312:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6313:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6314:             $setprivs = 1;
 6315:         }
 6316:     } else {
 6317:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6318:         $setprivs = 1;
 6319:     }
 6320:     return $setprivs;
 6321: }
 6322: 
 6323: sub set_adhoc_privileges {
 6324: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6325:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6326:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6327:     if ($sec ne '') {
 6328:         $area .= '/'.$sec;
 6329:     }
 6330:     my $spec = $role.'.'.$area;
 6331:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6332:                                   $env{'user.name'},1);
 6333:     my %rolehash = ();
 6334:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6335:         my $rolename = $1;
 6336:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6337:         my %domdef = &get_domain_defaults($dcdom);
 6338:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6339:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6340:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6341:             }
 6342:         }
 6343:     } else {
 6344:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6345:     }
 6346:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6347:     &appenv(\%userroles,[$role,'cm']);
 6348:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6349:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6350:         &appenv( {'request.role'        => $spec,
 6351:                   'request.role.domain' => $dcdom,
 6352:                   'request.course.sec'  => $sec,
 6353:                  }
 6354:                );
 6355:         my $tadv=0;
 6356:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6357:         &appenv({'request.role.adv'    => $tadv});
 6358:     }
 6359: }
 6360: 
 6361: # --------------------------------------------------------------- get interface
 6362: 
 6363: sub get {
 6364:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6365:    my $items='';
 6366:    foreach my $item (@$storearr) {
 6367:        $items.=&escape($item).'&';
 6368:    }
 6369:    $items=~s/\&$//;
 6370:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6371:    if (!$uname) { $uname=$env{'user.name'}; }
 6372:    my $uhome=&homeserver($uname,$udomain);
 6373: 
 6374:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6375:    my @pairs=split(/\&/,$rep);
 6376:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6377:      return @pairs;
 6378:    }
 6379:    my %returnhash=();
 6380:    my $i=0;
 6381:    foreach my $item (@$storearr) {
 6382:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6383:       $i++;
 6384:    }
 6385:    return %returnhash;
 6386: }
 6387: 
 6388: # --------------------------------------------------------------- del interface
 6389: 
 6390: sub del {
 6391:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6392:    my $items='';
 6393:    foreach my $item (@$storearr) {
 6394:        $items.=&escape($item).'&';
 6395:    }
 6396: 
 6397:    $items=~s/\&$//;
 6398:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6399:    if (!$uname) { $uname=$env{'user.name'}; }
 6400:    my $uhome=&homeserver($uname,$udomain);
 6401:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6402: }
 6403: 
 6404: # -------------------------------------------------------------- dump interface
 6405: 
 6406: sub unserialize {
 6407:     my ($rep, $escapedkeys) = @_;
 6408: 
 6409:     return {} if $rep =~ /^error/;
 6410: 
 6411:     my %returnhash=();
 6412: 	foreach my $item (split(/\&/,$rep)) {
 6413: 	    my ($key, $value) = split(/=/, $item, 2);
 6414: 	    $key = unescape($key) unless $escapedkeys;
 6415: 	    next if $key =~ /^error: 2 /;
 6416: 	    $returnhash{$key} = &thaw_unescape($value);
 6417: 	}
 6418:     #return %returnhash;
 6419:     return \%returnhash;
 6420: }        
 6421: 
 6422: # see Lond::dump_with_regexp
 6423: # if $escapedkeys hash keys won't get unescaped.
 6424: sub dump {
 6425:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6426:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6427:     if (!$uname) { $uname=$env{'user.name'}; }
 6428:     my $uhome=&homeserver($uname,$udomain);
 6429: 
 6430:     if ($regexp) {
 6431:         $regexp=&escape($regexp);
 6432:     } else {
 6433:         $regexp='.';
 6434:     }
 6435:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6436:         # user is hosted on this machine
 6437:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6438:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6439:         return %{unserialize($reply, $escapedkeys)};
 6440:     }
 6441:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6442:     my @pairs=split(/\&/,$rep);
 6443:     my %returnhash=();
 6444:     if (!($rep =~ /^error/ )) {
 6445: 	foreach my $item (@pairs) {
 6446: 	    my ($key,$value)=split(/=/,$item,2);
 6447:         $key = unescape($key) unless $escapedkeys;
 6448:         #$key = &unescape($key);
 6449: 	    next if ($key =~ /^error: 2 /);
 6450: 	    $returnhash{$key}=&thaw_unescape($value);
 6451: 	}
 6452:     }
 6453:     return %returnhash;
 6454: }
 6455: 
 6456: 
 6457: # --------------------------------------------------------- dumpstore interface
 6458: 
 6459: sub dumpstore {
 6460:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6461:    # same as dump but keys must be escaped. They may contain colon separated
 6462:    # lists of values that may themself contain colons (e.g. symbs).
 6463:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6464: }
 6465: 
 6466: # -------------------------------------------------------------- keys interface
 6467: 
 6468: sub getkeys {
 6469:    my ($namespace,$udomain,$uname)=@_;
 6470:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6471:    if (!$uname) { $uname=$env{'user.name'}; }
 6472:    my $uhome=&homeserver($uname,$udomain);
 6473:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6474:    my @keyarray=();
 6475:    foreach my $key (split(/\&/,$rep)) {
 6476:       next if ($key =~ /^error: 2 /);
 6477:       push(@keyarray,&unescape($key));
 6478:    }
 6479:    return @keyarray;
 6480: }
 6481: 
 6482: # --------------------------------------------------------------- currentdump
 6483: sub currentdump {
 6484:    my ($courseid,$sdom,$sname)=@_;
 6485:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6486:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6487:    $sname    = $env{'user.name'}         if (! defined($sname));
 6488:    my $uhome = &homeserver($sname,$sdom);
 6489:    my $rep;
 6490: 
 6491:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6492:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6493:                    $courseid)));
 6494:    } else {
 6495:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6496:    }
 6497: 
 6498:    return if ($rep =~ /^(error:|no_such_host)/);
 6499:    #
 6500:    my %returnhash=();
 6501:    #
 6502:    if ($rep eq 'unknown_cmd') {
 6503:        # an old lond will not know currentdump
 6504:        # Do a dump and make it look like a currentdump
 6505:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6506:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6507:        my %hash = @tmp;
 6508:        @tmp=();
 6509:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6510:    } else {
 6511:        my @pairs=split(/\&/,$rep);
 6512:        foreach my $pair (@pairs) {
 6513:            my ($key,$value)=split(/=/,$pair,2);
 6514:            my ($symb,$param) = split(/:/,$key);
 6515:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6516:                                                         &thaw_unescape($value);
 6517:        }
 6518:    }
 6519:    return %returnhash;
 6520: }
 6521: 
 6522: sub convert_dump_to_currentdump{
 6523:     my %hash = %{shift()};
 6524:     my %returnhash;
 6525:     # Code ripped from lond, essentially.  The only difference
 6526:     # here is the unescaping done by lonnet::dump().  Conceivably
 6527:     # we might run in to problems with parameter names =~ /^v\./
 6528:     while (my ($key,$value) = each(%hash)) {
 6529:         my ($v,$symb,$param) = split(/:/,$key);
 6530: 	$symb  = &unescape($symb);
 6531: 	$param = &unescape($param);
 6532:         next if ($v eq 'version' || $symb eq 'keys');
 6533:         next if (exists($returnhash{$symb}) &&
 6534:                  exists($returnhash{$symb}->{$param}) &&
 6535:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6536:         $returnhash{$symb}->{$param}=$value;
 6537:         $returnhash{$symb}->{'v.'.$param}=$v;
 6538:     }
 6539:     #
 6540:     # Remove all of the keys in the hashes which keep track of
 6541:     # the version of the parameter.
 6542:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6543:         # use a foreach because we are going to delete from the hash.
 6544:         foreach my $key (keys(%$param_hash)) {
 6545:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6546:         }
 6547:     }
 6548:     return \%returnhash;
 6549: }
 6550: 
 6551: # ------------------------------------------------------ critical inc interface
 6552: 
 6553: sub cinc {
 6554:     return &inc(@_,'critical');
 6555: }
 6556: 
 6557: # --------------------------------------------------------------- inc interface
 6558: 
 6559: sub inc {
 6560:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6561:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6562:     if (!$uname) { $uname=$env{'user.name'}; }
 6563:     my $uhome=&homeserver($uname,$udomain);
 6564:     my $items='';
 6565:     if (! ref($store)) {
 6566:         # got a single value, so use that instead
 6567:         $items = &escape($store).'=&';
 6568:     } elsif (ref($store) eq 'SCALAR') {
 6569:         $items = &escape($$store).'=&';        
 6570:     } elsif (ref($store) eq 'ARRAY') {
 6571:         $items = join('=&',map {&escape($_);} @{$store});
 6572:     } elsif (ref($store) eq 'HASH') {
 6573:         while (my($key,$value) = each(%{$store})) {
 6574:             $items.= &escape($key).'='.&escape($value).'&';
 6575:         }
 6576:     }
 6577:     $items=~s/\&$//;
 6578:     if ($critical) {
 6579: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6580:     } else {
 6581: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6582:     }
 6583: }
 6584: 
 6585: # --------------------------------------------------------------- put interface
 6586: 
 6587: sub put {
 6588:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6589:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6590:    if (!$uname) { $uname=$env{'user.name'}; }
 6591:    my $uhome=&homeserver($uname,$udomain);
 6592:    my $items='';
 6593:    foreach my $item (keys(%$storehash)) {
 6594:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6595:    }
 6596:    $items=~s/\&$//;
 6597:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6598: }
 6599: 
 6600: # ------------------------------------------------------------ newput interface
 6601: 
 6602: sub newput {
 6603:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6604:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6605:    if (!$uname) { $uname=$env{'user.name'}; }
 6606:    my $uhome=&homeserver($uname,$udomain);
 6607:    my $items='';
 6608:    foreach my $key (keys(%$storehash)) {
 6609:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6610:    }
 6611:    $items=~s/\&$//;
 6612:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6613: }
 6614: 
 6615: # ---------------------------------------------------------  putstore interface
 6616: 
 6617: sub putstore {
 6618:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6619:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6620:    if (!$uname) { $uname=$env{'user.name'}; }
 6621:    my $uhome=&homeserver($uname,$udomain);
 6622:    my $items='';
 6623:    foreach my $key (keys(%$storehash)) {
 6624:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6625:    }
 6626:    $items=~s/\&$//;
 6627:    my $esc_symb=&escape($symb);
 6628:    my $esc_v=&escape($version);
 6629:    my $reply =
 6630:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6631: 	      $uhome);
 6632:    if (($tolog) && ($reply eq 'ok')) {
 6633:        my $namevalue='';
 6634:        foreach my $key (keys(%{$storehash})) {
 6635:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6636:        }
 6637:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6638:                      '&host='.&escape($perlvar{'lonHostID'}).
 6639:                      '&version='.$esc_v.
 6640:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6641:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6642:    }
 6643:    if ($reply eq 'unknown_cmd') {
 6644:        # gfall back to way things use to be done
 6645:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6646: 			    $uname);
 6647:    }
 6648:    return $reply;
 6649: }
 6650: 
 6651: sub old_putstore {
 6652:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6653:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6654:     if (!$uname) { $uname=$env{'user.name'}; }
 6655:     my $uhome=&homeserver($uname,$udomain);
 6656:     my %newstorehash;
 6657:     foreach my $item (keys(%$storehash)) {
 6658: 	my $key = $version.':'.&escape($symb).':'.$item;
 6659: 	$newstorehash{$key} = $storehash->{$item};
 6660:     }
 6661:     my $items='';
 6662:     my %allitems = ();
 6663:     foreach my $item (keys(%newstorehash)) {
 6664: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6665: 	    my $key = $1.':keys:'.$2;
 6666: 	    $allitems{$key} .= $3.':';
 6667: 	}
 6668: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6669:     }
 6670:     foreach my $item (keys(%allitems)) {
 6671: 	$allitems{$item} =~ s/\:$//;
 6672: 	$items.= $item.'='.$allitems{$item}.'&';
 6673:     }
 6674:     $items=~s/\&$//;
 6675:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6676: }
 6677: 
 6678: # ------------------------------------------------------ critical put interface
 6679: 
 6680: sub cput {
 6681:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6682:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6683:    if (!$uname) { $uname=$env{'user.name'}; }
 6684:    my $uhome=&homeserver($uname,$udomain);
 6685:    my $items='';
 6686:    foreach my $item (keys(%$storehash)) {
 6687:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6688:    }
 6689:    $items=~s/\&$//;
 6690:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6691: }
 6692: 
 6693: # -------------------------------------------------------------- eget interface
 6694: 
 6695: sub eget {
 6696:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6697:    my $items='';
 6698:    foreach my $item (@$storearr) {
 6699:        $items.=&escape($item).'&';
 6700:    }
 6701:    $items=~s/\&$//;
 6702:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6703:    if (!$uname) { $uname=$env{'user.name'}; }
 6704:    my $uhome=&homeserver($uname,$udomain);
 6705:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6706:    my @pairs=split(/\&/,$rep);
 6707:    my %returnhash=();
 6708:    my $i=0;
 6709:    foreach my $item (@$storearr) {
 6710:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6711:       $i++;
 6712:    }
 6713:    return %returnhash;
 6714: }
 6715: 
 6716: # ------------------------------------------------------------ tmpput interface
 6717: sub tmpput {
 6718:     my ($storehash,$server,$context)=@_;
 6719:     my $items='';
 6720:     foreach my $item (keys(%$storehash)) {
 6721: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6722:     }
 6723:     $items=~s/\&$//;
 6724:     if (defined($context)) {
 6725:         $items .= ':'.&escape($context);
 6726:     }
 6727:     return &reply("tmpput:$items",$server);
 6728: }
 6729: 
 6730: # ------------------------------------------------------------ tmpget interface
 6731: sub tmpget {
 6732:     my ($token,$server)=@_;
 6733:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6734:     my $rep=&reply("tmpget:$token",$server);
 6735:     my %returnhash;
 6736:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6737:         return %returnhash;
 6738:     }
 6739:     foreach my $item (split(/\&/,$rep)) {
 6740: 	my ($key,$value)=split(/=/,$item);
 6741: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6742:     }
 6743:     return %returnhash;
 6744: }
 6745: 
 6746: # ------------------------------------------------------------ tmpdel interface
 6747: sub tmpdel {
 6748:     my ($token,$server)=@_;
 6749:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6750:     return &reply("tmpdel:$token",$server);
 6751: }
 6752: 
 6753: # ------------------------------------------------------------ get_timebased_id 
 6754: 
 6755: sub get_timebased_id {
 6756:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6757:         $maxtries) = @_;
 6758:     my ($newid,$error,$dellock);
 6759:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6760:         return ('','ok','invalid call to get suffix');
 6761:     }
 6762: 
 6763: # set defaults for any optional args for which values were not supplied
 6764:     if ($who eq '') {
 6765:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6766:     }
 6767:     if (!$locktries) {
 6768:         $locktries = 3;
 6769:     }
 6770:     if (!$maxtries) {
 6771:         $maxtries = 10;
 6772:     }
 6773:     
 6774:     if (($cdom eq '') || ($cnum eq '')) {
 6775:         if ($env{'request.course.id'}) {
 6776:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6777:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6778:         }
 6779:         if (($cdom eq '') || ($cnum eq '')) {
 6780:             return ('','ok','call to get suffix not in course context');
 6781:         }
 6782:     }
 6783: 
 6784: # construct locking item
 6785:     my $lockhash = {
 6786:                       $prefix."\0".'locked_'.$keyid => $who,
 6787:                    };
 6788:     my $tries = 0;
 6789: 
 6790: # attempt to get lock on nohist_$namespace file
 6791:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6792:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6793:         $tries ++;
 6794:         sleep 1;
 6795:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6796:     }
 6797: 
 6798: # attempt to get unique identifier, based on current timestamp
 6799:     if ($gotlock eq 'ok') {
 6800:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6801:         my $id = time;
 6802:         $newid = $id;
 6803:         if ($idtype eq 'addcode') {
 6804:             $newid .= &sixnum_code();
 6805:         }
 6806:         my $idtries = 0;
 6807:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6808:             if ($idtype eq 'concat') {
 6809:                 $newid = $id.$idtries;
 6810:             } elsif ($idtype eq 'addcode') {
 6811:                 $newid = $newid.&sixnum_code();
 6812:             } else {
 6813:                 $newid ++;
 6814:             }
 6815:             $idtries ++;
 6816:         }
 6817:         if (!exists($inuse{$prefix."\0".$newid})) {
 6818:             my %new_item =  (
 6819:                               $prefix."\0".$newid => $who,
 6820:                             );
 6821:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6822:                                                  $cdom,$cnum);
 6823:             if ($putresult ne 'ok') {
 6824:                 undef($newid);
 6825:                 $error = 'error saving new item: '.$putresult;
 6826:             }
 6827:         } else {
 6828:              undef($newid);
 6829:              $error = ('error: no unique suffix available for the new item ');
 6830:         }
 6831: #  remove lock
 6832:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6833:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6834:     } else {
 6835:         $error = "error: could not obtain lockfile\n";
 6836:         $dellock = 'ok';
 6837:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6838:             $dellock = 'nolock';
 6839:         }
 6840:     }
 6841:     return ($newid,$dellock,$error);
 6842: }
 6843: 
 6844: sub sixnum_code {
 6845:     my $code;
 6846:     for (0..6) {
 6847:         $code .= int( rand(9) );
 6848:     }
 6849:     return $code;
 6850: }
 6851: 
 6852: # -------------------------------------------------- portfolio access checking
 6853: 
 6854: sub portfolio_access {
 6855:     my ($requrl,$clientip) = @_;
 6856:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6857:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6858:     if ($result) {
 6859:         my %setters;
 6860:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6861:             my ($startblock,$endblock) =
 6862:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6863:             if ($startblock && $endblock) {
 6864:                 return 'B';
 6865:             }
 6866:         } else {
 6867:             my ($startblock,$endblock) =
 6868:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6869:             if ($startblock && $endblock) {
 6870:                 return 'B';
 6871:             }
 6872:         }
 6873:     }
 6874:     if ($result eq 'ok') {
 6875:        return 'F';
 6876:     } elsif ($result =~ /^[^:]+:guest_/) {
 6877:        return 'A';
 6878:     }
 6879:     return '';
 6880: }
 6881: 
 6882: sub get_portfolio_access {
 6883:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6884: 
 6885:     if (!ref($access_hash)) {
 6886: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6887: 	my %access_controls = &get_access_controls($current_perms,$group,
 6888: 						   $file_name);
 6889: 	$access_hash = $access_controls{$file_name};
 6890:     }
 6891: 
 6892:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6893:     my $now = time;
 6894:     if (ref($access_hash) eq 'HASH') {
 6895:         foreach my $key (keys(%{$access_hash})) {
 6896:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6897:             if ($start > $now) {
 6898:                 next;
 6899:             }
 6900:             if ($end && $end<$now) {
 6901:                 next;
 6902:             }
 6903:             if ($scope eq 'public') {
 6904:                 $public = $key;
 6905:                 last;
 6906:             } elsif ($scope eq 'guest') {
 6907:                 $guest = $key;
 6908:             } elsif ($scope eq 'domains') {
 6909:                 push(@domains,$key);
 6910:             } elsif ($scope eq 'users') {
 6911:                 push(@users,$key);
 6912:             } elsif ($scope eq 'course') {
 6913:                 push(@courses,$key);
 6914:             } elsif ($scope eq 'group') {
 6915:                 push(@groups,$key);
 6916:             } elsif ($scope eq 'ip') {
 6917:                 push(@ips,$key);
 6918:             }
 6919:         }
 6920:         if ($public) {
 6921:             return 'ok';
 6922:         } elsif (@ips > 0) {
 6923:             my $allowed;
 6924:             foreach my $ipkey (@ips) {
 6925:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6926:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6927:                         $allowed = 1;
 6928:                         last; 
 6929:                     }
 6930:                 }
 6931:             }
 6932:             if ($allowed) {
 6933:                 return 'ok';
 6934:             }
 6935:         }
 6936:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6937:             if ($guest) {
 6938:                 return $guest;
 6939:             }
 6940:         } else {
 6941:             if (@domains > 0) {
 6942:                 foreach my $domkey (@domains) {
 6943:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6944:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6945:                             return 'ok';
 6946:                         }
 6947:                     }
 6948:                 }
 6949:             }
 6950:             if (@users > 0) {
 6951:                 foreach my $userkey (@users) {
 6952:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6953:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6954:                             if (ref($item) eq 'HASH') {
 6955:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6956:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6957:                                     return 'ok';
 6958:                                 }
 6959:                             }
 6960:                         }
 6961:                     } 
 6962:                 }
 6963:             }
 6964:             my %roleshash;
 6965:             my @courses_and_groups = @courses;
 6966:             push(@courses_and_groups,@groups); 
 6967:             if (@courses_and_groups > 0) {
 6968:                 my (%allgroups,%allroles); 
 6969:                 my ($start,$end,$role,$sec,$group);
 6970:                 foreach my $envkey (%env) {
 6971:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6972:                         my $cid = $2.'_'.$3; 
 6973:                         if ($1 eq 'gr') {
 6974:                             $group = $4;
 6975:                             $allgroups{$cid}{$group} = $env{$envkey};
 6976:                         } else {
 6977:                             if ($4 eq '') {
 6978:                                 $sec = 'none';
 6979:                             } else {
 6980:                                 $sec = $4;
 6981:                             }
 6982:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6983:                         }
 6984:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6985:                         my $cid = $2.'_'.$3;
 6986:                         if ($4 eq '') {
 6987:                             $sec = 'none';
 6988:                         } else {
 6989:                             $sec = $4;
 6990:                         }
 6991:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6992:                     }
 6993:                 }
 6994:                 if (keys(%allroles) == 0) {
 6995:                     return;
 6996:                 }
 6997:                 foreach my $key (@courses_and_groups) {
 6998:                     my %content = %{$$access_hash{$key}};
 6999:                     my $cnum = $content{'number'};
 7000:                     my $cdom = $content{'domain'};
 7001:                     my $cid = $cdom.'_'.$cnum;
 7002:                     if (!exists($allroles{$cid})) {
 7003:                         next;
 7004:                     }    
 7005:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7006:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7007:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7008:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7009:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7010:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7011:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7012:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7013:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7014:                                         if (grep/^all$/,@sections) {
 7015:                                             return 'ok';
 7016:                                         } else {
 7017:                                             if (grep/^$sec$/,@sections) {
 7018:                                                 return 'ok';
 7019:                                             }
 7020:                                         }
 7021:                                     }
 7022:                                 }
 7023:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7024:                                     if (grep/^none$/,@groups) {
 7025:                                         return 'ok';
 7026:                                     }
 7027:                                 } else {
 7028:                                     if (grep/^all$/,@groups) {
 7029:                                         return 'ok';
 7030:                                     } 
 7031:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7032:                                         if (grep/^$group$/,@groups) {
 7033:                                             return 'ok';
 7034:                                         }
 7035:                                     }
 7036:                                 } 
 7037:                             }
 7038:                         }
 7039:                     }
 7040:                 }
 7041:             }
 7042:             if ($guest) {
 7043:                 return $guest;
 7044:             }
 7045:         }
 7046:     }
 7047:     return;
 7048: }
 7049: 
 7050: sub course_group_datechecker {
 7051:     my ($dates,$now,$status) = @_;
 7052:     my ($start,$end) = split(/\./,$dates);
 7053:     if (!$start && !$end) {
 7054:         return 'ok';
 7055:     }
 7056:     if (grep/^active$/,@{$status}) {
 7057:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7058:             return 'ok';
 7059:         }
 7060:     }
 7061:     if (grep/^previous$/,@{$status}) {
 7062:         if ($end > $now ) {
 7063:             return 'ok';
 7064:         }
 7065:     }
 7066:     if (grep/^future$/,@{$status}) {
 7067:         if ($start > $now) {
 7068:             return 'ok';
 7069:         }
 7070:     }
 7071:     return; 
 7072: }
 7073: 
 7074: sub parse_portfolio_url {
 7075:     my ($url) = @_;
 7076: 
 7077:     my ($type,$udom,$unum,$group,$file_name);
 7078:     
 7079:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7080: 	$type = 1;
 7081:         $udom = $1;
 7082:         $unum = $2;
 7083:         $file_name = $3;
 7084:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7085: 	$type = 2;
 7086:         $udom = $1;
 7087:         $unum = $2;
 7088:         $group = $3;
 7089:         $file_name = $3.'/'.$4;
 7090:     }
 7091:     if (wantarray) {
 7092: 	return ($type,$udom,$unum,$file_name,$group);
 7093:     }
 7094:     return $type;
 7095: }
 7096: 
 7097: sub is_portfolio_url {
 7098:     my ($url) = @_;
 7099:     return scalar(&parse_portfolio_url($url));
 7100: }
 7101: 
 7102: sub is_portfolio_file {
 7103:     my ($file) = @_;
 7104:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7105:         return 1;
 7106:     }
 7107:     return;
 7108: }
 7109: 
 7110: sub usertools_access {
 7111:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7112:     my ($access,%tools);
 7113:     if ($context eq '') {
 7114:         $context = 'tools';
 7115:     }
 7116:     if ($context eq 'requestcourses') {
 7117:         %tools = (
 7118:                       official   => 1,
 7119:                       unofficial => 1,
 7120:                       community  => 1,
 7121:                       textbook   => 1,
 7122:                       placement  => 1,
 7123:                  );
 7124:     } elsif ($context eq 'requestauthor') {
 7125:         %tools = (
 7126:                       requestauthor => 1,
 7127:                  );
 7128:     } else {
 7129:         %tools = (
 7130:                       aboutme   => 1,
 7131:                       blog      => 1,
 7132:                       webdav    => 1,
 7133:                       portfolio => 1,
 7134:                  );
 7135:     }
 7136:     return if (!defined($tools{$tool}));
 7137: 
 7138:     if (($udom eq '') || ($uname eq '')) {
 7139:         $udom = $env{'user.domain'};
 7140:         $uname = $env{'user.name'};
 7141:     }
 7142: 
 7143:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7144:         if ($action ne 'reload') {
 7145:             if ($context eq 'requestcourses') {
 7146:                 return $env{'environment.canrequest.'.$tool};
 7147:             } elsif ($context eq 'requestauthor') {
 7148:                 return $env{'environment.canrequest.author'};
 7149:             } else {
 7150:                 return $env{'environment.availabletools.'.$tool};
 7151:             }
 7152:         }
 7153:     }
 7154: 
 7155:     my ($toolstatus,$inststatus,$envkey);
 7156:     if ($context eq 'requestauthor') {
 7157:         $envkey = $context; 
 7158:     } else {
 7159:         $envkey = $context.'.'.$tool;
 7160:     }
 7161: 
 7162:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7163:          ($action ne 'reload')) {
 7164:         $toolstatus = $env{'environment.'.$envkey};
 7165:         $inststatus = $env{'environment.inststatus'};
 7166:     } else {
 7167:         if (ref($userenvref) eq 'HASH') {
 7168:             $toolstatus = $userenvref->{$envkey};
 7169:             $inststatus = $userenvref->{'inststatus'};
 7170:         } else {
 7171:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7172:             $toolstatus = $userenv{$envkey};
 7173:             $inststatus = $userenv{'inststatus'};
 7174:         }
 7175:     }
 7176: 
 7177:     if ($toolstatus ne '') {
 7178:         if ($toolstatus) {
 7179:             $access = 1;
 7180:         } else {
 7181:             $access = 0;
 7182:         }
 7183:         return $access;
 7184:     }
 7185: 
 7186:     my ($is_adv,%domdef);
 7187:     if (ref($is_advref) eq 'HASH') {
 7188:         $is_adv = $is_advref->{'is_adv'};
 7189:     } else {
 7190:         $is_adv = &is_advanced_user($udom,$uname);
 7191:     }
 7192:     if (ref($domdefref) eq 'HASH') {
 7193:         %domdef = %{$domdefref};
 7194:     } else {
 7195:         %domdef = &get_domain_defaults($udom);
 7196:     }
 7197:     if (ref($domdef{$tool}) eq 'HASH') {
 7198:         if ($is_adv) {
 7199:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7200:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7201:                     $access = 1;
 7202:                 } else {
 7203:                     $access = 0;
 7204:                 }
 7205:                 return $access;
 7206:             }
 7207:         }
 7208:         if ($inststatus ne '') {
 7209:             my ($hasaccess,$hasnoaccess);
 7210:             foreach my $affiliation (split(/:/,$inststatus)) {
 7211:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7212:                     if ($domdef{$tool}{$affiliation}) {
 7213:                         $hasaccess = 1;
 7214:                     } else {
 7215:                         $hasnoaccess = 1;
 7216:                     }
 7217:                 }
 7218:             }
 7219:             if ($hasaccess || $hasnoaccess) {
 7220:                 if ($hasaccess) {
 7221:                     $access = 1;
 7222:                 } elsif ($hasnoaccess) {
 7223:                     $access = 0; 
 7224:                 }
 7225:                 return $access;
 7226:             }
 7227:         } else {
 7228:             if ($domdef{$tool}{'default'} ne '') {
 7229:                 if ($domdef{$tool}{'default'}) {
 7230:                     $access = 1;
 7231:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7232:                     $access = 0;
 7233:                 }
 7234:                 return $access;
 7235:             }
 7236:         }
 7237:     } else {
 7238:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7239:             $access = 1;
 7240:         } else {
 7241:             $access = 0;
 7242:         }
 7243:         return $access;
 7244:     }
 7245: }
 7246: 
 7247: sub is_course_owner {
 7248:     my ($cdom,$cnum,$udom,$uname) = @_;
 7249:     if (($udom eq '') || ($uname eq '')) {
 7250:         $udom = $env{'user.domain'};
 7251:         $uname = $env{'user.name'};
 7252:     }
 7253:     unless (($udom eq '') || ($uname eq '')) {
 7254:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7255:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7256:                 return 1;
 7257:             } else {
 7258:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7259:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7260:                     return 1;
 7261:                 }
 7262:             }
 7263:         }
 7264:     }
 7265:     return;
 7266: }
 7267: 
 7268: sub is_advanced_user {
 7269:     my ($udom,$uname) = @_;
 7270:     if ($udom ne '' && $uname ne '') {
 7271:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7272:             if (wantarray) {
 7273:                 return ($env{'user.adv'},$env{'user.author'});
 7274:             } else {
 7275:                 return $env{'user.adv'};
 7276:             }
 7277:         }
 7278:     }
 7279:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7280:     my %allroles;
 7281:     my ($is_adv,$is_author);
 7282:     foreach my $role (keys(%roleshash)) {
 7283:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7284:         my $area = '/'.$tdomain.'/'.$trest;
 7285:         if ($sec ne '') {
 7286:             $area .= '/'.$sec;
 7287:         }
 7288:         if (($area ne '') && ($trole ne '')) {
 7289:             my $spec=$trole.'.'.$area;
 7290:             if ($trole =~ /^cr\//) {
 7291:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7292:             } elsif ($trole ne 'gr') {
 7293:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7294:             }
 7295:             if ($trole eq 'au') {
 7296:                 $is_author = 1;
 7297:             }
 7298:         }
 7299:     }
 7300:     foreach my $role (keys(%allroles)) {
 7301:         last if ($is_adv);
 7302:         foreach my $item (split(/:/,$allroles{$role})) {
 7303:             if ($item ne '') {
 7304:                 my ($privilege,$restrictions)=split(/&/,$item);
 7305:                 if ($privilege eq 'adv') {
 7306:                     $is_adv = 1;
 7307:                     last;
 7308:                 }
 7309:             }
 7310:         }
 7311:     }
 7312:     if (wantarray) {
 7313:         return ($is_adv,$is_author);
 7314:     }
 7315:     return $is_adv;
 7316: }
 7317: 
 7318: sub check_can_request {
 7319:     my ($dom,$can_request,$request_domains) = @_;
 7320:     my $canreq = 0;
 7321:     my ($types,$typename) = &Apache::loncommon::course_types();
 7322:     my @options = ('approval','validate','autolimit');
 7323:     my $optregex = join('|',@options);
 7324:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7325:         foreach my $type (@{$types}) {
 7326:             if (&usertools_access($env{'user.name'},
 7327:                                   $env{'user.domain'},
 7328:                                   $type,undef,'requestcourses')) {
 7329:                 $canreq ++;
 7330:                 if (ref($request_domains) eq 'HASH') {
 7331:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7332:                 }
 7333:                 if ($dom eq $env{'user.domain'}) {
 7334:                     $can_request->{$type} = 1;
 7335:                 }
 7336:             }
 7337:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7338:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7339:                 if (@curr > 0) {
 7340:                     foreach my $item (@curr) {
 7341:                         if (ref($request_domains) eq 'HASH') {
 7342:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7343:                             if ($otherdom ne '') {
 7344:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7345:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7346:                                         push(@{$request_domains->{$type}},$otherdom);
 7347:                                     }
 7348:                                 } else {
 7349:                                     push(@{$request_domains->{$type}},$otherdom);
 7350:                                 }
 7351:                             }
 7352:                         }
 7353:                     }
 7354:                     unless($dom eq $env{'user.domain'}) {
 7355:                         $canreq ++;
 7356:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7357:                             $can_request->{$type} = 1;
 7358:                         }
 7359:                     }
 7360:                 }
 7361:             }
 7362:         }
 7363:     }
 7364:     return $canreq;
 7365: }
 7366: 
 7367: # ---------------------------------------------- Custom access rule evaluation
 7368: 
 7369: sub customaccess {
 7370:     my ($priv,$uri)=@_;
 7371:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7372:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7373:     $udom = &LONCAPA::clean_domain($udom);
 7374:     $ucrs = &LONCAPA::clean_username($ucrs);
 7375:     my $access=0;
 7376:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7377: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7378: 	if ($type eq 'user') {
 7379: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7380: 		my ($tdom,$tuname)=split(m{/},$scope);
 7381: 		if ($tdom) {
 7382: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7383: 		}
 7384: 		if ($tuname) {
 7385: 		    if ($tuname ne $env{'user.name'}) { next; }
 7386: 		}
 7387: 		$access=($effect eq 'allow');
 7388: 		last;
 7389: 	    }
 7390: 	} else {
 7391: 	    if ($role) {
 7392: 		if ($role ne $urole) { next; }
 7393: 	    }
 7394: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7395: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7396: 		if ($tdom) {
 7397: 		    if ($tdom ne $udom) { next; }
 7398: 		}
 7399: 		if ($tcrs) {
 7400: 		    if ($tcrs ne $ucrs) { next; }
 7401: 		}
 7402: 		if ($tsec) {
 7403: 		    if ($tsec ne $usec) { next; }
 7404: 		}
 7405: 		$access=($effect eq 'allow');
 7406: 		last;
 7407: 	    }
 7408: 	    if ($realm eq '' && $role eq '') {
 7409: 		$access=($effect eq 'allow');
 7410: 	    }
 7411: 	}
 7412:     }
 7413:     return $access;
 7414: }
 7415: 
 7416: # ------------------------------------------------- Check for a user privilege
 7417: 
 7418: sub allowed {
 7419:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7420:     my $ver_orguri=$uri;
 7421:     $uri=&deversion($uri);
 7422:     my $orguri=$uri;
 7423:     $uri=&declutter($uri);
 7424: 
 7425:     if ($priv eq 'evb') {
 7426: # Evade communication block restrictions for specified role in a course
 7427:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7428:             return $1;
 7429:         } else {
 7430:             return;
 7431:         }
 7432:     }
 7433: 
 7434:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7435: # Free bre access to adm and meta resources
 7436:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7437: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7438: 	&& ($priv eq 'bre')) {
 7439: 	return 'F';
 7440:     }
 7441: 
 7442: # Free bre access to user's own portfolio contents
 7443:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7444:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7445: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7446:         my %setters;
 7447:         my ($startblock,$endblock) = 
 7448:             &Apache::loncommon::blockcheck(\%setters,'port');
 7449:         if ($startblock && $endblock) {
 7450:             return 'B';
 7451:         } else {
 7452:             return 'F';
 7453:         }
 7454:     }
 7455: 
 7456: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7457:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7458:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7459:         if (exists($env{'request.course.id'})) {
 7460:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7461:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7462:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7463:                 my $courseprivid=$env{'request.course.id'};
 7464:                 $courseprivid=~s/\_/\//;
 7465:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7466:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7467:                     return $1; 
 7468:                 } else {
 7469:                     if ($env{'request.course.sec'}) {
 7470:                         $courseprivid.='/'.$env{'request.course.sec'};
 7471:                     }
 7472:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7473:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7474:                         return $2;
 7475:                     }
 7476:                 }
 7477:             }
 7478:         }
 7479:     }
 7480: 
 7481: # Free bre to public access
 7482: 
 7483:     if ($priv eq 'bre') {
 7484:         my $copyright=&metadata($uri,'copyright');
 7485: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7486:            return 'F'; 
 7487:         }
 7488:         if ($copyright eq 'priv') {
 7489:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7490: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7491: 		return '';
 7492:             }
 7493:         }
 7494:         if ($copyright eq 'domain') {
 7495:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7496: 	    unless (($env{'user.domain'} eq $1) ||
 7497:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7498: 		return '';
 7499:             }
 7500:         }
 7501:         if ($env{'request.role'}=~ /li\.\//) {
 7502:             # Library role, so allow browsing of resources in this domain.
 7503:             return 'F';
 7504:         }
 7505:         if ($copyright eq 'custom') {
 7506: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7507:         }
 7508:     }
 7509:     # Domain coordinator is trying to create a course
 7510:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7511:         # uri is the requested domain in this case.
 7512:         # comparison to 'request.role.domain' shows if the user has selected
 7513:         # a role of dc for the domain in question.
 7514:         return 'F' if ($uri eq $env{'request.role.domain'});
 7515:     }
 7516: 
 7517:     my $thisallowed='';
 7518:     my $statecond=0;
 7519:     my $courseprivid='';
 7520: 
 7521:     my $ownaccess;
 7522:     # Community Coordinator or Assistant Co-author browsing resource space.
 7523:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7524:         if ($uri eq '') {
 7525:             $ownaccess = 1;
 7526:         } else {
 7527:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7528:                 my $udom = $env{'user.domain'};
 7529:                 my $uname = $env{'user.name'};
 7530:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7531:                     $ownaccess = 1;
 7532:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7533:                     unless ($uri =~ m{\.\./}) {
 7534:                         $ownaccess = 1;
 7535:                     }
 7536:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7537:                     my $now = time;
 7538:                     if ($uri =~ m{^([^/]+)/?$}) {
 7539:                         my $adom = $1;
 7540:                         foreach my $key (keys(%env)) {
 7541:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7542:                                 my ($start,$end) = split('.',$env{$key});
 7543:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7544:                                     $ownaccess = 1;
 7545:                                     last;
 7546:                                 }
 7547:                             }
 7548:                         }
 7549:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7550:                         my $adom = $1;
 7551:                         my $aname = $2;
 7552:                         foreach my $role ('ca','aa') { 
 7553:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7554:                                 my ($start,$end) =
 7555:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7556:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7557:                                     $ownaccess = 1;
 7558:                                     last;
 7559:                                 }
 7560:                             }
 7561:                         }
 7562:                     }
 7563:                 }
 7564:             }
 7565:         }
 7566:     }
 7567: 
 7568: # Course
 7569: 
 7570:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7571:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7572:             $thisallowed.=$1;
 7573:         }
 7574:     }
 7575: 
 7576: # Domain
 7577: 
 7578:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7579:        =~/\Q$priv\E\&([^\:]*)/) {
 7580:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7581:             $thisallowed.=$1;
 7582:         }
 7583:     }
 7584: 
 7585: # User who is not author or co-author might still be able to edit
 7586: # resource of an author in the domain (e.g., if Domain Coordinator).
 7587:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7588:         (&allowed('mdc',$env{'request.course.id'}))) {
 7589:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7590:             $thisallowed.=$1;
 7591:         }
 7592:     }
 7593: 
 7594: # Course: uri itself is a course
 7595:     my $courseuri=$uri;
 7596:     $courseuri=~s/\_(\d)/\/$1/;
 7597:     $courseuri=~s/^([^\/])/\/$1/;
 7598: 
 7599:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7600:        =~/\Q$priv\E\&([^\:]*)/) {
 7601:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7602:             $thisallowed.=$1;
 7603:         }
 7604:     }
 7605: 
 7606: # URI is an uploaded document for this course, default permissions don't matter
 7607: # not allowing 'edit' access (editupload) to uploaded course docs
 7608:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7609: 	$thisallowed='';
 7610:         my ($match)=&is_on_map($uri);
 7611:         if ($match) {
 7612:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7613:                   =~/\Q$priv\E\&([^\:]*)/) {
 7614:                 my $value = $1;
 7615:                 if ($noblockcheck) {
 7616:                     $thisallowed.=$value;
 7617:                 } else {
 7618:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7619:                     if (@blockers > 0) {
 7620:                         $thisallowed = 'B';
 7621:                     } else {
 7622:                         $thisallowed.=$value;
 7623:                     }
 7624:                 }
 7625:             }
 7626:         } else {
 7627:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7628:             if ($refuri) {
 7629:                 if ($refuri =~ m|^/adm/|) {
 7630:                     $thisallowed='F';
 7631:                 } else {
 7632:                     $refuri=&declutter($refuri);
 7633:                     my ($match) = &is_on_map($refuri);
 7634:                     if ($match) {
 7635:                         if ($noblockcheck) {
 7636:                             $thisallowed='F';
 7637:                         } else {
 7638:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7639:                             if (@blockers > 0) {
 7640:                                 $thisallowed = 'B';
 7641:                             } else {
 7642:                                 $thisallowed='F';
 7643:                             }
 7644:                         }
 7645:                     }
 7646:                 }
 7647:             }
 7648:         }
 7649:     }
 7650: 
 7651:     if ($priv eq 'bre'
 7652: 	&& $thisallowed ne 'F' 
 7653: 	&& $thisallowed ne '2'
 7654: 	&& &is_portfolio_url($uri)) {
 7655: 	$thisallowed = &portfolio_access($uri,$clientip);
 7656:     }
 7657: 
 7658: # Full access at system, domain or course-wide level? Exit.
 7659:     if ($thisallowed=~/F/) {
 7660: 	return 'F';
 7661:     }
 7662: 
 7663: # If this is generating or modifying users, exit with special codes
 7664: 
 7665:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7666: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7667: 	    my ($audom,$auname)=split('/',$uri);
 7668: # no author name given, so this just checks on the general right to make a co-author in this domain
 7669: 	    unless ($auname) { return $thisallowed; }
 7670: # an author name is given, so we are about to actually make a co-author for a certain account
 7671: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7672: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7673: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7674: 	}
 7675: 	return $thisallowed;
 7676:     }
 7677: #
 7678: # Gathered so far: system, domain and course wide privileges
 7679: #
 7680: # Course: See if uri or referer is an individual resource that is part of 
 7681: # the course
 7682: 
 7683:     if ($env{'request.course.id'}) {
 7684: 
 7685:        $courseprivid=$env{'request.course.id'};
 7686:        if ($env{'request.course.sec'}) {
 7687:           $courseprivid.='/'.$env{'request.course.sec'};
 7688:        }
 7689:        $courseprivid=~s/\_/\//;
 7690:        my $checkreferer=1;
 7691:        my ($match,$cond)=&is_on_map($uri);
 7692:        if ($match) {
 7693:            $statecond=$cond;
 7694:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7695:                =~/\Q$priv\E\&([^\:]*)/) {
 7696:                my $value = $1;
 7697:                if ($priv eq 'bre') {
 7698:                    if ($noblockcheck) {
 7699:                        $thisallowed.=$value;
 7700:                    } else {
 7701:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7702:                        if (@blockers > 0) {
 7703:                            $thisallowed = 'B';
 7704:                        } else {
 7705:                            $thisallowed.=$value;
 7706:                        }
 7707:                    }
 7708:                } else {
 7709:                    $thisallowed.=$value;
 7710:                }
 7711:                $checkreferer=0;
 7712:            }
 7713:        }
 7714:        
 7715:        if ($checkreferer) {
 7716: 	  my $refuri=$env{'httpref.'.$orguri};
 7717:             unless ($refuri) {
 7718:                 foreach my $key (keys(%env)) {
 7719: 		    if ($key=~/^httpref\..*\*/) {
 7720: 			my $pattern=$key;
 7721:                         $pattern=~s/^httpref\.\/res\///;
 7722:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7723:                         $pattern=~s/\//\\\//g;
 7724:                         if ($orguri=~/$pattern/) {
 7725: 			    $refuri=$env{$key};
 7726:                         }
 7727:                     }
 7728:                 }
 7729:             }
 7730: 
 7731:          if ($refuri) { 
 7732: 	  $refuri=&declutter($refuri);
 7733:           my ($match,$cond)=&is_on_map($refuri);
 7734:             if ($match) {
 7735:               my $refstatecond=$cond;
 7736:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7737:                   =~/\Q$priv\E\&([^\:]*)/) {
 7738:                   my $value = $1;
 7739:                   if ($priv eq 'bre') {
 7740:                       if ($noblockcheck) {
 7741:                           $thisallowed.=$value;
 7742:                       } else {
 7743:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7744:                           if (@blockers > 0) {
 7745:                               $thisallowed = 'B';
 7746:                           } else {
 7747:                               $thisallowed.=$value;
 7748:                           }
 7749:                       }
 7750:                   } else {
 7751:                       $thisallowed.=$value;
 7752:                   }
 7753:                   $uri=$refuri;
 7754:                   $statecond=$refstatecond;
 7755:               }
 7756:           }
 7757:         }
 7758:        }
 7759:    }
 7760: 
 7761: #
 7762: # Gathered now: all privileges that could apply, and condition number
 7763: # 
 7764: #
 7765: # Full or no access?
 7766: #
 7767: 
 7768:     if ($thisallowed=~/F/) {
 7769: 	return 'F';
 7770:     }
 7771: 
 7772:     unless ($thisallowed) {
 7773:         return '';
 7774:     }
 7775: 
 7776: # Restrictions exist, deal with them
 7777: #
 7778: #   C:according to course preferences
 7779: #   R:according to resource settings
 7780: #   L:unless locked
 7781: #   X:according to user session state
 7782: #
 7783: 
 7784: # Possibly locked functionality, check all courses
 7785: # Locks might take effect only after 10 minutes cache expiration for other
 7786: # courses, and 2 minutes for current course
 7787: 
 7788:     my $envkey;
 7789:     if ($thisallowed=~/L/) {
 7790:         foreach $envkey (keys(%env)) {
 7791:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7792:                my $courseid=$2;
 7793:                my $roleid=$1.'.'.$2;
 7794:                $courseid=~s/^\///;
 7795:                my $expiretime=600;
 7796:                if ($env{'request.role'} eq $roleid) {
 7797: 		  $expiretime=120;
 7798:                }
 7799: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7800:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7801:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7802: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7803:                }
 7804:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7805:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7806: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7807:                        &log($env{'user.domain'},$env{'user.name'},
 7808:                             $env{'user.home'},
 7809:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7810:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7811:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7812: 		       return '';
 7813:                    }
 7814:                }
 7815:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7816:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7817: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7818:                        &log($env{'user.domain'},$env{'user.name'},
 7819:                             $env{'user.home'},
 7820:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7821:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7822:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7823: 		       return '';
 7824:                    }
 7825:                }
 7826: 	   }
 7827:        }
 7828:     }
 7829:    
 7830: #
 7831: # Rest of the restrictions depend on selected course
 7832: #
 7833: 
 7834:     unless ($env{'request.course.id'}) {
 7835: 	if ($thisallowed eq 'A') {
 7836: 	    return 'A';
 7837:         } elsif ($thisallowed eq 'B') {
 7838:             return 'B';
 7839: 	} else {
 7840: 	    return '1';
 7841: 	}
 7842:     }
 7843: 
 7844: #
 7845: # Now user is definitely in a course
 7846: #
 7847: 
 7848: 
 7849: # Course preferences
 7850: 
 7851:    if ($thisallowed=~/C/) {
 7852:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7853:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7854:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7855: 	   =~/\Q$rolecode\E/) {
 7856: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7857: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7858: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7859: 			$env{'request.course.id'});
 7860: 	   }
 7861:            return '';
 7862:        }
 7863: 
 7864:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7865: 	   =~/\Q$unamedom\E/) {
 7866: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7867: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7868: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7869: 			$env{'request.course.id'});
 7870: 	   }
 7871:            return '';
 7872:        }
 7873:    }
 7874: 
 7875: # Resource preferences
 7876: 
 7877:    if ($thisallowed=~/R/) {
 7878:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7879:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7880: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7881: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7882: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7883: 	   }
 7884: 	   return '';
 7885:        }
 7886:    }
 7887: 
 7888: # Restricted by state or randomout?
 7889: 
 7890:    if ($thisallowed=~/X/) {
 7891:       if ($env{'acc.randomout'}) {
 7892: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7893:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7894:             return ''; 
 7895:          }
 7896:       }
 7897:       if (&condval($statecond)) {
 7898: 	 return '2';
 7899:       } else {
 7900:          return '';
 7901:       }
 7902:    }
 7903: 
 7904:     if ($thisallowed eq 'A') {
 7905: 	return 'A';
 7906:     } elsif ($thisallowed eq 'B') {
 7907:         return 'B';
 7908:     }
 7909:    return 'F';
 7910: }
 7911: 
 7912: # ------------------------------------------- Check construction space access
 7913: 
 7914: sub constructaccess {
 7915:     my ($url,$setpriv)=@_;
 7916: 
 7917: # We do not allow editing of previous versions of files
 7918:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7919: 
 7920: # Get username and domain from URL
 7921:     my ($ownername,$ownerdomain,$ownerhome);
 7922: 
 7923:     ($ownerdomain,$ownername) =
 7924:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7925: 
 7926: # The URL does not really point to any authorspace, forget it
 7927:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7928: 
 7929: # Now we need to see if the user has access to the authorspace of
 7930: # $ownername at $ownerdomain
 7931: 
 7932:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7933: # Real author for this?
 7934:        $ownerhome = $env{'user.home'};
 7935:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7936:           return ($ownername,$ownerdomain,$ownerhome);
 7937:        }
 7938:     } else {
 7939: # Co-author for this?
 7940:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7941:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7942:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7943:             return ($ownername,$ownerdomain,$ownerhome);
 7944:         }
 7945:         if ($env{'request.course.id'}) {
 7946:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 7947:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 7948:                 if (&allowed('mdc',$env{'request.course.id'})) {
 7949:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 7950:                     return ($ownername,$ownerdomain,$ownerhome);
 7951:                 }
 7952:             }
 7953:         }
 7954:     }
 7955: 
 7956: # We don't have any access right now. If we are not possibly going to do anything about this,
 7957: # we might as well leave
 7958:    unless ($setpriv) { return ''; }
 7959: 
 7960: # Backdoor access?
 7961:     my $allowed=&allowed('eco',$ownerdomain);
 7962: # Nope
 7963:     unless ($allowed) { return ''; }
 7964: # Looks like we may have access, but could be locked by the owner of the construction space
 7965:     if ($allowed eq 'U') {
 7966:         my %blocked=&get('environment',['domcoord.author'],
 7967:                          $ownerdomain,$ownername);
 7968: # Is blocked by owner
 7969:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7970:     }
 7971:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7972: # Grant temporary access
 7973:         my $then=$env{'user.login.time'};
 7974:         my $update=$env{'user.update.time'};
 7975:         if (!$update) { $update = $then; }
 7976:         my $refresh=$env{'user.refresh.time'};
 7977:         if (!$refresh) { $refresh = $update; }
 7978:         my $now = time;
 7979:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7980:                            $now,'ca','constructaccess');
 7981:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7982:         return($ownername,$ownerdomain,$ownerhome);
 7983:     }
 7984: # No business here
 7985:     return '';
 7986: }
 7987: 
 7988: # ----------------------------------------------------------- Content Blocking
 7989: 
 7990: {
 7991: # Caches for faster Course Contents display where content blocking
 7992: # is in operation (i.e., interval param set) for timed quiz.
 7993: #
 7994: # User for whom data are being temporarily cached.
 7995: my $cacheduser='';
 7996: # Cached blockers for this user (a hash of blocking items). 
 7997: my %cachedblockers=();
 7998: # When the data were last cached.
 7999: my $cachedlast='';
 8000: 
 8001: sub load_all_blockers {
 8002:     my ($uname,$udom,$blocks)=@_;
 8003:     if (($uname ne '') && ($udom ne '')) { 
 8004:         if (($cacheduser eq $uname.':'.$udom) &&
 8005:             (abs($cachedlast-time)<5)) {
 8006:             return;
 8007:         }
 8008:     }
 8009:     $cachedlast=time;
 8010:     $cacheduser=$uname.':'.$udom;
 8011:     %cachedblockers = &get_commblock_resources($blocks);
 8012: }
 8013: 
 8014: sub get_comm_blocks {
 8015:     my ($cdom,$cnum) = @_;
 8016:     if ($cdom eq '' || $cnum eq '') {
 8017:         return unless ($env{'request.course.id'});
 8018:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8019:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8020:     }
 8021:     my %commblocks;
 8022:     my $hashid=$cdom.'_'.$cnum;
 8023:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8024:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8025:         %commblocks = %{$blocksref};
 8026:     } else {
 8027:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8028:         my $cachetime = 600;
 8029:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8030:     }
 8031:     return %commblocks;
 8032: }
 8033: 
 8034: sub get_commblock_resources {
 8035:     my ($blocks) = @_;
 8036:     my %blockers = ();
 8037:     return %blockers unless ($env{'request.course.id'});
 8038:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8039:     my %commblocks;
 8040:     if (ref($blocks) eq 'HASH') {
 8041:         %commblocks = %{$blocks};
 8042:     } else {
 8043:         %commblocks = &get_comm_blocks();
 8044:     }
 8045:     return %blockers unless (keys(%commblocks) > 0); 
 8046:     my $navmap = Apache::lonnavmaps::navmap->new();
 8047:     return %blockers unless (ref($navmap));
 8048:     my $now = time;
 8049:     foreach my $block (keys(%commblocks)) {
 8050:         if ($block =~ /^(\d+)____(\d+)$/) {
 8051:             my ($start,$end) = ($1,$2);
 8052:             if ($start <= $now && $end >= $now) {
 8053:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8054:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8055:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8056:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8057:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8058:                             }
 8059:                         }
 8060:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8061:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8062:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8063:                             }
 8064:                         }
 8065:                     }
 8066:                 }
 8067:             }
 8068:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8069:             my $item = $1;
 8070:             my @to_test;
 8071:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8072:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8073:                     my @interval;
 8074:                     my $type = 'map';
 8075:                     if ($item eq 'course') {
 8076:                         $type = 'course';
 8077:                         @interval=&EXT("resource.0.interval");
 8078:                     } else {
 8079:                         if ($item =~ /___\d+___/) {
 8080:                             $type = 'resource';
 8081:                             @interval=&EXT("resource.0.interval",$item);
 8082:                             if (ref($navmap)) {                        
 8083:                                 my $res = $navmap->getBySymb($item); 
 8084:                                 push(@to_test,$res);
 8085:                             }
 8086:                         } else {
 8087:                             my $mapsymb = &symbread($item,1);
 8088:                             if ($mapsymb) {
 8089:                                 if (ref($navmap)) {
 8090:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8091:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8092:                                     foreach my $res (@to_test) {
 8093:                                         my $symb = $res->symb();
 8094:                                         next if ($symb eq $mapsymb);
 8095:                                         if ($symb ne '') {
 8096:                                             @interval=&EXT("resource.0.interval",$symb);
 8097:                                             if ($interval[1] eq 'map') {
 8098:                                                 last;
 8099:                                             }
 8100:                                         }
 8101:                                     }
 8102:                                 }
 8103:                             }
 8104:                         }
 8105:                     }
 8106:                     if ($interval[0] =~ /^(\d+)/) {
 8107:                         my $timelimit = $1; 
 8108:                         my $first_access;
 8109:                         if ($type eq 'resource') {
 8110:                             $first_access=&get_first_access($interval[1],$item);
 8111:                         } elsif ($type eq 'map') {
 8112:                             $first_access=&get_first_access($interval[1],undef,$item);
 8113:                         } else {
 8114:                             $first_access=&get_first_access($interval[1]);
 8115:                         }
 8116:                         if ($first_access) {
 8117:                             my $timesup = $first_access+$timelimit;
 8118:                             if ($timesup > $now) {
 8119:                                 my $activeblock;
 8120:                                 foreach my $res (@to_test) {
 8121:                                     if ($res->answerable()) {
 8122:                                         $activeblock = 1;
 8123:                                         last;
 8124:                                     }
 8125:                                 }
 8126:                                 if ($activeblock) {
 8127:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8128:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8129:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8130:                                          }
 8131:                                     }
 8132:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8133:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8134:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8135:                                         }
 8136:                                     }
 8137:                                 }
 8138:                             }
 8139:                         }
 8140:                     }
 8141:                 }
 8142:             }
 8143:         }
 8144:     }
 8145:     return %blockers;
 8146: }
 8147: 
 8148: sub has_comm_blocking {
 8149:     my ($priv,$symb,$uri,$blocks) = @_;
 8150:     my @blockers;
 8151:     return unless ($env{'request.course.id'});
 8152:     return unless ($priv eq 'bre');
 8153:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8154:     return if ($env{'request.state'} eq 'construct');
 8155:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8156:     return unless (keys(%cachedblockers) > 0);
 8157:     my (%possibles,@symbs);
 8158:     if (!$symb) {
 8159:         $symb = &symbread($uri,1,1,1,\%possibles);
 8160:     }
 8161:     if ($symb) {
 8162:         @symbs = ($symb);
 8163:     } elsif (keys(%possibles)) { 
 8164:         @symbs = keys(%possibles);
 8165:     }
 8166:     my $noblock;
 8167:     foreach my $symb (@symbs) {
 8168:         last if ($noblock);
 8169:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8170:         foreach my $block (keys(%cachedblockers)) {
 8171:             if ($block =~ /^firstaccess____(.+)$/) {
 8172:                 my $item = $1;
 8173:                 if (($item eq $map) || ($item eq $symb)) {
 8174:                     $noblock = 1;
 8175:                     last;
 8176:                 }
 8177:             }
 8178:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8179:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8180:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8181:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8182:                             push(@blockers,$block);
 8183:                         }
 8184:                     }
 8185:                 }
 8186:             }
 8187:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8188:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8189:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8190:                         push(@blockers,$block);
 8191:                     }
 8192:                 }
 8193:             }
 8194:         }
 8195:     }
 8196:     return if ($noblock);
 8197:     return @blockers;
 8198: }
 8199: }
 8200: 
 8201: # -------------------------------- Deversion and split uri into path an filename   
 8202: 
 8203: #
 8204: #   Removes the version from a URI and
 8205: #   splits it in to its filename and path to the filename.
 8206: #   Seems like File::Basename could have done this more clearly.
 8207: #   Parameters:
 8208: #      $uri   - input URI
 8209: #   Returns:
 8210: #     Two element list consisting of 
 8211: #     $pathname  - the URI up to and excluding the trailing /
 8212: #     $filename  - The part of the URI following the last /
 8213: #  NOTE:
 8214: #    Another realization of this is simply:
 8215: #    use File::Basename;
 8216: #    ...
 8217: #    $uri = shift;
 8218: #    $filename = basename($uri);
 8219: #    $path     = dirname($uri);
 8220: #    return ($filename, $path);
 8221: #
 8222: #     The implementation below is probably faster however.
 8223: #
 8224: sub split_uri_for_cond {
 8225:     my $uri=&deversion(&declutter(shift));
 8226:     my @uriparts=split(/\//,$uri);
 8227:     my $filename=pop(@uriparts);
 8228:     my $pathname=join('/',@uriparts);
 8229:     return ($pathname,$filename);
 8230: }
 8231: # --------------------------------------------------- Is a resource on the map?
 8232: 
 8233: sub is_on_map {
 8234:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8235:     #Trying to find the conditional for the file
 8236:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8237: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8238:     if ($match) {
 8239: 	return (1,$1);
 8240:     } else {
 8241: 	return (0,0);
 8242:     }
 8243: }
 8244: 
 8245: # --------------------------------------------------------- Get symb from alias
 8246: 
 8247: sub get_symb_from_alias {
 8248:     my $symb=shift;
 8249:     my ($map,$resid,$url)=&decode_symb($symb);
 8250: # Already is a symb
 8251:     if ($url) { return $symb; }
 8252: # Must be an alias
 8253:     my $aliassymb='';
 8254:     my %bighash;
 8255:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8256:                             &GDBM_READER(),0640)) {
 8257:         my $rid=$bighash{'mapalias_'.$symb};
 8258: 	if ($rid) {
 8259: 	    my ($mapid,$resid)=split(/\./,$rid);
 8260: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8261: 				    $resid,$bighash{'src_'.$rid});
 8262: 	}
 8263:         untie %bighash;
 8264:     }
 8265:     return $aliassymb;
 8266: }
 8267: 
 8268: # ----------------------------------------------------------------- Define Role
 8269: 
 8270: sub definerole {
 8271:   if (allowed('mcr','/')) {
 8272:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8273:     foreach my $role (split(':',$sysrole)) {
 8274: 	my ($crole,$cqual)=split(/\&/,$role);
 8275:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8276:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8277: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8278:                return "refused:s:$crole&$cqual"; 
 8279:             }
 8280:         }
 8281:     }
 8282:     foreach my $role (split(':',$domrole)) {
 8283: 	my ($crole,$cqual)=split(/\&/,$role);
 8284:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8285:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8286: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8287:                return "refused:d:$crole&$cqual"; 
 8288:             }
 8289:         }
 8290:     }
 8291:     foreach my $role (split(':',$courole)) {
 8292: 	my ($crole,$cqual)=split(/\&/,$role);
 8293:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8294:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8295: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8296:                return "refused:c:$crole&$cqual"; 
 8297:             }
 8298:         }
 8299:     }
 8300:     my $uhome;
 8301:     if (($uname ne '') && ($udom ne '')) {
 8302:         $uhome = &homeserver($uname,$udom);
 8303:         return $uhome if ($uhome eq 'no_host');
 8304:     } else {
 8305:         $uname = $env{'user.name'};
 8306:         $udom = $env{'user.domain'};
 8307:         $uhome = $env{'user.home'};
 8308:     }
 8309:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8310:                 "$udom:$uname:rolesdef_$rolename=".
 8311:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8312:     return reply($command,$uhome);
 8313:   } else {
 8314:     return 'refused';
 8315:   }
 8316: }
 8317: 
 8318: # ---------------- Make a metadata query against the network of library servers
 8319: 
 8320: sub metadata_query {
 8321:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8322:     my %rhash;
 8323:     my %libserv = &all_library();
 8324:     my @server_list = (defined($server_array) ? @$server_array
 8325:                                               : keys(%libserv) );
 8326:     for my $server (@server_list) {
 8327:         my $domains = ''; 
 8328:         if (ref($domains_hash) eq 'HASH') {
 8329:             $domains = $domains_hash->{$server}; 
 8330:         }
 8331: 	unless ($custom or $customshow) {
 8332: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8333: 	    $rhash{$server}=$reply;
 8334: 	}
 8335: 	else {
 8336: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8337: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8338: 			     $server);
 8339: 	    $rhash{$server}=$reply;
 8340: 	}
 8341:     }
 8342:     return \%rhash;
 8343: }
 8344: 
 8345: # ----------------------------------------- Send log queries and wait for reply
 8346: 
 8347: sub log_query {
 8348:     my ($uname,$udom,$query,%filters)=@_;
 8349:     my $uhome=&homeserver($uname,$udom);
 8350:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8351:     my $uhost=&hostname($uhome);
 8352:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8353:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8354:                        $uhome);
 8355:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8356:     return get_query_reply($queryid);
 8357: }
 8358: 
 8359: # -------------------------- Update MySQL table for portfolio file
 8360: 
 8361: sub update_portfolio_table {
 8362:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8363:     if ($group ne '') {
 8364:         $file_name =~s /^\Q$group\E//;
 8365:     }
 8366:     my $homeserver = &homeserver($uname,$udom);
 8367:     my $queryid=
 8368:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8369:                ':'.&escape($file_name).':'.$action,$homeserver);
 8370:     my $reply = &get_query_reply($queryid);
 8371:     return $reply;
 8372: }
 8373: 
 8374: # -------------------------- Update MySQL allusers table
 8375: 
 8376: sub update_allusers_table {
 8377:     my ($uname,$udom,$names) = @_;
 8378:     my $homeserver = &homeserver($uname,$udom);
 8379:     my $queryid=
 8380:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8381:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8382:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8383:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8384:                'generation='.&escape($names->{'generation'}).'%%'.
 8385:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8386:                'id='.&escape($names->{'id'}),$homeserver);
 8387:     return;
 8388: }
 8389: 
 8390: # ------- Request retrieval of institutional classlists for course(s)
 8391: 
 8392: sub fetch_enrollment_query {
 8393:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8394:     my ($homeserver,$sleep,$loopmax);
 8395:     my $maxtries = 1;
 8396:     if ($context eq 'automated') {
 8397:         $homeserver = $perlvar{'lonHostID'};
 8398:         $sleep = 2;
 8399:         $loopmax = 100;
 8400:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8401:     } else {
 8402:         $homeserver = &homeserver($cnum,$dom);
 8403:     }
 8404:     my $host=&hostname($homeserver);
 8405:     my $cmd = '';
 8406:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8407:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8408:     }
 8409:     $cmd =~ s/%%$//;
 8410:     $cmd = &escape($cmd);
 8411:     my $query = 'fetchenrollment';
 8412:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8413:     unless ($queryid=~/^\Q$host\E\_/) { 
 8414:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8415:         return 'error: '.$queryid;
 8416:     }
 8417:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8418:     my $tries = 1;
 8419:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8420:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8421:         $tries ++;
 8422:     }
 8423:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8424:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8425:     } else {
 8426:         my @responses = split(/:/,$reply);
 8427:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8428:             foreach my $line (@responses) {
 8429:                 my ($key,$value) = split(/=/,$line,2);
 8430:                 $$replyref{$key} = $value;
 8431:             }
 8432:         } else {
 8433:             my $pathname = LONCAPA::tempdir();
 8434:             foreach my $line (@responses) {
 8435:                 my ($key,$value) = split(/=/,$line);
 8436:                 $$replyref{$key} = $value;
 8437:                 if ($value > 0) {
 8438:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8439:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8440:                         my $destname = $pathname.'/'.$filename;
 8441:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8442:                         if ($xml_classlist =~ /^error/) {
 8443:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8444:                         } else {
 8445:                             if ( open(FILE,">$destname") ) {
 8446:                                 print FILE &unescape($xml_classlist);
 8447:                                 close(FILE);
 8448:                             } else {
 8449:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8450:                             }
 8451:                         }
 8452:                     }
 8453:                 }
 8454:             }
 8455:         }
 8456:         return 'ok';
 8457:     }
 8458:     return 'error';
 8459: }
 8460: 
 8461: sub get_query_reply {
 8462:     my ($queryid,$sleep,$loopmax) = @_;;
 8463:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8464:         $sleep = 0.2;
 8465:     }
 8466:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8467:         $loopmax = 100;
 8468:     }
 8469:     my $replyfile=LONCAPA::tempdir().$queryid;
 8470:     my $reply='';
 8471:     for (1..$loopmax) {
 8472: 	sleep($sleep);
 8473:         if (-e $replyfile.'.end') {
 8474: 	    if (open(my $fh,$replyfile)) {
 8475: 		$reply = join('',<$fh>);
 8476: 		close($fh);
 8477: 	   } else { return 'error: reply_file_error'; }
 8478:            return &unescape($reply);
 8479: 	}
 8480:     }
 8481:     return 'timeout:'.$queryid;
 8482: }
 8483: 
 8484: sub courselog_query {
 8485: #
 8486: # possible filters:
 8487: # url: url or symb
 8488: # username
 8489: # domain
 8490: # action: view, submit, grade
 8491: # start: timestamp
 8492: # end: timestamp
 8493: #
 8494:     my (%filters)=@_;
 8495:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8496:     if ($filters{'url'}) {
 8497: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8498:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8499:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8500:     }
 8501:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8502:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8503:     return &log_query($cname,$cdom,'courselog',%filters);
 8504: }
 8505: 
 8506: sub userlog_query {
 8507: #
 8508: # possible filters:
 8509: # action: log check role
 8510: # start: timestamp
 8511: # end: timestamp
 8512: #
 8513:     my ($uname,$udom,%filters)=@_;
 8514:     return &log_query($uname,$udom,'userlog',%filters);
 8515: }
 8516: 
 8517: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8518: 
 8519: sub auto_run {
 8520:     my ($cnum,$cdom) = @_;
 8521:     my $response = 0;
 8522:     my $settings;
 8523:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8524:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8525:         $settings = $domconfig{'autoenroll'};
 8526:         if ($settings->{'run'} eq '1') {
 8527:             $response = 1;
 8528:         }
 8529:     } else {
 8530:         my $homeserver;
 8531:         if (&is_course($cdom,$cnum)) {
 8532:             $homeserver = &homeserver($cnum,$cdom);
 8533:         } else {
 8534:             $homeserver = &domain($cdom,'primary');
 8535:         }
 8536:         if ($homeserver ne 'no_host') {
 8537:             $response = &reply('autorun:'.$cdom,$homeserver);
 8538:         }
 8539:     }
 8540:     return $response;
 8541: }
 8542: 
 8543: sub auto_get_sections {
 8544:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8545:     my $homeserver;
 8546:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8547:         $homeserver = &homeserver($cnum,$cdom);
 8548:     }
 8549:     if (!defined($homeserver)) { 
 8550:         if ($cdom =~ /^$match_domain$/) {
 8551:             $homeserver = &domain($cdom,'primary');
 8552:         }
 8553:     }
 8554:     my @secs;
 8555:     if (defined($homeserver)) {
 8556:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8557:         unless ($response eq 'refused') {
 8558:             @secs = split(/:/,$response);
 8559:         }
 8560:     }
 8561:     return @secs;
 8562: }
 8563: 
 8564: sub auto_new_course {
 8565:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8566:     my $homeserver = &homeserver($cnum,$cdom);
 8567:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8568:     return $response;
 8569: }
 8570: 
 8571: sub auto_validate_courseID {
 8572:     my ($cnum,$cdom,$inst_course_id) = @_;
 8573:     my $homeserver = &homeserver($cnum,$cdom);
 8574:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8575:     return $response;
 8576: }
 8577: 
 8578: sub auto_validate_instcode {
 8579:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8580:     my ($homeserver,$response);
 8581:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8582:         $homeserver = &homeserver($cnum,$cdom);
 8583:     }
 8584:     if (!defined($homeserver)) {
 8585:         if ($cdom =~ /^$match_domain$/) {
 8586:             $homeserver = &domain($cdom,'primary');
 8587:         }
 8588:     }
 8589:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8590:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8591:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8592:     return ($outcome,$description,$defaultcredits);
 8593: }
 8594: 
 8595: sub auto_create_password {
 8596:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8597:     my ($homeserver,$response);
 8598:     my $create_passwd = 0;
 8599:     my $authchk = '';
 8600:     if ($udom =~ /^$match_domain$/) {
 8601:         $homeserver = &domain($udom,'primary');
 8602:     }
 8603:     if ($homeserver eq '') {
 8604:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8605:             $homeserver = &homeserver($cnum,$cdom);
 8606:         }
 8607:     }
 8608:     if ($homeserver eq '') {
 8609:         $authchk = 'nodomain';
 8610:     } else {
 8611:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8612:         if ($response eq 'refused') {
 8613:             $authchk = 'refused';
 8614:         } else {
 8615:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8616:         }
 8617:     }
 8618:     return ($authparam,$create_passwd,$authchk);
 8619: }
 8620: 
 8621: sub auto_photo_permission {
 8622:     my ($cnum,$cdom,$students) = @_;
 8623:     my $homeserver = &homeserver($cnum,$cdom);
 8624:     my ($outcome,$perm_reqd,$conditions) = 
 8625: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8626:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8627: 	return (undef,undef);
 8628:     }
 8629:     return ($outcome,$perm_reqd,$conditions);
 8630: }
 8631: 
 8632: sub auto_checkphotos {
 8633:     my ($uname,$udom,$pid) = @_;
 8634:     my $homeserver = &homeserver($uname,$udom);
 8635:     my ($result,$resulttype);
 8636:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8637: 				   &escape($uname).':'.&escape($pid),
 8638: 				   $homeserver));
 8639:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8640: 	return (undef,undef);
 8641:     }
 8642:     if ($outcome) {
 8643:         ($result,$resulttype) = split(/:/,$outcome);
 8644:     } 
 8645:     return ($result,$resulttype);
 8646: }
 8647: 
 8648: sub auto_photochoice {
 8649:     my ($cnum,$cdom) = @_;
 8650:     my $homeserver = &homeserver($cnum,$cdom);
 8651:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8652: 						       &escape($cdom),
 8653: 						       $homeserver)));
 8654:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8655: 	return (undef,undef);
 8656:     }
 8657:     return ($update,$comment);
 8658: }
 8659: 
 8660: sub auto_photoupdate {
 8661:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8662:     my $homeserver = &homeserver($cnum,$dom);
 8663:     my $host=&hostname($homeserver);
 8664:     my $cmd = '';
 8665:     my $maxtries = 1;
 8666:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8667:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8668:     }
 8669:     $cmd =~ s/%%$//;
 8670:     $cmd = &escape($cmd);
 8671:     my $query = 'institutionalphotos';
 8672:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8673:     unless ($queryid=~/^\Q$host\E\_/) {
 8674:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8675:         return 'error: '.$queryid;
 8676:     }
 8677:     my $reply = &get_query_reply($queryid);
 8678:     my $tries = 1;
 8679:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8680:         $reply = &get_query_reply($queryid);
 8681:         $tries ++;
 8682:     }
 8683:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8684:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8685:     } else {
 8686:         my @responses = split(/:/,$reply);
 8687:         my $outcome = shift(@responses); 
 8688:         foreach my $item (@responses) {
 8689:             my ($key,$value) = split(/=/,$item);
 8690:             $$photo{$key} = $value;
 8691:         }
 8692:         return $outcome;
 8693:     }
 8694:     return 'error';
 8695: }
 8696: 
 8697: sub auto_instcode_format {
 8698:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8699: 	$cat_order) = @_;
 8700:     my $courses = '';
 8701:     my @homeservers;
 8702:     if ($caller eq 'global') {
 8703: 	my %servers = &get_servers($codedom,'library');
 8704: 	foreach my $tryserver (keys(%servers)) {
 8705: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8706: 		push(@homeservers,$tryserver);
 8707: 	    }
 8708:         }
 8709:     } elsif ($caller eq 'requests') {
 8710:         if ($codedom =~ /^$match_domain$/) {
 8711:             my $chome = &domain($codedom,'primary');
 8712:             unless ($chome eq 'no_host') {
 8713:                 push(@homeservers,$chome);
 8714:             }
 8715:         }
 8716:     } else {
 8717:         push(@homeservers,&homeserver($caller,$codedom));
 8718:     }
 8719:     foreach my $code (keys(%{$instcodes})) {
 8720:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8721:     }
 8722:     chop($courses);
 8723:     my $ok_response = 0;
 8724:     my $response;
 8725:     while (@homeservers > 0 && $ok_response == 0) {
 8726:         my $server = shift(@homeservers); 
 8727:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8728:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8729:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8730: 		split(/:/,$response);
 8731:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8732:             push(@{$codetitles},&str2array($codetitles_str));
 8733:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8734:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8735:             $ok_response = 1;
 8736:         }
 8737:     }
 8738:     if ($ok_response) {
 8739:         return 'ok';
 8740:     } else {
 8741:         return $response;
 8742:     }
 8743: }
 8744: 
 8745: sub auto_instcode_defaults {
 8746:     my ($domain,$returnhash,$code_order) = @_;
 8747:     my @homeservers;
 8748: 
 8749:     my %servers = &get_servers($domain,'library');
 8750:     foreach my $tryserver (keys(%servers)) {
 8751: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8752: 	    push(@homeservers,$tryserver);
 8753: 	}
 8754:     }
 8755: 
 8756:     my $response;
 8757:     foreach my $server (@homeservers) {
 8758:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8759:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8760: 	
 8761: 	foreach my $pair (split(/\&/,$response)) {
 8762: 	    my ($name,$value)=split(/\=/,$pair);
 8763: 	    if ($name eq 'code_order') {
 8764: 		@{$code_order} = split(/\&/,&unescape($value));
 8765: 	    } else {
 8766: 		$returnhash->{&unescape($name)}=&unescape($value);
 8767: 	    }
 8768: 	}
 8769: 	return 'ok';
 8770:     }
 8771: 
 8772:     return $response;
 8773: }
 8774: 
 8775: sub auto_possible_instcodes {
 8776:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8777:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8778:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8779:         return;
 8780:     }
 8781:     my (@homeservers,$uhome);
 8782:     if (defined(&domain($domain,'primary'))) {
 8783:         $uhome=&domain($domain,'primary');
 8784:         push(@homeservers,&domain($domain,'primary'));
 8785:     } else {
 8786:         my %servers = &get_servers($domain,'library');
 8787:         foreach my $tryserver (keys(%servers)) {
 8788:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8789:                 push(@homeservers,$tryserver);
 8790:             }
 8791:         }
 8792:     }
 8793:     my $response;
 8794:     foreach my $server (@homeservers) {
 8795:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8796:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8797:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8798:             split(':',$response);
 8799:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8800:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8801:         foreach my $item (split('&',$cat_title)) {   
 8802:             my ($name,$value)=split('=',$item);
 8803:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8804:         }
 8805:         foreach my $item (split('&',$cat_order)) {
 8806:             my ($name,$value)=split('=',$item);
 8807:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8808:         }
 8809:         return 'ok';
 8810:     }
 8811:     return $response;
 8812: }
 8813: 
 8814: sub auto_courserequest_checks {
 8815:     my ($dom) = @_;
 8816:     my ($homeserver,%validations);
 8817:     if ($dom =~ /^$match_domain$/) {
 8818:         $homeserver = &domain($dom,'primary');
 8819:     }
 8820:     unless ($homeserver eq 'no_host') {
 8821:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8822:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8823:             my @items = split(/&/,$response);
 8824:             foreach my $item (@items) {
 8825:                 my ($key,$value) = split('=',$item);
 8826:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8827:             }
 8828:         }
 8829:     }
 8830:     return %validations; 
 8831: }
 8832: 
 8833: sub auto_courserequest_validation {
 8834:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8835:     my ($homeserver,$response);
 8836:     if ($dom =~ /^$match_domain$/) {
 8837:         $homeserver = &domain($dom,'primary');
 8838:     }
 8839:     unless ($homeserver eq 'no_host') {
 8840:         my $customdata;
 8841:         if (ref($custominfo) eq 'HASH') {
 8842:             $customdata = &freeze_escape($custominfo);
 8843:         }
 8844:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8845:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8846:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8847:                                     $customdata,$homeserver));
 8848:     }
 8849:     return $response;
 8850: }
 8851: 
 8852: sub auto_validate_class_sec {
 8853:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8854:     my $homeserver = &homeserver($cnum,$cdom);
 8855:     my $ownerlist;
 8856:     if (ref($owners) eq 'ARRAY') {
 8857:         $ownerlist = join(',',@{$owners});
 8858:     } else {
 8859:         $ownerlist = $owners;
 8860:     }
 8861:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8862:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8863:     return $response;
 8864: }
 8865: 
 8866: sub auto_crsreq_update {
 8867:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8868:         $code,$accessstart,$accessend,$inbound) = @_;
 8869:     my ($homeserver,%crsreqresponse);
 8870:     if ($cdom =~ /^$match_domain$/) {
 8871:         $homeserver = &domain($cdom,'primary');
 8872:     }
 8873:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8874:         my $info;
 8875:         if (ref($inbound) eq 'HASH') {
 8876:             $info = &freeze_escape($inbound);
 8877:         }
 8878:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8879:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8880:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8881:                             &escape($title).':'.&escape($code).':'.
 8882:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8883:                             $homeserver);
 8884:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8885:             my @items = split(/&/,$response);
 8886:             foreach my $item (@items) {
 8887:                 my ($key,$value) = split('=',$item);
 8888:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8889:             }
 8890:         }
 8891:     }
 8892:     return \%crsreqresponse;
 8893: }
 8894: 
 8895: sub auto_export_grades {
 8896:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8897:     my ($homeserver,%exportresponse);
 8898:     if ($cdom =~ /^$match_domain$/) {
 8899:         $homeserver = &domain($cdom,'primary');
 8900:     }
 8901:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8902:         my $info;
 8903:         if (ref($inforef) eq 'HASH') {
 8904:             $info = &freeze_escape($inforef);
 8905:         }
 8906:         if (ref($gradesref) eq 'HASH') {
 8907:             my $grades = &freeze_escape($gradesref);
 8908:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8909:                                 $info.':'.$grades,$homeserver);
 8910:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8911:                 my @items = split(/&/,$response);
 8912:                 foreach my $item (@items) {
 8913:                     my ($key,$value) = split('=',$item);
 8914:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8915:                 }
 8916:             }
 8917:         }
 8918:     }
 8919:     return \%exportresponse;
 8920: }
 8921: 
 8922: sub check_instcode_cloning {
 8923:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8924:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8925:         return;
 8926:     }
 8927:     my $canclone;
 8928:     if (@{$code_order} > 0) {
 8929:         my $instcoderegexp ='^';
 8930:         my @clonecodes = split(/\&/,$cloner);
 8931:         foreach my $item (@{$code_order}) {
 8932:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8933:                 foreach my $pair (@clonecodes) {
 8934:                     my ($key,$val) = split(/\=/,$pair,2);
 8935:                     $val = &unescape($val);
 8936:                     if ($key eq $item) {
 8937:                         $instcoderegexp .= '('.$val.')';
 8938:                         last;
 8939:                     }
 8940:                 }
 8941:             } else {
 8942:                 $instcoderegexp .= $codedefaults->{$item};
 8943:             }
 8944:         }
 8945:         $instcoderegexp .= '$';
 8946:         my (@from,@to);
 8947:         eval {
 8948:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8949:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8950:         };
 8951:         if ((@from > 0) && (@to > 0)) {
 8952:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8953:             if (!@diffs) {
 8954:                 $canclone = 1;
 8955:             }
 8956:         }
 8957:     }
 8958:     return $canclone;
 8959: }
 8960: 
 8961: sub default_instcode_cloning {
 8962:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8963:     my (%codedefaults,@code_order,$canclone);
 8964:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8965:         %codedefaults = %{$codedefaultsref};
 8966:         @code_order = @{$codeorderref};
 8967:     } elsif ($clonedom) {
 8968:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8969:     }
 8970:     if (($domdefclone) && (@code_order)) {
 8971:         my @clonecodes = split(/\+/,$domdefclone);
 8972:         my $instcoderegexp ='^';
 8973:         foreach my $item (@code_order) {
 8974:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8975:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8976:             } else {
 8977:                 $instcoderegexp .= $codedefaults{$item};
 8978:             }
 8979:         }
 8980:         $instcoderegexp .= '$';
 8981:         my (@from,@to);
 8982:         eval {
 8983:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8984:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 8985:         };
 8986:         if ((@from > 0) && (@to > 0)) {
 8987:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8988:             if (!@diffs) {
 8989:                 $canclone = 1;
 8990:             }
 8991:         }
 8992:     }
 8993:     return $canclone;
 8994: }
 8995: 
 8996: # ------------------------------------------------------- Course Group routines
 8997: 
 8998: sub get_coursegroups {
 8999:     my ($cdom,$cnum,$group,$namespace) = @_;
 9000:     return(&dump($namespace,$cdom,$cnum,$group));
 9001: }
 9002: 
 9003: sub modify_coursegroup {
 9004:     my ($cdom,$cnum,$groupsettings) = @_;
 9005:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9006: }
 9007: 
 9008: sub toggle_coursegroup_status {
 9009:     my ($cdom,$cnum,$group,$action) = @_;
 9010:     my ($from_namespace,$to_namespace);
 9011:     if ($action eq 'delete') {
 9012:         $from_namespace = 'coursegroups';
 9013:         $to_namespace = 'deleted_groups';
 9014:     } else {
 9015:         $from_namespace = 'deleted_groups';
 9016:         $to_namespace = 'coursegroups';
 9017:     }
 9018:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9019:     if (my $tmp = &error(%curr_group)) {
 9020:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9021:         return ('read error',$tmp);
 9022:     } else {
 9023:         my %savedsettings = %curr_group; 
 9024:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9025:         my $deloutcome;
 9026:         if ($result eq 'ok') {
 9027:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9028:         } else {
 9029:             return ('write error',$result);
 9030:         }
 9031:         if ($deloutcome eq 'ok') {
 9032:             return 'ok';
 9033:         } else {
 9034:             return ('delete error',$deloutcome);
 9035:         }
 9036:     }
 9037: }
 9038: 
 9039: sub modify_group_roles {
 9040:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9041:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9042:     my $role = 'gr/'.&escape($userprivs);
 9043:     my ($uname,$udom) = split(/:/,$user);
 9044:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9045:     if ($result eq 'ok') {
 9046:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9047:     }
 9048:     return $result;
 9049: }
 9050: 
 9051: sub modify_coursegroup_membership {
 9052:     my ($cdom,$cnum,$membership) = @_;
 9053:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9054:     return $result;
 9055: }
 9056: 
 9057: sub get_active_groups {
 9058:     my ($udom,$uname,$cdom,$cnum) = @_;
 9059:     my $now = time;
 9060:     my %groups = ();
 9061:     foreach my $key (keys(%env)) {
 9062:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9063:             my ($start,$end) = split(/\./,$env{$key});
 9064:             if (($end!=0) && ($end<$now)) { next; }
 9065:             if (($start!=0) && ($start>$now)) { next; }
 9066:             if ($1 eq $cdom && $2 eq $cnum) {
 9067:                 $groups{$3} = $env{$key} ;
 9068:             }
 9069:         }
 9070:     }
 9071:     return %groups;
 9072: }
 9073: 
 9074: sub get_group_membership {
 9075:     my ($cdom,$cnum,$group) = @_;
 9076:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9077: }
 9078: 
 9079: sub get_users_groups {
 9080:     my ($udom,$uname,$courseid) = @_;
 9081:     my @usersgroups;
 9082:     my $cachetime=1800;
 9083: 
 9084:     my $hashid="$udom:$uname:$courseid";
 9085:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9086:     if (defined($cached)) {
 9087:         @usersgroups = split(/:/,$grouplist);
 9088:     } else {  
 9089:         $grouplist = '';
 9090:         my $courseurl = &courseid_to_courseurl($courseid);
 9091:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9092:         my $access_end = $env{'course.'.$courseid.
 9093:                               '.default_enrollment_end_date'};
 9094:         my $now = time;
 9095:         foreach my $key (keys(%roleshash)) {
 9096:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9097:                 my $group = $1;
 9098:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9099:                     my $start = $2;
 9100:                     my $end = $1;
 9101:                     if ($start == -1) { next; } # deleted from group
 9102:                     if (($start!=0) && ($start>$now)) { next; }
 9103:                     if (($end!=0) && ($end<$now)) {
 9104:                         if ($access_end && $access_end < $now) {
 9105:                             if ($access_end - $end < 86400) {
 9106:                                 push(@usersgroups,$group);
 9107:                             }
 9108:                         }
 9109:                         next;
 9110:                     }
 9111:                     push(@usersgroups,$group);
 9112:                 }
 9113:             }
 9114:         }
 9115:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9116:         $grouplist = join(':',@usersgroups);
 9117:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9118:     }
 9119:     return @usersgroups;
 9120: }
 9121: 
 9122: sub devalidate_getgroups_cache {
 9123:     my ($udom,$uname,$cdom,$cnum)=@_;
 9124:     my $courseid = $cdom.'_'.$cnum;
 9125: 
 9126:     my $hashid="$udom:$uname:$courseid";
 9127:     &devalidate_cache_new('getgroups',$hashid);
 9128: }
 9129: 
 9130: # ------------------------------------------------------------------ Plain Text
 9131: 
 9132: sub plaintext {
 9133:     my ($short,$type,$cid,$forcedefault) = @_;
 9134:     if ($short =~ m{^cr/}) {
 9135: 	return (split('/',$short))[-1];
 9136:     }
 9137:     if (!defined($cid)) {
 9138:         $cid = $env{'request.course.id'};
 9139:     }
 9140:     my %rolenames = (
 9141:                       Course    => 'std',
 9142:                       Community => 'alt1',
 9143:                       Placement => 'std',
 9144:                     );
 9145:     if ($cid ne '') {
 9146:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9147:             unless ($forcedefault) {
 9148:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9149:                 &Apache::lonlocal::mt_escape(\$roletext);
 9150:                 return &Apache::lonlocal::mt($roletext);
 9151:             }
 9152:         }
 9153:     }
 9154:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9155:         (defined($rolenames{$type})) && 
 9156:         (defined($prp{$short}{$rolenames{$type}}))) {
 9157:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9158:     } elsif ($cid ne '') {
 9159:         my $crstype = $env{'course.'.$cid.'.type'};
 9160:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9161:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9162:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9163:         }
 9164:     }
 9165:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9166: }
 9167: 
 9168: # ----------------------------------------------------------------- Assign Role
 9169: 
 9170: sub assignrole {
 9171:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9172:         $context)=@_;
 9173:     my $mrole;
 9174:     if ($role =~ /^cr\//) {
 9175:         my $cwosec=$url;
 9176:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9177: 	unless (&allowed('ccr',$cwosec)) {
 9178:            my $refused = 1;
 9179:            if ($context eq 'requestcourses') {
 9180:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9181:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9182:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9183:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9184:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9185:                            if ($crsenv{'internal.courseowner'} eq
 9186:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9187:                                $refused = '';
 9188:                            }
 9189:                        }
 9190:                    }
 9191:                }
 9192:            }
 9193:            if ($refused) {
 9194:                &logthis('Refused custom assignrole: '.
 9195:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9196:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9197:                return 'refused';
 9198:            }
 9199:         }
 9200:         $mrole='cr';
 9201:     } elsif ($role =~ /^gr\//) {
 9202:         my $cwogrp=$url;
 9203:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9204:         unless (&allowed('mdg',$cwogrp)) {
 9205:             &logthis('Refused group assignrole: '.
 9206:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9207:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9208:             return 'refused';
 9209:         }
 9210:         $mrole='gr';
 9211:     } else {
 9212:         my $cwosec=$url;
 9213:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9214:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9215:             my $refused;
 9216:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9217:                 if (!(&allowed('c'.$role,$url))) {
 9218:                     $refused = 1;
 9219:                 }
 9220:             } else {
 9221:                 $refused = 1;
 9222:             }
 9223:             if ($refused) {
 9224:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9225:                 if (!$selfenroll && $context eq 'course') {
 9226:                     my %crsenv;
 9227:                     if ($role eq 'cc' || $role eq 'co') {
 9228:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9229:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9230:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9231:                                 if ($crsenv{'internal.courseowner'} eq 
 9232:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9233:                                     $refused = '';
 9234:                                 }
 9235:                             }
 9236:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9237:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9238:                                 if ($crsenv{'internal.courseowner'} eq 
 9239:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9240:                                     $refused = '';
 9241:                                 }
 9242:                             }
 9243:                         }
 9244:                     }
 9245:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9246:                     $refused = '';
 9247:                 } elsif ($context eq 'requestcourses') {
 9248:                     my @possroles = ('st','ta','ep','in','cc','co');
 9249:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9250:                         my $wrongcc;
 9251:                         if ($cnum =~ /^$match_community$/) {
 9252:                             $wrongcc = 1 if ($role eq 'cc');
 9253:                         } else {
 9254:                             $wrongcc = 1 if ($role eq 'co');
 9255:                         }
 9256:                         unless ($wrongcc) {
 9257:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9258:                             if ($crsenv{'internal.courseowner'} eq 
 9259:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9260:                                 $refused = '';
 9261:                             }
 9262:                         }
 9263:                     }
 9264:                 } elsif ($context eq 'requestauthor') {
 9265:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9266:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9267:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9268:                             $refused = '';
 9269:                         } else {
 9270:                             my %domdefaults = &get_domain_defaults($udom);
 9271:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9272:                                 my $checkbystatus;
 9273:                                 if ($env{'user.adv'}) { 
 9274:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9275:                                     if ($disposition eq 'automatic') {
 9276:                                         $refused = '';
 9277:                                     } elsif ($disposition eq '') {
 9278:                                         $checkbystatus = 1;
 9279:                                     } 
 9280:                                 } else {
 9281:                                     $checkbystatus = 1;
 9282:                                 }
 9283:                                 if ($checkbystatus) {
 9284:                                     if ($env{'environment.inststatus'}) {
 9285:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9286:                                         foreach my $type (@inststatuses) {
 9287:                                             if (($type ne '') &&
 9288:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9289:                                                 $refused = '';
 9290:                                             }
 9291:                                         }
 9292:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9293:                                         $refused = '';
 9294:                                     }
 9295:                                 }
 9296:                             }
 9297:                         }
 9298:                     }
 9299:                 }
 9300:                 if ($refused) {
 9301:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9302:                              ' '.$role.' '.$end.' '.$start.' by '.
 9303: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9304:                     return 'refused';
 9305:                 }
 9306:             }
 9307:         } elsif ($role eq 'au') {
 9308:             if ($url ne '/'.$udom.'/') {
 9309:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9310:                          ' to assign author role for '.$uname.':'.$udom.
 9311:                          ' in domain: '.$url.' refused (wrong domain).');
 9312:                 return 'refused';
 9313:             }
 9314:         }
 9315:         $mrole=$role;
 9316:     }
 9317:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9318:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9319:     if ($end) { $command.='_'.$end; }
 9320:     if ($start) {
 9321: 	if ($end) { 
 9322:            $command.='_'.$start; 
 9323:         } else {
 9324:            $command.='_0_'.$start;
 9325:         }
 9326:     }
 9327:     my $origstart = $start;
 9328:     my $origend = $end;
 9329:     my $delflag;
 9330: # actually delete
 9331:     if ($deleteflag) {
 9332: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9333: # modify command to delete the role
 9334:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9335:                 "$udom:$uname:$url".'_'."$mrole";
 9336: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9337: # set start and finish to negative values for userrolelog
 9338:            $start=-1;
 9339:            $end=-1;
 9340:            $delflag = 1;
 9341:         }
 9342:     }
 9343: # send command
 9344:     my $answer=&reply($command,&homeserver($uname,$udom));
 9345: # log new user role if status is ok
 9346:     if ($answer eq 'ok') {
 9347: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9348:         if (($role eq 'cc') || ($role eq 'in') ||
 9349:             ($role eq 'ep') || ($role eq 'ad') ||
 9350:             ($role eq 'ta') || ($role eq 'st') ||
 9351:             ($role=~/^cr/) || ($role eq 'gr') ||
 9352:             ($role eq 'co')) {
 9353: # for course roles, perform group memberships changes triggered by role change.
 9354:             unless ($role =~ /^gr/) {
 9355:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9356:                                                  $origstart,$selfenroll,$context);
 9357:             }
 9358:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9359:                            $selfenroll,$context);
 9360:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9361:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9362:                  ($role eq 'da')) {
 9363:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9364:                            $context);
 9365:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9366:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9367:                              $context); 
 9368:         }
 9369:         if ($role eq 'cc') {
 9370:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9371:         }
 9372:     }
 9373:     return $answer;
 9374: }
 9375: 
 9376: sub autoupdate_coowners {
 9377:     my ($url,$end,$start,$uname,$udom) = @_;
 9378:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9379:     if (($cdom ne '') && ($cnum ne '')) {
 9380:         my $now = time;
 9381:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9382:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9383:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9384:             my $instcode = $coursehash{'internal.coursecode'};
 9385:             if ($instcode ne '') {
 9386:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9387:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9388:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9389:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9390:                         if ($result eq 'valid') {
 9391:                             if ($coursehash{'internal.co-owners'}) {
 9392:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9393:                                     push(@newcoowners,$coowner);
 9394:                                 }
 9395:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9396:                                     push(@newcoowners,$uname.':'.$udom);
 9397:                                 }
 9398:                                 @newcoowners = sort(@newcoowners);
 9399:                             } else {
 9400:                                 push(@newcoowners,$uname.':'.$udom);
 9401:                             }
 9402:                         } else {
 9403:                             if ($coursehash{'internal.co-owners'}) {
 9404:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9405:                                     unless ($coowner eq $uname.':'.$udom) {
 9406:                                         push(@newcoowners,$coowner);
 9407:                                     }
 9408:                                 }
 9409:                                 unless (@newcoowners > 0) {
 9410:                                     $delcoowners = 1;
 9411:                                     $coowners = '';
 9412:                                 }
 9413:                             }
 9414:                         }
 9415:                         if (@newcoowners || $delcoowners) {
 9416:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9417:                                             $delcoowners,@newcoowners);
 9418:                         }
 9419:                     }
 9420:                 }
 9421:             }
 9422:         }
 9423:     }
 9424: }
 9425: 
 9426: sub store_coowners {
 9427:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9428:     my $cid = $cdom.'_'.$cnum;
 9429:     my ($coowners,$delresult,$putresult);
 9430:     if (@newcoowners) {
 9431:         $coowners = join(',',@newcoowners);
 9432:         my %coownershash = (
 9433:                             'internal.co-owners' => $coowners,
 9434:                            );
 9435:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9436:         if ($putresult eq 'ok') {
 9437:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9438:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9439:             }
 9440:         }
 9441:     }
 9442:     if ($delcoowners) {
 9443:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9444:         if ($delresult eq 'ok') {
 9445:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9446:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9447:             }
 9448:         }
 9449:     }
 9450:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9451:         my %crsinfo =
 9452:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9453:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9454:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9455:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9456:         }
 9457:     }
 9458: }
 9459: 
 9460: # -------------------------------------------------- Modify user authentication
 9461: # Overrides without validation
 9462: 
 9463: sub modifyuserauth {
 9464:     my ($udom,$uname,$umode,$upass)=@_;
 9465:     my $uhome=&homeserver($uname,$udom);
 9466:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9467:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9468:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9469:              ' in domain '.$env{'request.role.domain'});  
 9470:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9471: 		     &escape($upass),$uhome);
 9472:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9473:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9474:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9475:     &log($udom,,$uname,$uhome,
 9476:         'Authentication changed by '.$env{'user.domain'}.', '.
 9477:                                      $env{'user.name'}.', '.$umode.
 9478:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9479:     unless ($reply eq 'ok') {
 9480:         &logthis('Authentication mode error: '.$reply);
 9481: 	return 'error: '.$reply;
 9482:     }   
 9483:     return 'ok';
 9484: }
 9485: 
 9486: # --------------------------------------------------------------- Modify a user
 9487: 
 9488: sub modifyuser {
 9489:     my ($udom,    $uname, $uid,
 9490:         $umode,   $upass, $first,
 9491:         $middle,  $last,  $gene,
 9492:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9493:     $udom= &LONCAPA::clean_domain($udom);
 9494:     $uname=&LONCAPA::clean_username($uname);
 9495:     my $showcandelete = 'none';
 9496:     if (ref($candelete) eq 'ARRAY') {
 9497:         if (@{$candelete} > 0) {
 9498:             $showcandelete = join(', ',@{$candelete});
 9499:         }
 9500:     }
 9501:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9502:              $umode.', '.$first.', '.$middle.', '.
 9503: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9504:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9505:                                      ' desiredhome not specified'). 
 9506:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9507:              ' in domain '.$env{'request.role.domain'});
 9508:     my $uhome=&homeserver($uname,$udom,'true');
 9509:     my $newuser;
 9510:     if ($uhome eq 'no_host') {
 9511:         $newuser = 1;
 9512:     }
 9513: # ----------------------------------------------------------------- Create User
 9514:     if (($uhome eq 'no_host') && 
 9515: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 9516:         my $unhome='';
 9517:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9518:             $unhome = $desiredhome;
 9519: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9520: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9521:         } else { # load balancing routine for determining $unhome
 9522:             my $loadm=10000000;
 9523: 	    my %servers = &get_servers($udom,'library');
 9524: 	    foreach my $tryserver (keys(%servers)) {
 9525: 		my $answer=reply('load',$tryserver);
 9526: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9527: 		    $loadm=$answer;
 9528: 		    $unhome=$tryserver;
 9529: 		}
 9530: 	    }
 9531:         }
 9532:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9533: 	    return 'error: unable to find a home server for '.$uname.
 9534:                    ' in domain '.$udom;
 9535:         }
 9536:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9537:                          &escape($upass),$unhome);
 9538: 	unless ($reply eq 'ok') {
 9539:             return 'error: '.$reply;
 9540:         }   
 9541:         $uhome=&homeserver($uname,$udom,'true');
 9542:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9543: 	    return 'error: unable verify users home machine.';
 9544:         }
 9545:     }   # End of creation of new user
 9546: # ---------------------------------------------------------------------- Add ID
 9547:     if ($uid) {
 9548:        $uid=~tr/A-Z/a-z/;
 9549:        my %uidhash=&idrget($udom,$uname);
 9550:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9551:          && (!$forceid)) {
 9552: 	  unless ($uid eq $uidhash{$uname}) {
 9553: 	      return 'error: user id "'.$uid.'" does not match '.
 9554:                   'current user id "'.$uidhash{$uname}.'".';
 9555:           }
 9556:        } else {
 9557: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9558:        }
 9559:     }
 9560: # -------------------------------------------------------------- Add names, etc
 9561:     my @tmp=&get('environment',
 9562: 		   ['firstname','middlename','lastname','generation','id',
 9563:                     'permanentemail','inststatus'],
 9564: 		   $udom,$uname);
 9565:     my (%names,%oldnames);
 9566:     if ($tmp[0] =~ m/^error:.*/) { 
 9567:         %names=(); 
 9568:     } else {
 9569:         %names = @tmp;
 9570:         %oldnames = %names;
 9571:     }
 9572: #
 9573: # If name, email and/or uid are blank (e.g., because an uploaded file
 9574: # of users did not contain them), do not overwrite existing values
 9575: # unless field is in $candelete array ref.  
 9576: #
 9577: 
 9578:     my @fields = ('firstname','middlename','lastname','generation',
 9579:                   'permanentemail','id');
 9580:     my %newvalues;
 9581:     if (ref($candelete) eq 'ARRAY') {
 9582:         foreach my $field (@fields) {
 9583:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9584:                 if ($field eq 'firstname') {
 9585:                     $names{$field} = $first;
 9586:                 } elsif ($field eq 'middlename') {
 9587:                     $names{$field} = $middle;
 9588:                 } elsif ($field eq 'lastname') {
 9589:                     $names{$field} = $last;
 9590:                 } elsif ($field eq 'generation') { 
 9591:                     $names{$field} = $gene;
 9592:                 } elsif ($field eq 'permanentemail') {
 9593:                     $names{$field} = $email;
 9594:                 } elsif ($field eq 'id') {
 9595:                     $names{$field}  = $uid;
 9596:                 }
 9597:             }
 9598:         }
 9599:     }
 9600:     if ($first)  { $names{'firstname'}  = $first; }
 9601:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9602:     if ($last)   { $names{'lastname'}   = $last; }
 9603:     if (defined($gene))   { $names{'generation'} = $gene; }
 9604:     if ($email) {
 9605:        $email=~s/[^\w\@\.\-\,]//gs;
 9606:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9607:     }
 9608:     if ($uid) { $names{'id'}  = $uid; }
 9609:     if (defined($inststatus)) {
 9610:         $names{'inststatus'} = '';
 9611:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9612:         if (ref($usertypes) eq 'HASH') {
 9613:             my @okstatuses; 
 9614:             foreach my $item (split(/:/,$inststatus)) {
 9615:                 if (defined($usertypes->{$item})) {
 9616:                     push(@okstatuses,$item);  
 9617:                 }
 9618:             }
 9619:             if (@okstatuses) {
 9620:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9621:             }
 9622:         }
 9623:     }
 9624:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9625:                  $umode.', '.$first.', '.$middle.', '.
 9626:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9627:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9628:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9629:     } else {
 9630:         $logmsg .= ' during self creation';
 9631:     }
 9632:     my $changed;
 9633:     if ($newuser) {
 9634:         $changed = 1;
 9635:     } else {
 9636:         foreach my $field (@fields) {
 9637:             if ($names{$field} ne $oldnames{$field}) {
 9638:                 $changed = 1;
 9639:                 last;
 9640:             }
 9641:         }
 9642:     }
 9643:     unless ($changed) {
 9644:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9645:         &logthis($logmsg);
 9646:         return 'ok';
 9647:     }
 9648:     my $reply = &put('environment', \%names, $udom,$uname);
 9649:     if ($reply ne 'ok') { 
 9650:         return 'error: '.$reply;
 9651:     }
 9652:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9653:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9654:     }
 9655:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9656:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9657:     $logmsg = 'Success modifying user '.$logmsg;
 9658:     &logthis($logmsg);
 9659:     return 'ok';
 9660: }
 9661: 
 9662: # -------------------------------------------------------------- Modify student
 9663: 
 9664: sub modifystudent {
 9665:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9666:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9667:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9668:     if (!$cid) {
 9669: 	unless ($cid=$env{'request.course.id'}) {
 9670: 	    return 'not_in_class';
 9671: 	}
 9672:     }
 9673: # --------------------------------------------------------------- Make the user
 9674:     my $reply=&modifyuser
 9675: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9676:          $desiredhome,$email,$inststatus);
 9677:     unless ($reply eq 'ok') { return $reply; }
 9678:     # This will cause &modify_student_enrollment to get the uid from the
 9679:     # student's environment
 9680:     $uid = undef if (!$forceid);
 9681:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9682:                                         $gene,$usec,$end,$start,$type,$locktype,
 9683:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9684:     return $reply;
 9685: }
 9686: 
 9687: sub modify_student_enrollment {
 9688:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9689:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9690:     my ($cdom,$cnum,$chome);
 9691:     if (!$cid) {
 9692: 	unless ($cid=$env{'request.course.id'}) {
 9693: 	    return 'not_in_class';
 9694: 	}
 9695: 	$cdom=$env{'course.'.$cid.'.domain'};
 9696: 	$cnum=$env{'course.'.$cid.'.num'};
 9697:     } else {
 9698: 	($cdom,$cnum)=split(/_/,$cid);
 9699:     }
 9700:     $chome=$env{'course.'.$cid.'.home'};
 9701:     if (!$chome) {
 9702: 	$chome=&homeserver($cnum,$cdom);
 9703:     }
 9704:     if (!$chome) { return 'unknown_course'; }
 9705:     # Make sure the user exists
 9706:     my $uhome=&homeserver($uname,$udom);
 9707:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9708: 	return 'error: no such user';
 9709:     }
 9710:     # Get student data if we were not given enough information
 9711:     if (!defined($first)  || $first  eq '' || 
 9712:         !defined($last)   || $last   eq '' || 
 9713:         !defined($uid)    || $uid    eq '' || 
 9714:         !defined($middle) || $middle eq '' || 
 9715:         !defined($gene)   || $gene   eq '') {
 9716:         # They did not supply us with enough data to enroll the student, so
 9717:         # we need to pick up more information.
 9718:         my %tmp = &get('environment',
 9719:                        ['firstname','middlename','lastname', 'generation','id']
 9720:                        ,$udom,$uname);
 9721: 
 9722:         #foreach my $key (keys(%tmp)) {
 9723:         #    &logthis("key $key = ".$tmp{$key});
 9724:         #}
 9725:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9726:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9727:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9728:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9729:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9730:     }
 9731:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9732:     my $user = "$uname:$udom";
 9733:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9734:     my $reply=cput('classlist',
 9735: 		   {$user => 
 9736: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9737: 		   $cdom,$cnum);
 9738:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9739:         &devalidate_getsection_cache($udom,$uname,$cid);
 9740:     } else { 
 9741: 	return 'error: '.$reply;
 9742:     }
 9743:     # Add student role to user
 9744:     my $uurl='/'.$cid;
 9745:     $uurl=~s/\_/\//g;
 9746:     if ($usec) {
 9747: 	$uurl.='/'.$usec;
 9748:     }
 9749:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9750:                              $selfenroll,$context);
 9751:     if ($result ne 'ok') {
 9752:         if ($old_entry{$user} ne '') {
 9753:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9754:         } else {
 9755:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9756:         }
 9757:     }
 9758:     return $result; 
 9759: }
 9760: 
 9761: sub format_name {
 9762:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9763:     my $name;
 9764:     if ($first ne 'lastname') {
 9765: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9766:     } else {
 9767: 	if ($lastname=~/\S/) {
 9768: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9769: 	    $name=~s/\s+,/,/;
 9770: 	} else {
 9771: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9772: 	}
 9773:     }
 9774:     $name=~s/^\s+//;
 9775:     $name=~s/\s+$//;
 9776:     $name=~s/\s+/ /g;
 9777:     return $name;
 9778: }
 9779: 
 9780: # ------------------------------------------------- Write to course preferences
 9781: 
 9782: sub writecoursepref {
 9783:     my ($courseid,%prefs)=@_;
 9784:     $courseid=~s/^\///;
 9785:     $courseid=~s/\_/\//g;
 9786:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9787:     my $chome=homeserver($cnum,$cdomain);
 9788:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9789: 	return 'error: no such course';
 9790:     }
 9791:     my $cstring='';
 9792:     foreach my $pref (keys(%prefs)) {
 9793: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9794:     }
 9795:     $cstring=~s/\&$//;
 9796:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9797: }
 9798: 
 9799: # ---------------------------------------------------------- Make/modify course
 9800: 
 9801: sub createcourse {
 9802:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9803:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9804:     $url=&declutter($url);
 9805:     my $cid='';
 9806:     if ($context eq 'requestcourses') {
 9807:         my $can_create = 0;
 9808:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9809:         if ($udom eq $ownerdom) {
 9810:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9811:                                   $context)) {
 9812:                 $can_create = 1;
 9813:             }
 9814:         } else {
 9815:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9816:                                            $category);
 9817:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9818:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9819:                 if (@curr > 0) {
 9820:                     my @options = qw(approval validate autolimit);
 9821:                     my $optregex = join('|',@options);
 9822:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9823:                         $can_create = 1;
 9824:                     }
 9825:                 }
 9826:             }
 9827:         }
 9828:         if ($can_create) {
 9829:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9830:                 unless (&allowed('ccc',$udom)) {
 9831:                     return 'refused'; 
 9832:                 }
 9833:             }
 9834:         } else {
 9835:             return 'refused';
 9836:         }
 9837:     } elsif (!&allowed('ccc',$udom)) {
 9838:         return 'refused';
 9839:     }
 9840: # --------------------------------------------------------------- Get Unique ID
 9841:     my $uname;
 9842:     if ($cnum =~ /^$match_courseid$/) {
 9843:         my $chome=&homeserver($cnum,$udom,'true');
 9844:         if (($chome eq '') || ($chome eq 'no_host')) {
 9845:             $uname = $cnum;
 9846:         } else {
 9847:             $uname = &generate_coursenum($udom,$crstype);
 9848:         }
 9849:     } else {
 9850:         $uname = &generate_coursenum($udom,$crstype);
 9851:     }
 9852:     return $uname if ($uname =~ /^error/);
 9853: # -------------------------------------------------- Check supplied server name
 9854:     if (!defined($course_server)) {
 9855:         if (defined(&domain($udom,'primary'))) {
 9856:             $course_server = &domain($udom,'primary');
 9857:         } else {
 9858:             $course_server = $env{'user.home'}; 
 9859:         }
 9860:     }
 9861:     my %host_servers =
 9862:         &Apache::lonnet::get_servers($udom,'library');
 9863:     unless ($host_servers{$course_server}) {
 9864:         return 'error: invalid home server for course: '.$course_server;
 9865:     }
 9866: # ------------------------------------------------------------- Make the course
 9867:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9868:                       $course_server);
 9869:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9870:     my $uhome=&homeserver($uname,$udom,'true');
 9871:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9872: 	return 'error: no such course';
 9873:     }
 9874: # ----------------------------------------------------------------- Course made
 9875: # log existence
 9876:     my $now = time;
 9877:     my $newcourse = {
 9878:                     $udom.'_'.$uname => {
 9879:                                      description => $description,
 9880:                                      inst_code   => $inst_code,
 9881:                                      owner       => $course_owner,
 9882:                                      type        => $crstype,
 9883:                                      creator     => $env{'user.name'}.':'.
 9884:                                                     $env{'user.domain'},
 9885:                                      created     => $now,
 9886:                                      context     => $context,
 9887:                                                 },
 9888:                     };
 9889:     &courseidput($udom,$newcourse,$uhome,'notime');
 9890: # set toplevel url
 9891:     my $topurl=$url;
 9892:     unless ($nonstandard) {
 9893: # ------------------------------------------ For standard courses, make top url
 9894:         my $mapurl=&clutter($url);
 9895:         if ($mapurl eq '/res/') { $mapurl=''; }
 9896:         $env{'form.initmap'}=(<<ENDINITMAP);
 9897: <map>
 9898: <resource id="1" type="start"></resource>
 9899: <resource id="2" src="$mapurl"></resource>
 9900: <resource id="3" type="finish"></resource>
 9901: <link index="1" from="1" to="2"></link>
 9902: <link index="2" from="2" to="3"></link>
 9903: </map>
 9904: ENDINITMAP
 9905:         $topurl=&declutter(
 9906:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9907:                           );
 9908:     }
 9909: # ----------------------------------------------------------- Write preferences
 9910:     &writecoursepref($udom.'_'.$uname,
 9911:                      ('description'              => $description,
 9912:                       'url'                      => $topurl,
 9913:                       'internal.creator'         => $env{'user.name'}.':'.
 9914:                                                     $env{'user.domain'},
 9915:                       'internal.created'         => $now,
 9916:                       'internal.creationcontext' => $context)
 9917:                     );
 9918:     return '/'.$udom.'/'.$uname;
 9919: }
 9920: 
 9921: # ------------------------------------------------------------------- Create ID
 9922: sub generate_coursenum {
 9923:     my ($udom,$crstype) = @_;
 9924:     my $domdesc = &domain($udom);
 9925:     return 'error: invalid domain' if ($domdesc eq '');
 9926:     my $first;
 9927:     if ($crstype eq 'Community') {
 9928:         $first = '0';
 9929:     } else {
 9930:         $first = int(1+rand(9)); 
 9931:     } 
 9932:     my $uname=$first.
 9933:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9934:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9935:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9936: # ----------------------------------------------- Make sure that does not exist
 9937:     my $uhome=&homeserver($uname,$udom,'true');
 9938:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9939:         if ($crstype eq 'Community') {
 9940:             $first = '0';
 9941:         } else {
 9942:             $first = int(1+rand(9));
 9943:         }
 9944:         $uname=$first.
 9945:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9946:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9947:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9948:         $uhome=&homeserver($uname,$udom,'true');
 9949:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9950:             return 'error: unable to generate unique course-ID';
 9951:         }
 9952:     }
 9953:     return $uname;
 9954: }
 9955: 
 9956: sub is_course {
 9957:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9958:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9959: 
 9960:     return unless $cdom and $cnum;
 9961: 
 9962:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9963:         '.');
 9964: 
 9965:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9966:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9967: }
 9968: 
 9969: sub store_userdata {
 9970:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9971:     my $result;
 9972:     if ($datakey ne '') {
 9973:         if (ref($storehash) eq 'HASH') {
 9974:             if ($udom eq '' || $uname eq '') {
 9975:                 $udom = $env{'user.domain'};
 9976:                 $uname = $env{'user.name'};
 9977:             }
 9978:             my $uhome=&homeserver($uname,$udom);
 9979:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9980:                 $result = 'error: no_host';
 9981:             } else {
 9982:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9983:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9984: 
 9985:                 my $namevalue='';
 9986:                 foreach my $key (keys(%{$storehash})) {
 9987:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9988:                 }
 9989:                 $namevalue=~s/\&$//;
 9990:                 unless ($namespace eq 'courserequests') {
 9991:                     $datakey = &escape($datakey);
 9992:                 }
 9993:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9994:                                   $namevalue,$uhome);
 9995:             }
 9996:         } else {
 9997:             $result = 'error: data to store was not a hash reference'; 
 9998:         }
 9999:     } else {
10000:         $result= 'error: invalid requestkey'; 
10001:     }
10002:     return $result;
10003: }
10004: 
10005: # ---------------------------------------------------------- Assign Custom Role
10006: 
10007: sub assigncustomrole {
10008:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10009:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10010:                        $end,$start,$deleteflag,$selfenroll,$context);
10011: }
10012: 
10013: # ----------------------------------------------------------------- Revoke Role
10014: 
10015: sub revokerole {
10016:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10017:     my $now=time;
10018:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10019: }
10020: 
10021: # ---------------------------------------------------------- Revoke Custom Role
10022: 
10023: sub revokecustomrole {
10024:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10025:     my $now=time;
10026:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10027:            $deleteflag,$selfenroll,$context);
10028: }
10029: 
10030: # ------------------------------------------------------------ Disk usage
10031: sub diskusage {
10032:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10033:     $directorypath =~ s/\/$//;
10034:     my $listing=&reply('du2:'.&escape($directorypath).':'
10035:                        .&escape($getpropath).':'.&escape($uname).':'
10036:                        .&escape($udom),homeserver($uname,$udom));
10037:     if ($listing eq 'unknown_cmd') {
10038:         if ($getpropath) {
10039:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10040:         }
10041:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10042:     }
10043:     return $listing;
10044: }
10045: 
10046: sub is_locked {
10047:     my ($file_name, $domain, $user, $which) = @_;
10048:     my @check;
10049:     my $is_locked;
10050:     push (@check,$file_name);
10051:     my %locked = &get('file_permissions',\@check,
10052: 		      $env{'user.domain'},$env{'user.name'});
10053:     my ($tmp)=keys(%locked);
10054:     if ($tmp=~/^error:/) { undef(%locked); }
10055:     
10056:     if (ref($locked{$file_name}) eq 'ARRAY') {
10057:         $is_locked = 'false';
10058:         foreach my $entry (@{$locked{$file_name}}) {
10059:            if (ref($entry) eq 'ARRAY') {
10060:                $is_locked = 'true';
10061:                if (ref($which) eq 'ARRAY') {
10062:                    push(@{$which},$entry);
10063:                } else {
10064:                    last;
10065:                }
10066:            }
10067:        }
10068:     } else {
10069:         $is_locked = 'false';
10070:     }
10071:     return $is_locked;
10072: }
10073: 
10074: sub declutter_portfile {
10075:     my ($file) = @_;
10076:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10077:     return $file;
10078: }
10079: 
10080: # ------------------------------------------------------------- Mark as Read Only
10081: 
10082: sub mark_as_readonly {
10083:     my ($domain,$user,$files,$what) = @_;
10084:     my %current_permissions = &dump('file_permissions',$domain,$user);
10085:     my ($tmp)=keys(%current_permissions);
10086:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10087:     foreach my $file (@{$files}) {
10088: 	$file = &declutter_portfile($file);
10089:         push(@{$current_permissions{$file}},$what);
10090:     }
10091:     &put('file_permissions',\%current_permissions,$domain,$user);
10092:     return;
10093: }
10094: 
10095: # ------------------------------------------------------------Save Selected Files
10096: 
10097: sub save_selected_files {
10098:     my ($user, $path, @files) = @_;
10099:     my $filename = $user."savedfiles";
10100:     my @other_files = &files_not_in_path($user, $path);
10101:     open (OUT, '>'.$tmpdir.$filename);
10102:     foreach my $file (@files) {
10103:         print (OUT $env{'form.currentpath'}.$file."\n");
10104:     }
10105:     foreach my $file (@other_files) {
10106:         print (OUT $file."\n");
10107:     }
10108:     close (OUT);
10109:     return 'ok';
10110: }
10111: 
10112: sub clear_selected_files {
10113:     my ($user) = @_;
10114:     my $filename = $user."savedfiles";
10115:     open (OUT, '>'.LONCAPA::tempdir().$filename);
10116:     print (OUT undef);
10117:     close (OUT);
10118:     return ("ok");    
10119: }
10120: 
10121: sub files_in_path {
10122:     my ($user, $path) = @_;
10123:     my $filename = $user."savedfiles";
10124:     my %return_files;
10125:     open (IN, '<'.LONCAPA::tempdir().$filename);
10126:     while (my $line_in = <IN>) {
10127:         chomp ($line_in);
10128:         my @paths_and_file = split (m!/!, $line_in);
10129:         my $file_part = pop (@paths_and_file);
10130:         my $path_part = join ('/', @paths_and_file);
10131:         $path_part.='/';
10132:         my $path_and_file = $path_part.$file_part;
10133:         if ($path_part eq $path) {
10134:             $return_files{$file_part}= 'selected';
10135:         }
10136:     }
10137:     close (IN);
10138:     return (\%return_files);
10139: }
10140: 
10141: # called in portfolio select mode, to show files selected NOT in current directory
10142: sub files_not_in_path {
10143:     my ($user, $path) = @_;
10144:     my $filename = $user."savedfiles";
10145:     my @return_files;
10146:     my $path_part;
10147:     open(IN, '<'.LONCAPA::.$filename);
10148:     while (my $line = <IN>) {
10149:         #ok, I know it's clunky, but I want it to work
10150:         my @paths_and_file = split(m|/|, $line);
10151:         my $file_part = pop(@paths_and_file);
10152:         chomp($file_part);
10153:         my $path_part = join('/', @paths_and_file);
10154:         $path_part .= '/';
10155:         my $path_and_file = $path_part.$file_part;
10156:         if ($path_part ne $path) {
10157:             push(@return_files, ($path_and_file));
10158:         }
10159:     }
10160:     close(OUT);
10161:     return (@return_files);
10162: }
10163: 
10164: #------------------------------Submitted/Handedback Portfolio Files Versioning
10165:  
10166: sub portfiles_versioning {
10167:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10168:     my $portfolio_root = '/userfiles/portfolio';
10169:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10170:     foreach my $file (@{$portfiles}) {
10171:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10172:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10173:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10174:         my $getpropath = 1;
10175:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10176:                                              $stu_name,$getpropath);
10177:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10178:         my $new_answer = 
10179:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10180:         if ($new_answer ne 'problem getting file') {
10181:             push(@{$versioned_portfiles}, $directory.$new_answer);
10182:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10183:                               [$symb,$env{'request.course.id'},'graded']);
10184:         }
10185:     }
10186: }
10187: 
10188: sub get_next_version {
10189:     my ($answer_name, $answer_ext, $dir_list) = @_;
10190:     my $version;
10191:     if (ref($dir_list) eq 'ARRAY') {
10192:         foreach my $row (@{$dir_list}) {
10193:             my ($file) = split(/\&/,$row,2);
10194:             my ($file_name,$file_version,$file_ext) =
10195:                 &file_name_version_ext($file);
10196:             if (($file_name eq $answer_name) &&
10197:                 ($file_ext eq $answer_ext)) {
10198:                      # gets here if filename and extension match,
10199:                      # regardless of version
10200:                 if ($file_version ne '') {
10201:                     # a versioned file is found  so save it for later
10202:                     if ($file_version > $version) {
10203:                         $version = $file_version;
10204:                     }
10205:                 }
10206:             }
10207:         }
10208:     }
10209:     $version ++;
10210:     return($version);
10211: }
10212: 
10213: sub version_selected_portfile {
10214:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10215:     my ($answer_name,$answer_ver,$answer_ext) =
10216:         &file_name_version_ext($file_name);
10217:     my $new_answer;
10218:     $env{'form.copy'} =
10219:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10220:     if($env{'form.copy'} eq '-1') {
10221:         $new_answer = 'problem getting file';
10222:     } else {
10223:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10224:         my $copy_result = 
10225:             &finishuserfileupload($stu_name,$domain,'copy',
10226:                                   '/portfolio'.$directory.$new_answer);
10227:     }
10228:     undef($env{'form.copy'});
10229:     return ($new_answer);
10230: }
10231: 
10232: sub file_name_version_ext {
10233:     my ($file)=@_;
10234:     my @file_parts = split(/\./, $file);
10235:     my ($name,$version,$ext);
10236:     if (@file_parts > 1) {
10237:         $ext=pop(@file_parts);
10238:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10239:             $version=pop(@file_parts);
10240:         }
10241:         $name=join('.',@file_parts);
10242:     } else {
10243:         $name=join('.',@file_parts);
10244:     }
10245:     return($name,$version,$ext);
10246: }
10247: 
10248: #----------------------------------------------Get portfolio file permissions
10249: 
10250: sub get_portfile_permissions {
10251:     my ($domain,$user) = @_;
10252:     my %current_permissions = &dump('file_permissions',$domain,$user);
10253:     my ($tmp)=keys(%current_permissions);
10254:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10255:     return \%current_permissions;
10256: }
10257: 
10258: #---------------------------------------------Get portfolio file access controls
10259: 
10260: sub get_access_controls {
10261:     my ($current_permissions,$group,$file) = @_;
10262:     my %access;
10263:     my $real_file = $file;
10264:     $file =~ s/\.meta$//;
10265:     if (defined($file)) {
10266:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10267:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10268:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10269:             }
10270:         }
10271:     } else {
10272:         foreach my $key (keys(%{$current_permissions})) {
10273:             if ($key =~ /\0accesscontrol$/) {
10274:                 if (defined($group)) {
10275:                     if ($key !~ m-^\Q$group\E/-) {
10276:                         next;
10277:                     }
10278:                 }
10279:                 my ($fullpath) = split(/\0/,$key);
10280:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10281:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10282:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10283:                     }
10284:                 }
10285:             }
10286:         }
10287:     }
10288:     return %access;
10289: }
10290: 
10291: sub modify_access_controls {
10292:     my ($file_name,$changes,$domain,$user)=@_;
10293:     my ($outcome,$deloutcome);
10294:     my %store_permissions;
10295:     my %new_values;
10296:     my %new_control;
10297:     my %translation;
10298:     my @deletions = ();
10299:     my $now = time;
10300:     if (exists($$changes{'activate'})) {
10301:         if (ref($$changes{'activate'}) eq 'HASH') {
10302:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10303:             my $numnew = scalar(@newitems);
10304:             for (my $i=0; $i<$numnew; $i++) {
10305:                 my $newkey = $newitems[$i];
10306:                 my $newid = &Apache::loncommon::get_cgi_id();
10307:                 if ($newkey =~ /^\d+:/) { 
10308:                     $newkey =~ s/^(\d+)/$newid/;
10309:                     $translation{$1} = $newid;
10310:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10311:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10312:                     $translation{$1} = $newid;
10313:                 }
10314:                 $new_values{$file_name."\0".$newkey} = 
10315:                                           $$changes{'activate'}{$newitems[$i]};
10316:                 $new_control{$newkey} = $now;
10317:             }
10318:         }
10319:     }
10320:     my %todelete;
10321:     my %changed_items;
10322:     foreach my $action ('delete','update') {
10323:         if (exists($$changes{$action})) {
10324:             if (ref($$changes{$action}) eq 'HASH') {
10325:                 foreach my $key (keys(%{$$changes{$action}})) {
10326:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10327:                     if ($action eq 'delete') { 
10328:                         $todelete{$itemnum} = 1;
10329:                     } else {
10330:                         $changed_items{$itemnum} = $key;
10331:                     }
10332:                 }
10333:             }
10334:         }
10335:     }
10336:     # get lock on access controls for file.
10337:     my $lockhash = {
10338:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10339:                                                        ':'.$env{'user.domain'},
10340:                    }; 
10341:     my $tries = 0;
10342:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10343:    
10344:     while (($gotlock ne 'ok') && $tries < 10) {
10345:         $tries ++;
10346:         sleep(0.1);
10347:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10348:     }
10349:     if ($gotlock eq 'ok') {
10350:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10351:         my ($tmp)=keys(%curr_permissions);
10352:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10353:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10354:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10355:             if (ref($curr_controls) eq 'HASH') {
10356:                 foreach my $control_item (keys(%{$curr_controls})) {
10357:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10358:                     if (defined($todelete{$itemnum})) {
10359:                         push(@deletions,$file_name."\0".$control_item);
10360:                     } else {
10361:                         if (defined($changed_items{$itemnum})) {
10362:                             $new_control{$changed_items{$itemnum}} = $now;
10363:                             push(@deletions,$file_name."\0".$control_item);
10364:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10365:                         } else {
10366:                             $new_control{$control_item} = $$curr_controls{$control_item};
10367:                         }
10368:                     }
10369:                 }
10370:             }
10371:         }
10372:         my ($group);
10373:         if (&is_course($domain,$user)) {
10374:             ($group,my $file) = split(/\//,$file_name,2);
10375:         }
10376:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10377:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10378:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10379:         #  remove lock
10380:         my @del_lock = ($file_name."\0".'locked_access_records');
10381:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10382:         my $sqlresult =
10383:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10384:                                     $group);
10385:     } else {
10386:         $outcome = "error: could not obtain lockfile\n";  
10387:     }
10388:     return ($outcome,$deloutcome,\%new_values,\%translation);
10389: }
10390: 
10391: sub make_public_indefinitely {
10392:     my (@requrl) = @_;
10393:     return &automated_portfile_access('public',\@requrl);
10394: }
10395: 
10396: sub automated_portfile_access {
10397:     my ($accesstype,$addsref,$delsref,$info) = @_;
10398:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10399:         return 'invalid';
10400:     }
10401:     my %urls;
10402:     if (ref($addsref) eq 'ARRAY') {
10403:         foreach my $requrl (@{$addsref}) {
10404:             if (&is_portfolio_url($requrl)) {
10405:                 unless (exists($urls{$requrl})) {
10406:                     $urls{$requrl} = 'add';
10407:                 }
10408:             }
10409:         }
10410:     }
10411:     if (ref($delsref) eq 'ARRAY') {
10412:         foreach my $requrl (@{$delsref}) { 
10413:             if (&is_portfolio_url($requrl)) {
10414:                 unless (exists($urls{$requrl})) {
10415:                     $urls{$requrl} = 'delete'; 
10416:                 }
10417:             }
10418:         }
10419:     }
10420:     unless (keys(%urls)) {
10421:         return 'invalid';
10422:     }
10423:     my $ip;
10424:     if ($accesstype eq 'ip') {
10425:         if (ref($info) eq 'HASH') {
10426:             if ($info->{'ip'} ne '') {
10427:                 $ip = $info->{'ip'};
10428:             }
10429:         }
10430:         if ($ip eq '') {
10431:             return 'invalid';
10432:         }
10433:     }
10434:     my $errors;
10435:     my $now = time;
10436:     my %current_perms;
10437:     foreach my $requrl (sort(keys(%urls))) {
10438:         my $action;
10439:         if ($urls{$requrl} eq 'add') {
10440:             $action = 'activate';
10441:         } else {
10442:             $action = 'none';
10443:         }
10444:         my $aclnum = 0;
10445:         my (undef,$udom,$unum,$file_name,$group) =
10446:             &parse_portfolio_url($requrl);
10447:         unless (exists($current_perms{$unum.':'.$udom})) {
10448:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10449:         }
10450:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10451:                                                    $group,$file_name);
10452:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10453:             my ($num,$scope,$end,$start) = 
10454:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10455:             if ($scope eq $accesstype) {
10456:                 if (($start <= $now) && ($end == 0)) {
10457:                     if ($accesstype eq 'ip') {
10458:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10459:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10460:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10461:                                     if ($urls{$requrl} eq 'add') {
10462:                                         $action = 'none';
10463:                                         last;
10464:                                     } else {
10465:                                         $action = 'delete';
10466:                                         $aclnum = $num;
10467:                                         last;
10468:                                     }
10469:                                 }
10470:                             }
10471:                         }
10472:                     } elsif ($accesstype eq 'public') {
10473:                         if ($urls{$requrl} eq 'add') {
10474:                             $action = 'none';
10475:                             last;
10476:                         } else {
10477:                             $action = 'delete';
10478:                             $aclnum = $num;
10479:                             last;
10480:                         }
10481:                     }
10482:                 } elsif ($accesstype eq 'public') {
10483:                     $action = 'update';
10484:                     $aclnum = $num;
10485:                     last;
10486:                 }
10487:             }
10488:         }
10489:         if ($action eq 'none') {
10490:             next;
10491:         } else {
10492:             my %changes;
10493:             my $newend = 0;
10494:             my $newstart = $now;
10495:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10496:             $changes{$action}{$newkey} = {
10497:                 type => $accesstype,
10498:                 time => {
10499:                     start => $newstart,
10500:                     end   => $newend,
10501:                 },
10502:             };
10503:             if ($accesstype eq 'ip') {
10504:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10505:             }
10506:             my ($outcome,$deloutcome,$new_values,$translation) =
10507:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10508:             unless ($outcome eq 'ok') {
10509:                 $errors .= $outcome.' ';
10510:             }
10511:         }
10512:     }
10513:     if ($errors) {
10514:         $errors =~ s/\s$//;
10515:         return $errors;
10516:     } else {
10517:         return 'ok';
10518:     }
10519: }
10520: 
10521: #------------------------------------------------------Get Marked as Read Only
10522: 
10523: sub get_marked_as_readonly {
10524:     my ($domain,$user,$what,$group) = @_;
10525:     my $current_permissions = &get_portfile_permissions($domain,$user);
10526:     my @readonly_files;
10527:     my $cmp1=$what;
10528:     if (ref($what)) { $cmp1=join('',@{$what}) };
10529:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10530:         if (defined($group)) {
10531:             if ($file_name !~ m-^\Q$group\E/-) {
10532:                 next;
10533:             }
10534:         }
10535:         if (ref($value) eq "ARRAY"){
10536:             foreach my $stored_what (@{$value}) {
10537:                 my $cmp2=$stored_what;
10538:                 if (ref($stored_what) eq 'ARRAY') {
10539:                     $cmp2=join('',@{$stored_what});
10540:                 }
10541:                 if ($cmp1 eq $cmp2) {
10542:                     push(@readonly_files, $file_name);
10543:                     last;
10544:                 } elsif (!defined($what)) {
10545:                     push(@readonly_files, $file_name);
10546:                     last;
10547:                 }
10548:             }
10549:         }
10550:     }
10551:     return @readonly_files;
10552: }
10553: #-----------------------------------------------------------Get Marked as Read Only Hash
10554: 
10555: sub get_marked_as_readonly_hash {
10556:     my ($current_permissions,$group,$what) = @_;
10557:     my %readonly_files;
10558:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10559:         if (defined($group)) {
10560:             if ($file_name !~ m-^\Q$group\E/-) {
10561:                 next;
10562:             }
10563:         }
10564:         if (ref($value) eq "ARRAY"){
10565:             foreach my $stored_what (@{$value}) {
10566:                 if (ref($stored_what) eq 'ARRAY') {
10567:                     foreach my $lock_descriptor(@{$stored_what}) {
10568:                         if ($lock_descriptor eq 'graded') {
10569:                             $readonly_files{$file_name} = 'graded';
10570:                         } elsif ($lock_descriptor eq 'handback') {
10571:                             $readonly_files{$file_name} = 'handback';
10572:                         } else {
10573:                             if (!exists($readonly_files{$file_name})) {
10574:                                 $readonly_files{$file_name} = 'locked';
10575:                             }
10576:                         }
10577:                     }
10578:                 } 
10579:             }
10580:         } 
10581:     }
10582:     return %readonly_files;
10583: }
10584: # ------------------------------------------------------------ Unmark as Read Only
10585: 
10586: sub unmark_as_readonly {
10587:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10588:     # for portfolio submissions, $what contains [$symb,$crsid] 
10589:     my ($domain,$user,$what,$file_name,$group) = @_;
10590:     $file_name = &declutter_portfile($file_name);
10591:     my $symb_crs = $what;
10592:     if (ref($what)) { $symb_crs=join('',@$what); }
10593:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10594:     my ($tmp)=keys(%current_permissions);
10595:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10596:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10597:     foreach my $file (@readonly_files) {
10598: 	my $clean_file = &declutter_portfile($file);
10599: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10600: 	my $current_locks = $current_permissions{$file};
10601:         my @new_locks;
10602:         my @del_keys;
10603:         if (ref($current_locks) eq "ARRAY"){
10604:             foreach my $locker (@{$current_locks}) {
10605:                 my $compare=$locker;
10606:                 if (ref($locker) eq 'ARRAY') {
10607:                     $compare=join('',@{$locker});
10608:                     if ($compare ne $symb_crs) {
10609:                         push(@new_locks, $locker);
10610:                     }
10611:                 }
10612:             }
10613:             if (scalar(@new_locks) > 0) {
10614:                 $current_permissions{$file} = \@new_locks;
10615:             } else {
10616:                 push(@del_keys, $file);
10617:                 &del('file_permissions',\@del_keys, $domain, $user);
10618:                 delete($current_permissions{$file});
10619:             }
10620:         }
10621:     }
10622:     &put('file_permissions',\%current_permissions,$domain,$user);
10623:     return;
10624: }
10625: 
10626: # ------------------------------------------------------------ Directory lister
10627: 
10628: sub dirlist {
10629:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10630:     $uri=~s/^\///;
10631:     $uri=~s/\/$//;
10632:     my ($udom, $uname);
10633:     if ($getuserdir) {
10634:         $udom = $userdomain;
10635:         $uname = $username;
10636:     } else {
10637:         (undef,$udom,$uname)=split(/\//,$uri);
10638:         if(defined($userdomain)) {
10639:             $udom = $userdomain;
10640:         }
10641:         if(defined($username)) {
10642:             $uname = $username;
10643:         }
10644:     }
10645:     my ($dirRoot,$listing,@listing_results);
10646: 
10647:     $dirRoot = $perlvar{'lonDocRoot'};
10648:     if (defined($getpropath)) {
10649:         $dirRoot = &propath($udom,$uname);
10650:         $dirRoot =~ s/\/$//;
10651:     } elsif (defined($getuserdir)) {
10652:         my $subdir=$uname.'__';
10653:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10654:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10655:                    ."/$udom/$subdir/$uname";
10656:     } elsif (defined($alternateRoot)) {
10657:         $dirRoot = $alternateRoot;
10658:     }
10659: 
10660:     if($udom) {
10661:         if($uname) {
10662:             my $uhome = &homeserver($uname,$udom);
10663:             if ($uhome eq 'no_host') {
10664:                 return ([],'no_host');
10665:             }
10666:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10667:                               .$getuserdir.':'.&escape($dirRoot)
10668:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10669:             if ($listing eq 'unknown_cmd') {
10670:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10671:             } else {
10672:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10673:             }
10674:             if ($listing eq 'unknown_cmd') {
10675:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10676:                 @listing_results = split(/:/,$listing);
10677:             } else {
10678:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10679:             }
10680:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10681:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10682:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10683:                 return ([],$listing);
10684:             } else {
10685:                 return (\@listing_results);
10686:             }
10687:         } elsif(!$alternateRoot) {
10688:             my (%allusers,%listerror);
10689: 	    my %servers = &get_servers($udom,'library');
10690:  	    foreach my $tryserver (keys(%servers)) {
10691:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10692:                                   &escape($udom),$tryserver);
10693:                 if ($listing eq 'unknown_cmd') {
10694: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10695: 				      $udom, $tryserver);
10696:                 } else {
10697:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10698:                 }
10699: 		if ($listing eq 'unknown_cmd') {
10700: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10701: 				      $udom, $tryserver);
10702: 		    @listing_results = split(/:/,$listing);
10703: 		} else {
10704: 		    @listing_results =
10705: 			map { &unescape($_); } split(/:/,$listing);
10706: 		}
10707:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10708:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10709:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10710:                     $listerror{$tryserver} = $listing;
10711:                 } else {
10712: 		    foreach my $line (@listing_results) {
10713: 			my ($entry) = split(/&/,$line,2);
10714: 			$allusers{$entry} = 1;
10715: 		    }
10716: 		}
10717:             }
10718:             my @alluserslist=();
10719:             foreach my $user (sort(keys(%allusers))) {
10720:                 push(@alluserslist,$user.'&user');
10721:             }
10722: 
10723:             if (!%listerror) {
10724:                 # no errors
10725:                 return (\@alluserslist);
10726:             } elsif (scalar(keys(%servers)) == 1) {
10727:                 # one library server, one error 
10728:                 my ($key) = keys(%listerror);
10729:                 return (\@alluserslist, $listerror{$key});
10730:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10731:                 # con_lost indicates that we might miss data from at least one
10732:                 # library server
10733:                 return (\@alluserslist, 'con_lost');
10734:             } else {
10735:                 # multiple library servers and no con_lost -> data should be
10736:                 # complete. 
10737:                 return (\@alluserslist);
10738:             }
10739: 
10740:         } else {
10741:             return ([],'missing username');
10742:         }
10743:     } elsif(!defined($getpropath)) {
10744:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10745:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10746:         return (\@all_domains);
10747:     } else {
10748:         return ([],'missing domain');
10749:     }
10750: }
10751: 
10752: # --------------------------------------------- GetFileTimestamp
10753: # This function utilizes dirlist and returns the date stamp for
10754: # when it was last modified.  It will also return an error of -1
10755: # if an error occurs
10756: 
10757: sub GetFileTimestamp {
10758:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10759:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10760:     $studentName   = &LONCAPA::clean_username($studentName);
10761:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10762:                                     undef,$getuserdir);
10763:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10764:         return -1;
10765:     }
10766:     if (ref($fileref) eq 'ARRAY') {
10767:         my @stats = split('&',$fileref->[0]);
10768:         # @stats contains first the filename, then the stat output
10769:         return $stats[10]; # so this is 10 instead of 9.
10770:     } else {
10771:         return -1;
10772:     }
10773: }
10774: 
10775: sub stat_file {
10776:     my ($uri) = @_;
10777:     $uri = &clutter_with_no_wrapper($uri);
10778: 
10779:     my ($udom,$uname,$file);
10780:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10781: 	($udom,$uname,$file) =
10782: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10783: 	$file = 'userfiles/'.$file;
10784:     }
10785:     if ($uri =~ m-^/res/-) {
10786: 	($udom,$uname) = 
10787: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10788: 	$file = $uri;
10789:     }
10790: 
10791:     if (!$udom || !$uname || !$file) {
10792: 	# unable to handle the uri
10793: 	return ();
10794:     }
10795:     my $getpropath;
10796:     if ($file =~ /^userfiles\//) {
10797:         $getpropath = 1;
10798:     }
10799:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10800:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10801:         return ();
10802:     } else {
10803:         if (ref($listref) eq 'ARRAY') {
10804:             my @stats = split('&',$listref->[0]);
10805: 	    shift(@stats); #filename is first
10806: 	    return @stats;
10807:         }
10808:     }
10809:     return ();
10810: }
10811: 
10812: # --------------------------------------------------------- recursedirs
10813: # Recursive function to traverse either a specific user's Authoring Space
10814: # or corresponding Published Resource Space, and populate the hash ref:
10815: # $dirhashref with URLs of all directories, and if $filehashref hash
10816: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10817: # or .rights files in resource space, and .meta, .save, .log, and .bak
10818: # files in Authoring Space.
10819: #
10820: # Inputs:
10821: #
10822: # $is_home - true if current server is home server for user's space
10823: # $context - either: priv, or res respectively for Authoring or Resource Space.
10824: # $docroot - Document root (i.e., /home/httpd/html
10825: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10826: # $relpath - Current path (relative to top level).
10827: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10828: # $filehashref - reference to hash to populate with URLs of files (Optional)
10829: #
10830: # Returns: nothing
10831: #
10832: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10833: #
10834: # Currently used by interface/londocs.pm to create linked select boxes for
10835: # directory and filename to import a Course "Author" resource into a course, and
10836: # also to create linked select boxes for Authoring Space and Directory to choose
10837: # save location for creation of a new "standard" problem from the Course Editor.
10838: #
10839: 
10840: sub recursedirs {
10841:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10842:     return unless (ref($dirhashref) eq 'HASH');
10843:     my $currpath = $docroot.$toppath;
10844:     if ($relpath) {
10845:         $currpath .= "/$relpath";
10846:     }
10847:     my $savefile;
10848:     if (ref($filehashref)) {
10849:         $savefile = 1;
10850:     }
10851:     if ($is_home) {
10852:         if (opendir(my $dirh,$currpath)) {
10853:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10854:                 next if ($item eq '');
10855:                 if (-d "$currpath/$item") {
10856:                     my $newpath;
10857:                     if ($relpath) {
10858:                         $newpath = "$relpath/$item";
10859:                     } else {
10860:                         $newpath = $item;
10861:                     }
10862:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10863:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10864:                 } elsif ($savefile) {
10865:                     if ($context eq 'priv') {
10866:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10867:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10868:                         }
10869:                     } else {
10870:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10871:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10872:                         }
10873:                     }
10874:                 }
10875:             }
10876:             closedir($dirh);
10877:         }
10878:     } else {
10879:         my ($dirlistref,$listerror) =
10880:             &dirlist($toppath.$relpath);
10881:         my @dir_lines;
10882:         my $dirptr=16384;
10883:         if (ref($dirlistref) eq 'ARRAY') {
10884:             foreach my $dir_line (sort
10885:                               {
10886:                                   my ($afile)=split('&',$a,2);
10887:                                   my ($bfile)=split('&',$b,2);
10888:                                   return (lc($afile) cmp lc($bfile));
10889:                               } (@{$dirlistref})) {
10890:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10891:                     split(/\&/,$dir_line,16);
10892:                 $item =~ s/\s+$//;
10893:                 next if (($item =~ /^\.\.?$/) || ($obs));
10894:                 if ($dirptr&$testdir) {
10895:                     my $newpath;
10896:                     if ($relpath) {
10897:                         $newpath = "$relpath/$item";
10898:                     } else {
10899:                         $relpath = '/';
10900:                         $newpath = $item;
10901:                     }
10902:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10903:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10904:                 } elsif ($savefile) {
10905:                     if ($context eq 'priv') {
10906:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10907:                             $filehashref->{$relpath}{$item} = 1;
10908:                         }
10909:                     } else {
10910:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10911:                             $filehashref->{$relpath}{$item} = 1;
10912:                         }
10913:                     }
10914:                 }
10915:             }
10916:         }
10917:     }
10918:     return;
10919: }
10920: 
10921: # -------------------------------------------------------- Value of a Condition
10922: 
10923: # gets the value of a specific preevaluated condition
10924: #    stored in the string  $env{user.state.<cid>}
10925: # or looks up a condition reference in the bighash and if if hasn't
10926: # already been evaluated recurses into docondval to get the value of
10927: # the condition, then memoizing it to 
10928: #   $env{user.state.<cid>.<condition>}
10929: sub directcondval {
10930:     my $number=shift;
10931:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10932: 	&Apache::lonuserstate::evalstate();
10933:     }
10934:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10935: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10936:     } elsif ($number =~ /^_/) {
10937: 	my $sub_condition;
10938: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10939: 		&GDBM_READER(),0640)) {
10940: 	    $sub_condition=$bighash{'conditions'.$number};
10941: 	    untie(%bighash);
10942: 	}
10943: 	my $value = &docondval($sub_condition);
10944: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10945: 	return $value;
10946:     }
10947:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10948:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10949:     } else {
10950:        return 2;
10951:     }
10952: }
10953: 
10954: # get the collection of conditions for this resource
10955: sub condval {
10956:     my $condidx=shift;
10957:     my $allpathcond='';
10958:     foreach my $cond (split(/\|/,$condidx)) {
10959: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10960: 	    $allpathcond.=
10961: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10962: 	}
10963:     }
10964:     $allpathcond=~s/\|$//;
10965:     return &docondval($allpathcond);
10966: }
10967: 
10968: #evaluates an expression of conditions
10969: sub docondval {
10970:     my ($allpathcond) = @_;
10971:     my $result=0;
10972:     if ($env{'request.course.id'}
10973: 	&& defined($allpathcond)) {
10974: 	my $operand='|';
10975: 	my @stack;
10976: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10977: 	    if ($chunk eq '(') {
10978: 		push @stack,($operand,$result);
10979: 	    } elsif ($chunk eq ')') {
10980: 		my $before=pop @stack;
10981: 		if (pop @stack eq '&') {
10982: 		    $result=$result>$before?$before:$result;
10983: 		} else {
10984: 		    $result=$result>$before?$result:$before;
10985: 		}
10986: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
10987: 		$operand=$chunk;
10988: 	    } else {
10989: 		my $new=directcondval($chunk);
10990: 		if ($operand eq '&') {
10991: 		    $result=$result>$new?$new:$result;
10992: 		} else {
10993: 		    $result=$result>$new?$result:$new;
10994: 		}
10995: 	    }
10996: 	}
10997:     }
10998:     return $result;
10999: }
11000: 
11001: # ---------------------------------------------------- Devalidate courseresdata
11002: 
11003: sub devalidatecourseresdata {
11004:     my ($coursenum,$coursedomain)=@_;
11005:     my $hashid=$coursenum.':'.$coursedomain;
11006:     &devalidate_cache_new('courseres',$hashid);
11007: }
11008: 
11009: 
11010: # --------------------------------------------------- Course Resourcedata Query
11011: #
11012: #  Parameters:
11013: #      $coursenum    - Number of the course.
11014: #      $coursedomain - Domain at which the course was created.
11015: #  Returns:
11016: #     A hash of the course parameters along (I think) with timestamps
11017: #     and version info.
11018: 
11019: sub get_courseresdata {
11020:     my ($coursenum,$coursedomain)=@_;
11021:     my $coursehom=&homeserver($coursenum,$coursedomain);
11022:     my $hashid=$coursenum.':'.$coursedomain;
11023:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11024:     my %dumpreply;
11025:     unless (defined($cached)) {
11026: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11027: 	$result=\%dumpreply;
11028: 	my ($tmp) = keys(%dumpreply);
11029: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11030: 	    &do_cache_new('courseres',$hashid,$result,600);
11031: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11032: 	    return $tmp;
11033: 	} elsif ($tmp =~ /^(error)/) {
11034: 	    $result=undef;
11035: 	    &do_cache_new('courseres',$hashid,$result,600);
11036: 	}
11037:     }
11038:     return $result;
11039: }
11040: 
11041: sub devalidateuserresdata {
11042:     my ($uname,$udom)=@_;
11043:     my $hashid="$udom:$uname";
11044:     &devalidate_cache_new('userres',$hashid);
11045: }
11046: 
11047: sub get_userresdata {
11048:     my ($uname,$udom)=@_;
11049:     #most student don\'t have any data set, check if there is some data
11050:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11051: 
11052:     my $hashid="$udom:$uname";
11053:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11054:     if (!defined($cached)) {
11055: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11056: 	$result=\%resourcedata;
11057: 	&do_cache_new('userres',$hashid,$result,600);
11058:     }
11059:     my ($tmp)=keys(%$result);
11060:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11061: 	return $result;
11062:     }
11063:     #error 2 occurs when the .db doesn't exist
11064:     if ($tmp!~/error: 2 /) {
11065:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11066: 	    &logthis("<font color=\"blue\">WARNING:".
11067: 		     " Trying to get resource data for ".
11068: 		     $uname." at ".$udom.": ".
11069: 		     $tmp."</font>");
11070:         }
11071:     } elsif ($tmp=~/error: 2 /) {
11072: 	#&EXT_cache_set($udom,$uname);
11073: 	&do_cache_new('userres',$hashid,undef,600);
11074: 	undef($tmp); # not really an error so don't send it back
11075:     }
11076:     return $tmp;
11077: }
11078: #----------------------------------------------- resdata - return resource data
11079: #  Purpose:
11080: #    Return resource data for either users or for a course.
11081: #  Parameters:
11082: #     $name      - Course/user name.
11083: #     $domain    - Name of the domain the user/course is registered on.
11084: #     $type      - Type of thing $name is (must be 'course' or 'user')
11085: #     $mapp      - decluttered URL of enclosing map  
11086: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11087: #     $recurseup - Ref to array of map URLs, starting with map containing
11088: #                  $mapp up through hierarchy of nested maps to top level map.  
11089: #     $courseid  - CourseID (first part of param identifier).
11090: #     $modifier  - Middle part of param identifier.
11091: #     $what      - Last part of param identifier.
11092: #     @which     - Array of names of resources desired.
11093: #  Returns:
11094: #     The value of the first reasource in @which that is found in the
11095: #     resource hash.
11096: #  Exceptional Conditions:
11097: #     If the $type passed in is not valid (not the string 'course' or 
11098: #     'user', an undefined  reference is returned.
11099: #     If none of the resources are found, an undef is returned
11100: sub resdata {
11101:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11102:         $modifier,$what,@which)=@_;
11103:     my $result;
11104:     if ($type eq 'course') {
11105: 	$result=&get_courseresdata($name,$domain);
11106:     } elsif ($type eq 'user') {
11107: 	$result=&get_userresdata($name,$domain);
11108:     }
11109:     if (!ref($result)) { return $result; }    
11110:     foreach my $item (@which) {
11111:         if ($item->[1] eq 'course') {
11112:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11113:                 unless ($$recursed) {
11114:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11115:                     $$recursed = 1;
11116:                 }
11117:                 foreach my $item (@${recurseup}) {
11118:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11119:                     last if (defined($result->{$norecursechk}));
11120:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11121:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11122:                 }
11123:             }
11124:         }
11125:         if (defined($result->{$item->[0]})) {
11126: 	    return [$result->{$item->[0]},$item->[1]];
11127: 	}
11128:     }
11129:     return undef;
11130: }
11131: 
11132: sub get_domain_ltitools {
11133:     my ($cdom) = @_;
11134:     my %ltitools;
11135:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11136:     if (defined($cached)) {
11137:         if (ref($result) eq 'HASH') {
11138:             %ltitools = %{$result};
11139:         }
11140:     } else {
11141:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11142:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
11143:             %ltitools = %{$domconfig{'ltitools'}};
11144:             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11145:             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11146:                 foreach my $id (keys(%ltitools)) {
11147:                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11148:                         foreach my $item ('key','secret') {
11149:                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11150:                         }
11151:                     }
11152:                 }
11153:             }
11154:         }
11155:         my $cachetime = 24*60*60;
11156:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11157:     }
11158:     return %ltitools;
11159: }
11160: 
11161: sub get_numsuppfiles {
11162:     my ($cnum,$cdom,$ignorecache)=@_;
11163:     my $hashid=$cnum.':'.$cdom;
11164:     my ($suppcount,$cached);
11165:     unless ($ignorecache) {
11166:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11167:     }
11168:     unless (defined($cached)) {
11169:         my $chome=&homeserver($cnum,$cdom);
11170:         unless ($chome eq 'no_host') {
11171:             ($suppcount,my $errors) = (0,0);
11172:             my $suppmap = 'supplemental.sequence';
11173:             ($suppcount,$errors) = 
11174:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11175:         }
11176:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11177:     }
11178:     return $suppcount;
11179: }
11180: 
11181: #
11182: # EXT resource caching routines
11183: #
11184: 
11185: {
11186: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11187: #
11188: # The course for which we cache
11189: my $cachedmapkey='';
11190: # The cached recursive maps for this course
11191: my %cachedmaps=();
11192: # When this was last done
11193: my $cachedmaptime='';
11194: 
11195: sub clear_EXT_cache_status {
11196:     &delenv('cache.EXT.');
11197: }
11198: 
11199: sub EXT_cache_status {
11200:     my ($target_domain,$target_user) = @_;
11201:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11202:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11203:         # We know already the user has no data
11204:         return 1;
11205:     } else {
11206:         return 0;
11207:     }
11208: }
11209: 
11210: sub EXT_cache_set {
11211:     my ($target_domain,$target_user) = @_;
11212:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11213:     #&appenv({$cachename => time});
11214: }
11215: 
11216: # --------------------------------------------------------- Value of a Variable
11217: sub EXT {
11218: 
11219:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11220:     unless ($varname) { return ''; }
11221:     #get real user name/domain, courseid and symb
11222:     my $courseid;
11223:     my $publicuser;
11224:     if ($symbparm) {
11225: 	$symbparm=&get_symb_from_alias($symbparm);
11226:     }
11227:     if (!($uname && $udom)) {
11228:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11229:       if (!$symbparm) {	$symbparm=$cursymb; }
11230:     } else {
11231: 	$courseid=$env{'request.course.id'};
11232:     }
11233:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11234:     my $rest;
11235:     if (defined($therest[0])) {
11236:        $rest=join('.',@therest);
11237:     } else {
11238:        $rest='';
11239:     }
11240: 
11241:     my $qualifierrest=$qualifier;
11242:     if ($rest) { $qualifierrest.='.'.$rest; }
11243:     my $spacequalifierrest=$space;
11244:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11245:     if ($realm eq 'user') {
11246: # --------------------------------------------------------------- user.resource
11247: 	if ($space eq 'resource') {
11248: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11249: 		  || defined($Apache::lonhomework::parsing_a_task))
11250: 		 &&
11251: 		 ($symbparm eq &symbread()) ) {	
11252: 		# if we are in the middle of processing the resource the
11253: 		# get the value we are planning on committing
11254:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11255:                     return $Apache::lonhomework::results{$qualifierrest};
11256:                 } else {
11257:                     return $Apache::lonhomework::history{$qualifierrest};
11258:                 }
11259: 	    } else {
11260: 		my %restored;
11261: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11262: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11263: 		} else {
11264: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11265: 		}
11266: 		return $restored{$qualifierrest};
11267: 	    }
11268: # ----------------------------------------------------------------- user.access
11269:         } elsif ($space eq 'access') {
11270: 	    # FIXME - not supporting calls for a specific user
11271:             return &allowed($qualifier,$rest);
11272: # ------------------------------------------ user.preferences, user.environment
11273:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11274: 	    if (($uname eq $env{'user.name'}) &&
11275: 		($udom eq $env{'user.domain'})) {
11276: 		return $env{join('.',('environment',$qualifierrest))};
11277: 	    } else {
11278: 		my %returnhash;
11279: 		if (!$publicuser) {
11280: 		    %returnhash=&userenvironment($udom,$uname,
11281: 						 $qualifierrest);
11282: 		}
11283: 		return $returnhash{$qualifierrest};
11284: 	    }
11285: # ----------------------------------------------------------------- user.course
11286:         } elsif ($space eq 'course') {
11287: 	    # FIXME - not supporting calls for a specific user
11288:             return $env{join('.',('request.course',$qualifier))};
11289: # ------------------------------------------------------------------- user.role
11290:         } elsif ($space eq 'role') {
11291: 	    # FIXME - not supporting calls for a specific user
11292:             my ($role,$where)=split(/\./,$env{'request.role'});
11293:             if ($qualifier eq 'value') {
11294: 		return $role;
11295:             } elsif ($qualifier eq 'extent') {
11296:                 return $where;
11297:             }
11298: # ----------------------------------------------------------------- user.domain
11299:         } elsif ($space eq 'domain') {
11300:             return $udom;
11301: # ------------------------------------------------------------------- user.name
11302:         } elsif ($space eq 'name') {
11303:             return $uname;
11304: # ---------------------------------------------------- Any other user namespace
11305:         } else {
11306: 	    my %reply;
11307: 	    if (!$publicuser) {
11308: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11309: 	    }
11310: 	    return $reply{$qualifierrest};
11311:         }
11312:     } elsif ($realm eq 'query') {
11313: # ---------------------------------------------- pull stuff out of query string
11314:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11315: 						[$spacequalifierrest]);
11316: 	return $env{'form.'.$spacequalifierrest}; 
11317:    } elsif ($realm eq 'request') {
11318: # ------------------------------------------------------------- request.browser
11319:         if ($space eq 'browser') {
11320:             return $env{'browser.'.$qualifier};
11321: # ------------------------------------------------------------ request.filename
11322:         } else {
11323:             return $env{'request.'.$spacequalifierrest};
11324:         }
11325:     } elsif ($realm eq 'course') {
11326: # ---------------------------------------------------------- course.description
11327:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11328:     } elsif ($realm eq 'resource') {
11329: 
11330: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11331: 	    if (!$symbparm) { $symbparm=&symbread(); }
11332: 	}
11333: 
11334:         if ($qualifier eq '') {
11335: 	    if ($space eq 'title') {
11336: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11337: 	        return &gettitle($symbparm);
11338: 	    }
11339: 	
11340: 	    if ($space eq 'map') {
11341: 	        my ($map) = &decode_symb($symbparm);
11342: 	        return &symbread($map);
11343: 	    }
11344:             if ($space eq 'maptitle') {
11345:                 my ($map) = &decode_symb($symbparm);
11346:                 return &gettitle($map);
11347:             }
11348: 	    if ($space eq 'filename') {
11349: 	        if ($symbparm) {
11350: 		    return &clutter((&decode_symb($symbparm))[2]);
11351: 	        }
11352: 	        return &hreflocation('',$env{'request.filename'});
11353: 	    }
11354: 
11355:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11356:                 if ($space eq 'visibleparts') {
11357:                     my $navmap = Apache::lonnavmaps::navmap->new();
11358:                     my $item;
11359:                     if (ref($navmap)) {
11360:                         my $res = $navmap->getBySymb($symbparm);
11361:                         my $parts = $res->parts();
11362:                         if (ref($parts) eq 'ARRAY') {
11363:                             $item = join(',',@{$parts});
11364:                         }
11365:                         undef($navmap);
11366:                     }
11367:                     return $item;
11368:                 }
11369:             }
11370:         }
11371: 
11372: 	my ($section, $group, @groups, @recurseup, $recursed);
11373: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11374:         if (($courseid eq '') && ($cid)) {
11375:             $courseid = $cid;
11376:         }
11377: 	if (($symbparm && $courseid) && 
11378: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11379: 
11380: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11381: 
11382: # ----------------------------------------------------- Cascading lookup scheme
11383: 	    my $symbp=$symbparm;
11384: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11385: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11386:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11387: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11388: 	    if (($env{'user.name'} eq $uname) &&
11389: 		($env{'user.domain'} eq $udom)) {
11390: 		$section=$env{'request.course.sec'};
11391:                 @groups = split(/:/,$env{'request.course.groups'});  
11392:                 @groups=&sort_course_groups($courseid,@groups); 
11393: 	    } else {
11394: 		if (! defined($usection)) {
11395: 		    $section=&getsection($udom,$uname,$courseid);
11396: 		} else {
11397: 		    $section = $usection;
11398: 		}
11399:                 @groups = &get_users_groups($udom,$uname,$courseid);
11400: 	    }
11401: 
11402: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11403: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11404:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11405: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11406: 
11407: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11408: 	    my $courselevelr=$courseid.'.'.$symbparm;
11409:             $courseleveli=$courseid.'.'.$recurseparm;
11410: 	    $courselevelm=$courseid.'.'.$mapparm;
11411: 
11412: # ----------------------------------------------------------- first, check user
11413: 
11414: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11415:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11416: 				       ([$courselevelr,'resource'],
11417: 					[$courselevelm,'map'     ],
11418:                                         [$courseleveli,'map'     ],
11419: 					[$courselevel, 'course'  ]));
11420: 	    if (defined($userreply)) { return &get_reply($userreply); }
11421: 
11422: # ------------------------------------------------ second, check some of course
11423:             my $coursereply;
11424:             if (@groups > 0) {
11425:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11426:                                        $recurseparm,$mapparm,$spacequalifierrest,
11427:                                        $mapp,\$recursed,\@recurseup);
11428:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11429:             }
11430: 
11431: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11432: 				  $env{'course.'.$courseid.'.domain'},
11433: 				  'course',$mapp,\$recursed,\@recurseup,
11434:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11435: 				  ([$seclevelr,   'resource'],
11436: 				   [$seclevelm,   'map'     ],
11437:                                    [$secleveli,   'map'     ],
11438: 				   [$seclevel,    'course'  ],
11439: 				   [$courselevelr,'resource']));
11440: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11441: 
11442: # ------------------------------------------------------ third, check map parms
11443: 	    my %parmhash=();
11444: 	    my $thisparm='';
11445: 	    if (tie(%parmhash,'GDBM_File',
11446: 		    $env{'request.course.fn'}.'_parms.db',
11447: 		    &GDBM_READER(),0640)) {
11448: 		$thisparm=$parmhash{$symbparm};
11449: 		untie(%parmhash);
11450: 	    }
11451: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11452: 	}
11453: # ------------------------------------------ fourth, look in resource metadata
11454:  
11455:         my $what = $spacequalifierrest;
11456: 	$what=~s/\./\_/;
11457: 	my $filename;
11458: 	if (!$symbparm) { $symbparm=&symbread(); }
11459: 	if ($symbparm) {
11460: 	    $filename=(&decode_symb($symbparm))[2];
11461: 	} else {
11462: 	    $filename=$env{'request.filename'};
11463: 	}
11464: 	my $metadata=&metadata($filename,$what);
11465: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11466: 	$metadata=&metadata($filename,'parameter_'.$what);
11467: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11468: 
11469: # ----------------------------------------------- fifth, look in rest of course
11470: 	if ($symbparm && defined($courseid) && 
11471: 	    $courseid eq $env{'request.course.id'}) {
11472: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11473: 				     $env{'course.'.$courseid.'.domain'},
11474: 				     'course',$mapp,\$recursed,\@recurseup,
11475:                                      $courseid,'.',$spacequalifierrest,
11476: 				     ([$courselevelm,'map'   ],
11477:                                       [$courseleveli,'map'   ],
11478: 				      [$courselevel, 'course']));
11479: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11480: 	}
11481: # ------------------------------------------------------------------ Cascade up
11482: 	unless ($space eq '0') {
11483: 	    my @parts=split(/_/,$space);
11484: 	    my $id=pop(@parts);
11485: 	    my $part=join('_',@parts);
11486: 	    if ($part eq '') { $part='0'; }
11487: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11488: 				 $symbparm,$udom,$uname,$section,1);
11489: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11490: 	}
11491: 	if ($recurse) { return undef; }
11492: 	my $pack_def=&packages_tab_default($filename,$varname);
11493: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11494: # ---------------------------------------------------- Any other user namespace
11495:     } elsif ($realm eq 'environment') {
11496: # ----------------------------------------------------------------- environment
11497: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11498: 	    return $env{'environment.'.$spacequalifierrest};
11499: 	} else {
11500: 	    if ($uname eq 'anonymous' && $udom eq '') {
11501: 		return '';
11502: 	    }
11503: 	    my %returnhash=&userenvironment($udom,$uname,
11504: 					    $spacequalifierrest);
11505: 	    return $returnhash{$spacequalifierrest};
11506: 	}
11507:     } elsif ($realm eq 'system') {
11508: # ----------------------------------------------------------------- system.time
11509: 	if ($space eq 'time') {
11510: 	    return time;
11511:         }
11512:     } elsif ($realm eq 'server') {
11513: # ----------------------------------------------------------------- system.time
11514: 	if ($space eq 'name') {
11515: 	    return $ENV{'SERVER_NAME'};
11516:         }
11517:     }
11518:     return '';
11519: }
11520: 
11521: sub get_reply {
11522:     my ($reply_value) = @_;
11523:     if (ref($reply_value) eq 'ARRAY') {
11524:         if (wantarray) {
11525: 	    return @$reply_value;
11526:         }
11527:         return $reply_value->[0];
11528:     } else {
11529:         return $reply_value;
11530:     }
11531: }
11532: 
11533: sub check_group_parms {
11534:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11535:         $recursed,$recurseupref) = @_;
11536:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11537:                   [$what,'course']);
11538:     my $coursereply;
11539:     foreach my $group (@{$groups}) {
11540:         my @groupitems = ();
11541:         foreach my $level (@levels) {
11542:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11543:              push(@groupitems,[$item,$level->[1]]);
11544:         }
11545:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11546:                                    $env{'course.'.$courseid.'.domain'},
11547:                                    'course',$mapp,$recursed,$recurseupref,
11548:                                    $courseid,'.['.$group.'].',$what,
11549:                                    @groupitems);
11550:         last if (defined($coursereply));
11551:     }
11552:     return $coursereply;
11553: }
11554: 
11555: sub get_map_hierarchy {
11556:     my ($mapname,$courseid) = @_;
11557:     my @recurseup = ();
11558:     if ($mapname) {
11559:         if (($cachedmapkey eq $courseid) &&
11560:             (abs($cachedmaptime-time)<5)) {
11561:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11562:                 return @{$cachedmaps{$mapname}};
11563:             }
11564:         }
11565:         my $navmap = Apache::lonnavmaps::navmap->new();
11566:         if (ref($navmap)) {
11567:             @recurseup = $navmap->recurseup_maps($mapname);
11568:             undef($navmap);
11569:             $cachedmaps{$mapname} = \@recurseup;
11570:             $cachedmaptime=time;
11571:             $cachedmapkey=$courseid;
11572:         }
11573:     }
11574:     return @recurseup;
11575: }
11576: 
11577: }
11578: 
11579: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11580:     my ($courseid,@groups) = @_;
11581:     @groups = sort(@groups);
11582:     return @groups;
11583: }
11584: 
11585: sub packages_tab_default {
11586:     my ($uri,$varname)=@_;
11587:     my (undef,$part,$name)=split(/\./,$varname);
11588: 
11589:     my (@extension,@specifics,$do_default);
11590:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11591: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11592: 	if ($pack_type eq 'default') {
11593: 	    $do_default=1;
11594: 	} elsif ($pack_type eq 'extension') {
11595: 	    push(@extension,[$package,$pack_type,$pack_part]);
11596: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11597: 	    # only look at packages defaults for packages that this id is
11598: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11599: 	}
11600:     }
11601:     # first look for a package that matches the requested part id
11602:     foreach my $package (@specifics) {
11603: 	my (undef,$pack_type,$pack_part)=@{$package};
11604: 	next if ($pack_part ne $part);
11605: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11606: 	    return $packagetab{"$pack_type&$name&default"};
11607: 	}
11608:     }
11609:     # look for any possible matching non extension_ package
11610:     foreach my $package (@specifics) {
11611: 	my (undef,$pack_type,$pack_part)=@{$package};
11612: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11613: 	    return $packagetab{"$pack_type&$name&default"};
11614: 	}
11615: 	if ($pack_type eq 'part') { $pack_part='0'; }
11616: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11617: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11618: 	}
11619:     }
11620:     # look for any posible extension_ match
11621:     foreach my $package (@extension) {
11622: 	my ($package,$pack_type)=@{$package};
11623: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11624: 	    return $packagetab{"$pack_type&$name&default"};
11625: 	}
11626: 	if (defined($packagetab{$package."&$name&default"})) {
11627: 	    return $packagetab{$package."&$name&default"};
11628: 	}
11629:     }
11630:     # look for a global default setting
11631:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11632: 	return $packagetab{"default&$name&default"};
11633:     }
11634:     return undef;
11635: }
11636: 
11637: sub add_prefix_and_part {
11638:     my ($prefix,$part)=@_;
11639:     my $keyroot;
11640:     if (defined($prefix) && $prefix !~ /^__/) {
11641: 	# prefix that has a part already
11642: 	$keyroot=$prefix;
11643:     } elsif (defined($prefix)) {
11644: 	# prefix that is missing a part
11645: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11646:     } else {
11647: 	# no prefix at all
11648: 	if (defined($part)) { $keyroot='_'.$part; }
11649:     }
11650:     return $keyroot;
11651: }
11652: 
11653: # ---------------------------------------------------------------- Get metadata
11654: 
11655: my %metaentry;
11656: my %importedpartids;
11657: sub metadata {
11658:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11659:     $uri=&declutter($uri);
11660:     # if it is a non metadata possible uri return quickly
11661:     if (($uri eq '') || 
11662: 	(($uri =~ m|^/*adm/|) && 
11663: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11664:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11665: 	return undef;
11666:     }
11667:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11668: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11669: 	return undef;
11670:     }
11671:     my $filename=$uri;
11672:     $uri=~s/\.meta$//;
11673: #
11674: # Is the metadata already cached?
11675: # Look at timestamp of caching
11676: # Everything is cached by the main uri, libraries are never directly cached
11677: #
11678:     if (!defined($liburi)) {
11679: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11680: 	if (defined($cached)) { return $result->{':'.$what}; }
11681:     }
11682:     {
11683: # Imported parts would go here
11684:         my %importedids=();
11685:         my @origfileimportpartids=();
11686:         my $importedparts=0;
11687: #
11688: # Is this a recursive call for a library?
11689: #
11690: #	if (! exists($metacache{$uri})) {
11691: #	    $metacache{$uri}={};
11692: #	}
11693: 	my $cachetime = 60*60;
11694:         if ($liburi) {
11695: 	    $liburi=&declutter($liburi);
11696:             $filename=$liburi;
11697:         } else {
11698: 	    &devalidate_cache_new('meta',$uri);
11699: 	    undef(%metaentry);
11700: 	}
11701:         my %metathesekeys=();
11702:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11703: 	my $metastring;
11704: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11705: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11706: 	    $metastring = 
11707: 		&Apache::lonnet::ssi_body($which,
11708: 					  ('grade_target' => 'meta'));
11709: 	    $cachetime = 1; # only want this cached in the child not long term
11710: 	} elsif (($uri !~ m -^(editupload)/-) && 
11711:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11712: 	    my $file=&filelocation('',&clutter($filename));
11713: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11714: 	    $metastring=&getfile($file);
11715: 	}
11716:         my $parser=HTML::LCParser->new(\$metastring);
11717:         my $token;
11718:         undef %metathesekeys;
11719:         while ($token=$parser->get_token) {
11720: 	    if ($token->[0] eq 'S') {
11721: 		if (defined($token->[2]->{'package'})) {
11722: #
11723: # This is a package - get package info
11724: #
11725: 		    my $package=$token->[2]->{'package'};
11726: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11727: 		    if (defined($token->[2]->{'id'})) { 
11728: 			$keyroot.='_'.$token->[2]->{'id'}; 
11729: 		    }
11730: 		    if ($metaentry{':packages'}) {
11731: 			$metaentry{':packages'}.=','.$package.$keyroot;
11732: 		    } else {
11733: 			$metaentry{':packages'}=$package.$keyroot;
11734: 		    }
11735: 		    foreach my $pack_entry (keys(%packagetab)) {
11736: 			my $part=$keyroot;
11737: 			$part=~s/^\_//;
11738: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11739: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11740: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11741: 			    # ignore package.tab specified default values
11742:                             # here &package_tab_default() will fetch those
11743: 			    if ($subp eq 'default') { next; }
11744: 			    my $value=$packagetab{$pack_entry};
11745: 			    my $unikey;
11746: 			    if ($pack =~ /_0$/) {
11747: 				$unikey='parameter_0_'.$name;
11748: 				$part=0;
11749: 			    } else {
11750: 				$unikey='parameter'.$keyroot.'_'.$name;
11751: 			    }
11752: 			    if ($subp eq 'display') {
11753: 				$value.=' [Part: '.$part.']';
11754: 			    }
11755: 			    $metaentry{':'.$unikey.'.part'}=$part;
11756: 			    $metathesekeys{$unikey}=1;
11757: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11758: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11759: 			    }
11760: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11761: 				$metaentry{':'.$unikey}=
11762: 				    $metaentry{':'.$unikey.'.default'};
11763: 			    }
11764: 			}
11765: 		    }
11766: 		} else {
11767: #
11768: # This is not a package - some other kind of start tag
11769: #
11770: 		    my $entry=$token->[1];
11771: 		    my $unikey='';
11772: 
11773: 		    if ($entry eq 'import') {
11774: #
11775: # Importing a library here
11776: #
11777:                         my $location=$parser->get_text('/import');
11778:                         my $dir=$filename;
11779:                         $dir=~s|[^/]*$||;
11780:                         $location=&filelocation($dir,$location);
11781:                        
11782:                         my $importmode=$token->[2]->{'importmode'};
11783:                         if ($importmode eq 'problem') {
11784: # Import as problem/response
11785:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11786:                         } elsif ($importmode eq 'part') {
11787: # Import as part(s)
11788:                            $importedparts=1;
11789: # We need to get the original file and the imported file to get the part order correct
11790: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11791: # Load and inspect original file
11792:                            if ($#origfileimportpartids<0) {
11793:                               undef(%importedpartids);
11794:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11795:                               my $origfile=&getfile($origfilelocation);
11796:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11797:                            }
11798: 
11799: # Load and inspect imported file
11800:                            my $impfile=&getfile($location);
11801:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11802:                            if ($#impfilepartids>=0) {
11803: # This problem had parts
11804:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11805:                            } else {
11806: # Importing by turning a single problem into a problem part
11807: # It gets the import-tags ID as part-ID
11808:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11809:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11810:                            }
11811:                         } else {
11812: # Normal import
11813:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11814:                            if (defined($token->[2]->{'id'})) {
11815:                               $unikey.='_'.$token->[2]->{'id'};
11816:                            }
11817:                         }
11818: 
11819: 			if ($depthcount<20) {
11820: 			    my $metadata = 
11821: 				&metadata($uri,'keys', $location,$unikey,
11822: 					  $depthcount+1);
11823: 			    foreach my $meta (split(',',$metadata)) {
11824: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
11825: 				$metathesekeys{$meta}=1;
11826: 			    }
11827: 			
11828:                         }
11829: 		    } else {
11830: #
11831: # Not importing, some other kind of non-package, non-library start tag
11832: # 
11833:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11834:                         if (defined($token->[2]->{'id'})) {
11835:                             $unikey.='_'.$token->[2]->{'id'};
11836:                         }
11837: 			if (defined($token->[2]->{'name'})) { 
11838: 			    $unikey.='_'.$token->[2]->{'name'}; 
11839: 			}
11840: 			$metathesekeys{$unikey}=1;
11841: 			foreach my $param (@{$token->[3]}) {
11842: 			    $metaentry{':'.$unikey.'.'.$param} =
11843: 				$token->[2]->{$param};
11844: 			}
11845: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11846: 			my $default=$metaentry{':'.$unikey.'.default'};
11847: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11848: 		 # only ws inside the tag, and not in default, so use default
11849: 		 # as value
11850: 			    $metaentry{':'.$unikey}=$default;
11851: 			} elsif ( $internaltext =~ /\S/ ) {
11852: 		  # something interesting inside the tag
11853: 			    $metaentry{':'.$unikey}=$internaltext;
11854: 			} else {
11855: 		  # no interesting values, don't set a default
11856: 			}
11857: # end of not-a-package not-a-library import
11858: 		    }
11859: # end of not-a-package start tag
11860: 		}
11861: # the next is the end of "start tag"
11862: 	    }
11863: 	}
11864: 	my ($extension) = ($uri =~ /\.(\w+)$/);
11865: 	$extension = lc($extension);
11866: 	if ($extension eq 'htm') { $extension='html'; }
11867: 
11868: 	foreach my $key (keys(%packagetab)) {
11869: 	    #no specific packages #how's our extension
11870: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
11871: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
11872: 					 \%metathesekeys);
11873: 	}
11874: 
11875: 	if (!exists($metaentry{':packages'})
11876: 	    || $packagetab{"import_defaults&extension_$extension"}) {
11877: 	    foreach my $key (keys(%packagetab)) {
11878: 		#no specific packages well let's get default then
11879: 		if ($key!~/^default&/) { next; }
11880: 		&metadata_create_package_def($uri,$key,'default',
11881: 					     \%metathesekeys);
11882: 	    }
11883: 	}
11884: # are there custom rights to evaluate
11885: 	if ($metaentry{':copyright'} eq 'custom') {
11886: 
11887:     #
11888:     # Importing a rights file here
11889:     #
11890: 	    unless ($depthcount) {
11891: 		my $location=$metaentry{':customdistributionfile'};
11892: 		my $dir=$filename;
11893: 		$dir=~s|[^/]*$||;
11894: 		$location=&filelocation($dir,$location);
11895: 		my $rights_metadata =
11896: 		    &metadata($uri,'keys',$location,'_rights',
11897: 			      $depthcount+1);
11898: 		foreach my $rights (split(',',$rights_metadata)) {
11899: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11900: 		    $metathesekeys{$rights}=1;
11901: 		}
11902: 	    }
11903: 	}
11904: 	# uniqifiy package listing
11905: 	my %seen;
11906: 	my @uniq_packages =
11907: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11908: 	$metaentry{':packages'} = join(',',@uniq_packages);
11909: 
11910:         if ($importedparts) {
11911: # We had imported parts and need to rebuild partorder
11912:            $metaentry{':partorder'}='';
11913:            $metathesekeys{'partorder'}=1;
11914:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11915:                if ($origfileimportpartids[$index] eq 'part') {
11916: # original part, part of the problem
11917:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11918:                } else {
11919: # we have imported parts at this position
11920:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11921:                }
11922:            }
11923:            $metaentry{':partorder'}=~s/^\,//;
11924:         }
11925: 
11926: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
11927: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11928: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11929: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
11930: # this is the end of "was not already recently cached
11931:     }
11932:     return $metaentry{':'.$what};
11933: }
11934: 
11935: sub metadata_create_package_def {
11936:     my ($uri,$key,$package,$metathesekeys)=@_;
11937:     my ($pack,$name,$subp)=split(/\&/,$key);
11938:     if ($subp eq 'default') { next; }
11939:     
11940:     if (defined($metaentry{':packages'})) {
11941: 	$metaentry{':packages'}.=','.$package;
11942:     } else {
11943: 	$metaentry{':packages'}=$package;
11944:     }
11945:     my $value=$packagetab{$key};
11946:     my $unikey;
11947:     $unikey='parameter_0_'.$name;
11948:     $metaentry{':'.$unikey.'.part'}=0;
11949:     $$metathesekeys{$unikey}=1;
11950:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11951: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
11952:     }
11953:     if (defined($metaentry{':'.$unikey.'.default'})) {
11954: 	$metaentry{':'.$unikey}=
11955: 	    $metaentry{':'.$unikey.'.default'};
11956:     }
11957: }
11958: 
11959: sub metadata_generate_part0 {
11960:     my ($metadata,$metacache,$uri) = @_;
11961:     my %allnames;
11962:     foreach my $metakey (keys(%$metadata)) {
11963: 	if ($metakey=~/^parameter\_(.*)/) {
11964: 	  my $part=$$metacache{':'.$metakey.'.part'};
11965: 	  my $name=$$metacache{':'.$metakey.'.name'};
11966: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11967: 	    $allnames{$name}=$part;
11968: 	  }
11969: 	}
11970:     }
11971:     foreach my $name (keys(%allnames)) {
11972:       $$metadata{"parameter_0_$name"}=1;
11973:       my $key=":parameter_0_$name";
11974:       $$metacache{"$key.part"}='0';
11975:       $$metacache{"$key.name"}=$name;
11976:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
11977: 					   $allnames{$name}.'_'.$name.
11978: 					   '.type'};
11979:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
11980: 			     '.display'};
11981:       my $expr='[Part: '.$allnames{$name}.']';
11982:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
11983:       $$metacache{"$key.display"}=$olddis;
11984:     }
11985: }
11986: 
11987: # ------------------------------------------------------ Devalidate title cache
11988: 
11989: sub devalidate_title_cache {
11990:     my ($url)=@_;
11991:     if (!$env{'request.course.id'}) { return; }
11992:     my $symb=&symbread($url);
11993:     if (!$symb) { return; }
11994:     my $key=$env{'request.course.id'}."\0".$symb;
11995:     &devalidate_cache_new('title',$key);
11996: }
11997: 
11998: # ------------------------------------------------- Get the title of a course
11999: 
12000: sub current_course_title {
12001:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12002: }
12003: # ------------------------------------------------- Get the title of a resource
12004: 
12005: sub gettitle {
12006:     my $urlsymb=shift;
12007:     my $symb=&symbread($urlsymb);
12008:     if ($symb) {
12009: 	my $key=$env{'request.course.id'}."\0".$symb;
12010: 	my ($result,$cached)=&is_cached_new('title',$key);
12011: 	if (defined($cached)) { 
12012: 	    return $result;
12013: 	}
12014: 	my ($map,$resid,$url)=&decode_symb($symb);
12015: 	my $title='';
12016: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12017: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12018: 	} else {
12019: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12020: 		    &GDBM_READER(),0640)) {
12021: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12022: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12023: 		untie(%bighash);
12024: 	    }
12025: 	}
12026: 	$title=~s/\&colon\;/\:/gs;
12027: 	if ($title) {
12028: # Remember both $symb and $title for dynamic metadata
12029:             $accesshash{$symb.'___crstitle'}=$title;
12030:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12031: # Cache this title and then return it
12032: 	    return &do_cache_new('title',$key,$title,600);
12033: 	}
12034: 	$urlsymb=$url;
12035:     }
12036:     my $title=&metadata($urlsymb,'title');
12037:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12038:     return $title;
12039: }
12040: 
12041: sub get_slot {
12042:     my ($which,$cnum,$cdom)=@_;
12043:     if (!$cnum || !$cdom) {
12044: 	(undef,my $courseid)=&whichuser();
12045: 	$cdom=$env{'course.'.$courseid.'.domain'};
12046: 	$cnum=$env{'course.'.$courseid.'.num'};
12047:     }
12048:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12049:     my %slotinfo;
12050:     if (exists($remembered{$key})) {
12051: 	$slotinfo{$which} = $remembered{$key};
12052:     } else {
12053: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12054: 	&Apache::lonhomework::showhash(%slotinfo);
12055: 	my ($tmp)=keys(%slotinfo);
12056: 	if ($tmp=~/^error:/) { return (); }
12057: 	$remembered{$key} = $slotinfo{$which};
12058:     }
12059:     if (ref($slotinfo{$which}) eq 'HASH') {
12060: 	return %{$slotinfo{$which}};
12061:     }
12062:     return $slotinfo{$which};
12063: }
12064: 
12065: sub get_reservable_slots {
12066:     my ($cnum,$cdom,$uname,$udom) = @_;
12067:     my $now = time;
12068:     my $reservable_info;
12069:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12070:     if (exists($remembered{$key})) {
12071:         $reservable_info = $remembered{$key};
12072:     } else {
12073:         my %resv;
12074:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12075:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12076:         $reservable_info = \%resv;
12077:         $remembered{$key} = $reservable_info;
12078:     }
12079:     return $reservable_info;
12080: }
12081: 
12082: sub get_course_slots {
12083:     my ($cnum,$cdom) = @_;
12084:     my $hashid=$cnum.':'.$cdom;
12085:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12086:     if (defined($cached)) {
12087:         if (ref($result) eq 'HASH') {
12088:             return %{$result};
12089:         }
12090:     } else {
12091:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12092:         my ($tmp) = keys(%slots);
12093:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12094:             &do_cache_new('allslots',$hashid,\%slots,600);
12095:             return %slots;
12096:         }
12097:     }
12098:     return;
12099: }
12100: 
12101: sub devalidate_slots_cache {
12102:     my ($cnum,$cdom)=@_;
12103:     my $hashid=$cnum.':'.$cdom;
12104:     &devalidate_cache_new('allslots',$hashid);
12105: }
12106: 
12107: sub get_coursechange {
12108:     my ($cdom,$cnum) = @_;
12109:     if ($cdom eq '' || $cnum eq '') {
12110:         return unless ($env{'request.course.id'});
12111:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12112:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12113:     }
12114:     my $hashid=$cdom.'_'.$cnum;
12115:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12116:     if ((defined($cached)) && ($change ne '')) {
12117:         return $change;
12118:     } else {
12119:         my %crshash;
12120:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12121:         if ($crshash{'internal.contentchange'} eq '') {
12122:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12123:             if ($change eq '') {
12124:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12125:                 $change = $crshash{'internal.created'};
12126:             }
12127:         } else {
12128:             $change = $crshash{'internal.contentchange'};
12129:         }
12130:         my $cachetime = 600;
12131:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12132:     }
12133:     return $change;
12134: }
12135: 
12136: sub devalidate_coursechange_cache {
12137:     my ($cnum,$cdom)=@_;
12138:     my $hashid=$cnum.':'.$cdom;
12139:     &devalidate_cache_new('crschange',$hashid);
12140: }
12141: 
12142: # ------------------------------------------------- Update symbolic store links
12143: 
12144: sub symblist {
12145:     my ($mapname,%newhash)=@_;
12146:     $mapname=&deversion(&declutter($mapname));
12147:     my %hash;
12148:     if (($env{'request.course.fn'}) && (%newhash)) {
12149:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12150:                       &GDBM_WRCREAT(),0640)) {
12151: 	    foreach my $url (keys(%newhash)) {
12152: 		next if ($url eq 'last_known'
12153: 			 && $env{'form.no_update_last_known'});
12154: 		$hash{declutter($url)}=&encode_symb($mapname,
12155: 						    $newhash{$url}->[1],
12156: 						    $newhash{$url}->[0]);
12157:             }
12158:             if (untie(%hash)) {
12159: 		return 'ok';
12160:             }
12161:         }
12162:     }
12163:     return 'error';
12164: }
12165: 
12166: # --------------------------------------------------------------- Verify a symb
12167: 
12168: sub symbverify {
12169:     my ($symb,$thisurl,$encstate)=@_;
12170:     my $thisfn=$thisurl;
12171:     $thisfn=&declutter($thisfn);
12172: # direct jump to resource in page or to a sequence - will construct own symbs
12173:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12174: # check URL part
12175:     my ($map,$resid,$url)=&decode_symb($symb);
12176: 
12177:     unless ($url eq $thisfn) { return 0; }
12178: 
12179:     $symb=&symbclean($symb);
12180:     $thisurl=&deversion($thisurl);
12181:     $thisfn=&deversion($thisfn);
12182: 
12183:     my %bighash;
12184:     my $okay=0;
12185: 
12186:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12187:                             &GDBM_READER(),0640)) {
12188:         my $noclutter;
12189:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12190:             $thisurl =~ s/\?.+$//;
12191:             if ($map =~ m{^uploaded/.+\.page$}) {
12192:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12193:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12194:                 $noclutter = 1;
12195:             }
12196:         }
12197:         my $ids;
12198:         if ($noclutter) {
12199:             $ids=$bighash{'ids_'.$thisurl};
12200:         } else {
12201:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12202:         }
12203:         unless ($ids) {
12204:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12205:             $ids=$bighash{$idkey};
12206:         }
12207:         if ($ids) {
12208: # ------------------------------------------------------------------- Has ID(s)
12209:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12210:                 $symb =~ s/\?.+$//;
12211:             }
12212: 	    foreach my $id (split(/\,/,$ids)) {
12213: 	       my ($mapid,$resid)=split(/\./,$id);
12214:                if (
12215:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12216:    eq $symb) {
12217:                    if (ref($encstate)) {
12218:                        $$encstate = $bighash{'encrypted_'.$id};
12219:                    }
12220: 		   if (($env{'request.role.adv'}) ||
12221: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12222:                        ($thisurl eq '/adm/navmaps')) {
12223: 		       $okay=1;
12224:                        last;
12225: 		   }
12226: 	       }
12227: 	   }
12228:         }
12229: 	untie(%bighash);
12230:     }
12231:     return $okay;
12232: }
12233: 
12234: # --------------------------------------------------------------- Clean-up symb
12235: 
12236: sub symbclean {
12237:     my $symb=shift;
12238:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12239: # remove version from map
12240:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12241: 
12242: # remove version from URL
12243:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12244: 
12245: # remove wrapper
12246: 
12247:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12248:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12249:     return $symb;
12250: }
12251: 
12252: # ---------------------------------------------- Split symb to find map and url
12253: 
12254: sub encode_symb {
12255:     my ($map,$resid,$url)=@_;
12256:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12257: }
12258: 
12259: sub decode_symb {
12260:     my $symb=shift;
12261:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12262:     my ($map,$resid,$url)=split(/___/,$symb);
12263:     return (&fixversion($map),$resid,&fixversion($url));
12264: }
12265: 
12266: sub fixversion {
12267:     my $fn=shift;
12268:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12269:     my %bighash;
12270:     my $uri=&clutter($fn);
12271:     my $key=$env{'request.course.id'}.'_'.$uri;
12272: # is this cached?
12273:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12274:     if (defined($cached)) { return $result; }
12275: # unfortunately not cached, or expired
12276:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12277: 	    &GDBM_READER(),0640)) {
12278:  	if ($bighash{'version_'.$uri}) {
12279:  	    my $version=$bighash{'version_'.$uri};
12280:  	    unless (($version eq 'mostrecent') || 
12281: 		    ($version==&getversion($uri))) {
12282:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12283:  	    }
12284:  	}
12285:  	untie %bighash;
12286:     }
12287:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12288: }
12289: 
12290: sub deversion {
12291:     my $url=shift;
12292:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12293:     return $url;
12294: }
12295: 
12296: # ------------------------------------------------------ Return symb list entry
12297: 
12298: sub symbread {
12299:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12300:     my $cache_str='request.symbread.cached.'.$thisfn;
12301:     if (defined($env{$cache_str})) {
12302:         if ($ignorecachednull) {
12303:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12304:         } else {
12305:             return $env{$cache_str};
12306:         }
12307:     }
12308: # no filename provided? try from environment
12309:     unless ($thisfn) {
12310:         if ($env{'request.symb'}) {
12311: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12312: 	}
12313: 	$thisfn=$env{'request.filename'};
12314:     }
12315:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12316: # is that filename actually a symb? Verify, clean, and return
12317:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12318: 	if (&symbverify($thisfn,$1)) {
12319: 	    return $env{$cache_str}=&symbclean($thisfn);
12320: 	}
12321:     }
12322:     $thisfn=declutter($thisfn);
12323:     my %hash;
12324:     my %bighash;
12325:     my $syval='';
12326:     if (($env{'request.course.fn'}) && ($thisfn)) {
12327:         my $targetfn = $thisfn;
12328:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12329:             $targetfn = 'adm/wrapper/'.$thisfn;
12330:         }
12331: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12332: 	    $targetfn=$1;
12333: 	}
12334:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12335:                       &GDBM_READER(),0640)) {
12336: 	    $syval=$hash{$targetfn};
12337:             untie(%hash);
12338:         }
12339: # ---------------------------------------------------------- There was an entry
12340:         if ($syval) {
12341: 	    #unless ($syval=~/\_\d+$/) {
12342: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12343: 		    #&appenv({'request.ambiguous' => $thisfn});
12344: 		    #return $env{$cache_str}='';
12345: 		#}    
12346: 		#$syval.=$1;
12347: 	    #}
12348:         } else {
12349: # ------------------------------------------------------- Was not in symb table
12350:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12351:                             &GDBM_READER(),0640)) {
12352: # ---------------------------------------------- Get ID(s) for current resource
12353:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12354:               unless ($ids) { 
12355:                  $ids=$bighash{'ids_/'.$thisfn};
12356:               }
12357:               unless ($ids) {
12358: # alias?
12359: 		  $ids=$bighash{'mapalias_'.$thisfn};
12360:               }
12361:               if ($ids) {
12362: # ------------------------------------------------------------------- Has ID(s)
12363:                  my @possibilities=split(/\,/,$ids);
12364:                  if ($#possibilities==0) {
12365: # ----------------------------------------------- There is only one possibility
12366: 		     my ($mapid,$resid)=split(/\./,$ids);
12367: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12368: 						    $resid,$thisfn);
12369:                      if (ref($possibles) eq 'HASH') {
12370:                          $possibles->{$syval} = 1;    
12371:                      }
12372:                      if ($checkforblock) {
12373:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12374:                          if (@blockers) {
12375:                              $syval = '';
12376:                              return;
12377:                          }
12378:                      }
12379:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12380: # ------------------------------------------ There is more than one possibility
12381:                      my $realpossible=0;
12382:                      foreach my $id (@possibilities) {
12383: 			 my $file=$bighash{'src_'.$id};
12384:                          my $canaccess;
12385:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12386:                              $canaccess = 1;
12387:                          } else { 
12388:                              $canaccess = &allowed('bre',$file);
12389:                          }
12390:                          if ($canaccess) {
12391:          		     my ($mapid,$resid)=split(/\./,$id);
12392:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12393:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12394: 						             $resid,$thisfn);
12395:                                  if (ref($possibles) eq 'HASH') {
12396:                                      $possibles->{$syval} = 1;
12397:                                  }
12398:                                  if ($checkforblock) {
12399:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12400:                                      unless (@blockers > 0) {
12401:                                          $syval = $poss_syval;
12402:                                          $realpossible++;
12403:                                      }
12404:                                  } else {
12405:                                      $syval = $poss_syval;
12406:                                      $realpossible++;
12407:                                  }
12408:                              }
12409: 			 }
12410:                      }
12411: 		     if ($realpossible!=1) { $syval=''; }
12412:                  } else {
12413:                      $syval='';
12414:                  }
12415: 	      }
12416:               untie(%bighash);
12417:            }
12418:         }
12419:         if ($syval) {
12420: 	    return $env{$cache_str}=$syval;
12421:         }
12422:     }
12423:     &appenv({'request.ambiguous' => $thisfn});
12424:     return $env{$cache_str}='';
12425: }
12426: 
12427: # ---------------------------------------------------------- Return random seed
12428: 
12429: sub numval {
12430:     my $txt=shift;
12431:     $txt=~tr/A-J/0-9/;
12432:     $txt=~tr/a-j/0-9/;
12433:     $txt=~tr/K-T/0-9/;
12434:     $txt=~tr/k-t/0-9/;
12435:     $txt=~tr/U-Z/0-5/;
12436:     $txt=~tr/u-z/0-5/;
12437:     $txt=~s/\D//g;
12438:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12439:     return int($txt);
12440: }
12441: 
12442: sub numval2 {
12443:     my $txt=shift;
12444:     $txt=~tr/A-J/0-9/;
12445:     $txt=~tr/a-j/0-9/;
12446:     $txt=~tr/K-T/0-9/;
12447:     $txt=~tr/k-t/0-9/;
12448:     $txt=~tr/U-Z/0-5/;
12449:     $txt=~tr/u-z/0-5/;
12450:     $txt=~s/\D//g;
12451:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12452:     my $total;
12453:     foreach my $val (@txts) { $total+=$val; }
12454:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12455:     return int($total);
12456: }
12457: 
12458: sub numval3 {
12459:     use integer;
12460:     my $txt=shift;
12461:     $txt=~tr/A-J/0-9/;
12462:     $txt=~tr/a-j/0-9/;
12463:     $txt=~tr/K-T/0-9/;
12464:     $txt=~tr/k-t/0-9/;
12465:     $txt=~tr/U-Z/0-5/;
12466:     $txt=~tr/u-z/0-5/;
12467:     $txt=~s/\D//g;
12468:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12469:     my $total;
12470:     foreach my $val (@txts) { $total+=$val; }
12471:     if ($_64bit) { $total=(($total<<32)>>32); }
12472:     return $total;
12473: }
12474: 
12475: sub digest {
12476:     my ($data)=@_;
12477:     my $digest=&Digest::MD5::md5($data);
12478:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12479:     my ($e,$f);
12480:     {
12481:         use integer;
12482:         $e=($a+$b);
12483:         $f=($c+$d);
12484:         if ($_64bit) {
12485:             $e=(($e<<32)>>32);
12486:             $f=(($f<<32)>>32);
12487:         }
12488:     }
12489:     if (wantarray) {
12490: 	return ($e,$f);
12491:     } else {
12492: 	my $g;
12493: 	{
12494: 	    use integer;
12495: 	    $g=($e+$f);
12496: 	    if ($_64bit) {
12497: 		$g=(($g<<32)>>32);
12498: 	    }
12499: 	}
12500: 	return $g;
12501:     }
12502: }
12503: 
12504: sub latest_rnd_algorithm_id {
12505:     return '64bit5';
12506: }
12507: 
12508: sub get_rand_alg {
12509:     my ($courseid)=@_;
12510:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12511:     if ($courseid) {
12512: 	return $env{"course.$courseid.rndseed"};
12513:     }
12514:     return &latest_rnd_algorithm_id();
12515: }
12516: 
12517: sub validCODE {
12518:     my ($CODE)=@_;
12519:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12520:     return 0;
12521: }
12522: 
12523: sub getCODE {
12524:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12525:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12526: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12527: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12528: 	return $Apache::lonhomework::history{'resource.CODE'};
12529:     }
12530:     return undef;
12531: }
12532: #
12533: #  Determines the random seed for a specific context:
12534: #
12535: # parameters:
12536: #   symb      - in course context the symb for the seed.
12537: #   course_id - The course id of the form domain_coursenum.
12538: #   domain    - Domain for the user.
12539: #   course    - Course for the user.
12540: #   cenv      - environment of the course.
12541: #
12542: # NOTE:
12543: #   All parameters are picked out of the environment if missing
12544: #   or not defined.
12545: #   If a symb cannot be determined the current time is used instead.
12546: #
12547: #  For a given well defined symb, courside, domain, username,
12548: #  and course environment, the seed is reproducible.
12549: #
12550: sub rndseed {
12551:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12552:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12553:     if (!defined($symb)) {
12554: 	unless ($symb=$wsymb) { return time; }
12555:     }
12556:     if (!defined $courseid) { 
12557: 	$courseid=$wcourseid; 
12558:     }
12559:     if (!defined $domain) { $domain=$wdomain; }
12560:     if (!defined $username) { $username=$wusername }
12561: 
12562:     my $which;
12563:     if (defined($cenv->{'rndseed'})) {
12564: 	$which = $cenv->{'rndseed'};
12565:     } else {
12566: 	$which =&get_rand_alg($courseid);
12567:     }
12568:     if (defined(&getCODE())) {
12569: 
12570: 	if ($which eq '64bit5') {
12571: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12572: 	} elsif ($which eq '64bit4') {
12573: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12574: 	} else {
12575: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12576: 	}
12577:     } elsif ($which eq '64bit5') {
12578: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12579:     } elsif ($which eq '64bit4') {
12580: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12581:     } elsif ($which eq '64bit3') {
12582: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12583:     } elsif ($which eq '64bit2') {
12584: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12585:     } elsif ($which eq '64bit') {
12586: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12587:     }
12588:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12589: }
12590: 
12591: sub rndseed_32bit {
12592:     my ($symb,$courseid,$domain,$username)=@_;
12593:     {
12594: 	use integer;
12595: 	my $symbchck=unpack("%32C*",$symb) << 27;
12596: 	my $symbseed=numval($symb) << 22;
12597: 	my $namechck=unpack("%32C*",$username) << 17;
12598: 	my $nameseed=numval($username) << 12;
12599: 	my $domainseed=unpack("%32C*",$domain) << 7;
12600: 	my $courseseed=unpack("%32C*",$courseid);
12601: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12602: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12603: 	#&logthis("rndseed :$num:$symb");
12604: 	if ($_64bit) { $num=(($num<<32)>>32); }
12605: 	return $num;
12606:     }
12607: }
12608: 
12609: sub rndseed_64bit {
12610:     my ($symb,$courseid,$domain,$username)=@_;
12611:     {
12612: 	use integer;
12613: 	my $symbchck=unpack("%32S*",$symb) << 21;
12614: 	my $symbseed=numval($symb) << 10;
12615: 	my $namechck=unpack("%32S*",$username);
12616: 	
12617: 	my $nameseed=numval($username) << 21;
12618: 	my $domainseed=unpack("%32S*",$domain) << 10;
12619: 	my $courseseed=unpack("%32S*",$courseid);
12620: 	
12621: 	my $num1=$symbchck+$symbseed+$namechck;
12622: 	my $num2=$nameseed+$domainseed+$courseseed;
12623: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12624: 	#&logthis("rndseed :$num:$symb");
12625: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12626: 	return "$num1,$num2";
12627:     }
12628: }
12629: 
12630: sub rndseed_64bit2 {
12631:     my ($symb,$courseid,$domain,$username)=@_;
12632:     {
12633: 	use integer;
12634: 	# strings need to be an even # of cahracters long, it it is odd the
12635:         # last characters gets thrown away
12636: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12637: 	my $symbseed=numval($symb) << 10;
12638: 	my $namechck=unpack("%32S*",$username.' ');
12639: 	
12640: 	my $nameseed=numval($username) << 21;
12641: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12642: 	my $courseseed=unpack("%32S*",$courseid.' ');
12643: 	
12644: 	my $num1=$symbchck+$symbseed+$namechck;
12645: 	my $num2=$nameseed+$domainseed+$courseseed;
12646: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12647: 	#&logthis("rndseed :$num:$symb");
12648: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12649: 	return "$num1,$num2";
12650:     }
12651: }
12652: 
12653: sub rndseed_64bit3 {
12654:     my ($symb,$courseid,$domain,$username)=@_;
12655:     {
12656: 	use integer;
12657: 	# strings need to be an even # of cahracters long, it it is odd the
12658:         # last characters gets thrown away
12659: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12660: 	my $symbseed=numval2($symb) << 10;
12661: 	my $namechck=unpack("%32S*",$username.' ');
12662: 	
12663: 	my $nameseed=numval2($username) << 21;
12664: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12665: 	my $courseseed=unpack("%32S*",$courseid.' ');
12666: 	
12667: 	my $num1=$symbchck+$symbseed+$namechck;
12668: 	my $num2=$nameseed+$domainseed+$courseseed;
12669: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12670: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12671: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12672: 	
12673: 	return "$num1:$num2";
12674:     }
12675: }
12676: 
12677: sub rndseed_64bit4 {
12678:     my ($symb,$courseid,$domain,$username)=@_;
12679:     {
12680: 	use integer;
12681: 	# strings need to be an even # of cahracters long, it it is odd the
12682:         # last characters gets thrown away
12683: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12684: 	my $symbseed=numval3($symb) << 10;
12685: 	my $namechck=unpack("%32S*",$username.' ');
12686: 	
12687: 	my $nameseed=numval3($username) << 21;
12688: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12689: 	my $courseseed=unpack("%32S*",$courseid.' ');
12690: 	
12691: 	my $num1=$symbchck+$symbseed+$namechck;
12692: 	my $num2=$nameseed+$domainseed+$courseseed;
12693: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12694: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12695: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12696: 	
12697: 	return "$num1:$num2";
12698:     }
12699: }
12700: 
12701: sub rndseed_64bit5 {
12702:     my ($symb,$courseid,$domain,$username)=@_;
12703:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12704:     return "$num1:$num2";
12705: }
12706: 
12707: sub rndseed_CODE_64bit {
12708:     my ($symb,$courseid,$domain,$username)=@_;
12709:     {
12710: 	use integer;
12711: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12712: 	my $symbseed=numval2($symb);
12713: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12714: 	my $CODEseed=numval(&getCODE());
12715: 	my $courseseed=unpack("%32S*",$courseid.' ');
12716: 	my $num1=$symbseed+$CODEchck;
12717: 	my $num2=$CODEseed+$courseseed+$symbchck;
12718: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12719: 	#&logthis("rndseed :$num1:$num2:$symb");
12720: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12721: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12722: 	return "$num1:$num2";
12723:     }
12724: }
12725: 
12726: sub rndseed_CODE_64bit4 {
12727:     my ($symb,$courseid,$domain,$username)=@_;
12728:     {
12729: 	use integer;
12730: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12731: 	my $symbseed=numval3($symb);
12732: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12733: 	my $CODEseed=numval3(&getCODE());
12734: 	my $courseseed=unpack("%32S*",$courseid.' ');
12735: 	my $num1=$symbseed+$CODEchck;
12736: 	my $num2=$CODEseed+$courseseed+$symbchck;
12737: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12738: 	#&logthis("rndseed :$num1:$num2:$symb");
12739: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12740: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12741: 	return "$num1:$num2";
12742:     }
12743: }
12744: 
12745: sub rndseed_CODE_64bit5 {
12746:     my ($symb,$courseid,$domain,$username)=@_;
12747:     my $code = &getCODE();
12748:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12749:     return "$num1:$num2";
12750: }
12751: 
12752: sub setup_random_from_rndseed {
12753:     my ($rndseed)=@_;
12754:     if ($rndseed =~/([,:])/) {
12755:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12756:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12757:             &Math::Random::random_set_seed_from_phrase($rndseed);
12758:         } else {
12759:             &Math::Random::random_set_seed($num1,$num2);
12760:         }
12761:     } else {
12762: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12763:     }
12764: }
12765: 
12766: sub latest_receipt_algorithm_id {
12767:     return 'receipt3';
12768: }
12769: 
12770: sub recunique {
12771:     my $fucourseid=shift;
12772:     my $unique;
12773:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12774: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12775: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12776:     } else {
12777: 	$unique=$perlvar{'lonReceipt'};
12778:     }
12779:     return unpack("%32C*",$unique);
12780: }
12781: 
12782: sub recprefix {
12783:     my $fucourseid=shift;
12784:     my $prefix;
12785:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12786: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12787: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
12788:     } else {
12789: 	$prefix=$perlvar{'lonHostID'};
12790:     }
12791:     return unpack("%32C*",$prefix);
12792: }
12793: 
12794: sub ireceipt {
12795:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12796: 
12797:     my $return =&recprefix($fucourseid).'-';
12798: 
12799:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12800: 	$env{'request.state'} eq 'construct') {
12801: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12802: 	return $return;
12803:     }
12804: 
12805:     my $cuname=unpack("%32C*",$funame);
12806:     my $cudom=unpack("%32C*",$fudom);
12807:     my $cucourseid=unpack("%32C*",$fucourseid);
12808:     my $cusymb=unpack("%32C*",$fusymb);
12809:     my $cunique=&recunique($fucourseid);
12810:     my $cpart=unpack("%32S*",$part);
12811:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12812: 
12813: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
12814: 			       
12815: 	$return.= ($cunique%$cuname+
12816: 		   $cunique%$cudom+
12817: 		   $cusymb%$cuname+
12818: 		   $cusymb%$cudom+
12819: 		   $cucourseid%$cuname+
12820: 		   $cucourseid%$cudom+
12821: 		   $cpart%$cuname+
12822: 		   $cpart%$cudom);
12823:     } else {
12824: 	$return.= ($cunique%$cuname+
12825: 		   $cunique%$cudom+
12826: 		   $cusymb%$cuname+
12827: 		   $cusymb%$cudom+
12828: 		   $cucourseid%$cuname+
12829: 		   $cucourseid%$cudom);
12830:     }
12831:     return $return;
12832: }
12833: 
12834: sub receipt {
12835:     my ($part)=@_;
12836:     my ($symb,$courseid,$domain,$name) = &whichuser();
12837:     return &ireceipt($name,$domain,$courseid,$symb,$part);
12838: }
12839: 
12840: sub whichuser {
12841:     my ($passedsymb)=@_;
12842:     my ($symb,$courseid,$domain,$name,$publicuser);
12843:     if (defined($env{'form.grade_symb'})) {
12844: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12845: 	my $allowed=&allowed('vgr',$tmp_courseid);
12846: 	if (!$allowed &&
12847: 	    exists($env{'request.course.sec'}) &&
12848: 	    $env{'request.course.sec'} !~ /^\s*$/) {
12849: 	    $allowed=&allowed('vgr',$tmp_courseid.
12850: 			      '/'.$env{'request.course.sec'});
12851: 	}
12852: 	if ($allowed) {
12853: 	    ($symb)=&get_env_multiple('form.grade_symb');
12854: 	    $courseid=$tmp_courseid;
12855: 	    ($domain)=&get_env_multiple('form.grade_domain');
12856: 	    ($name)=&get_env_multiple('form.grade_username');
12857: 	    return ($symb,$courseid,$domain,$name,$publicuser);
12858: 	}
12859:     }
12860:     if (!$passedsymb) {
12861: 	$symb=&symbread();
12862:     } else {
12863: 	$symb=$passedsymb;
12864:     }
12865:     $courseid=$env{'request.course.id'};
12866:     $domain=$env{'user.domain'};
12867:     $name=$env{'user.name'};
12868:     if ($name eq 'public' && $domain eq 'public') {
12869: 	if (!defined($env{'form.username'})) {
12870: 	    $env{'form.username'}.=time.rand(10000000);
12871: 	}
12872: 	$name.=$env{'form.username'};
12873:     }
12874:     return ($symb,$courseid,$domain,$name,$publicuser);
12875: 
12876: }
12877: 
12878: # ------------------------------------------------------------ Serves up a file
12879: # returns either the contents of the file or 
12880: # -1 if the file doesn't exist
12881: #
12882: # if the target is a file that was uploaded via DOCS, 
12883: # a check will be made to see if a current copy exists on the local server,
12884: # if it does this will be served, otherwise a copy will be retrieved from
12885: # the home server for the course and stored in /home/httpd/html/userfiles on
12886: # the local server.   
12887: 
12888: sub getfile {
12889:     my ($file) = @_;
12890:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12891:     &repcopy($file);
12892:     return &readfile($file);
12893: }
12894: 
12895: sub repcopy_userfile {
12896:     my ($file)=@_;
12897:     my $londocroot = $perlvar{'lonDocRoot'};
12898:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12899:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12900:     my ($cdom,$cnum,$filename) = 
12901: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12902:     my $uri="/uploaded/$cdom/$cnum/$filename";
12903:     if (-e "$file") {
12904: # we already have a local copy, check it out
12905: 	my @fileinfo = stat($file);
12906: 	my $rtncode;
12907: 	my $info;
12908: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12909: 	if ($lwpresp ne 'ok') {
12910: # there is no such file anymore, even though we had a local copy
12911: 	    if ($rtncode eq '404') {
12912: 		unlink($file);
12913: 	    }
12914: 	    return -1;
12915: 	}
12916: 	if ($info < $fileinfo[9]) {
12917: # nice, the file we have is up-to-date, just say okay
12918: 	    return 'ok';
12919: 	} else {
12920: # the file is outdated, get rid of it
12921: 	    unlink($file);
12922: 	}
12923:     }
12924: # one way or the other, at this point, we don't have the file
12925: # construct the correct path for the file
12926:     my @parts = ($cdom,$cnum); 
12927:     if ($filename =~ m|^(.+)/[^/]+$|) {
12928: 	push @parts, split(/\//,$1);
12929:     }
12930:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12931:     foreach my $part (@parts) {
12932: 	$path .= '/'.$part;
12933: 	if (!-e $path) {
12934: 	    mkdir($path,0770);
12935: 	}
12936:     }
12937: # now the path exists for sure
12938: # get a user agent
12939:     my $transferfile=$file.'.in.transfer';
12940: # FIXME: this should flock
12941:     if (-e $transferfile) { return 'ok'; }
12942:     my $request;
12943:     $uri=~s/^\///;
12944:     my $homeserver = &homeserver($cnum,$cdom);
12945:     my $protocol = $protocol{$homeserver};
12946:     $protocol = 'http' if ($protocol ne 'https');
12947:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12948:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
12949: # did it work?
12950:     if ($response->is_error()) {
12951: 	unlink($transferfile);
12952: 	&logthis("Userfile repcopy failed for $uri");
12953: 	return -1;
12954:     }
12955: # worked, rename the transfer file
12956:     rename($transferfile,$file);
12957:     return 'ok';
12958: }
12959: 
12960: sub tokenwrapper {
12961:     my $uri=shift;
12962:     $uri=~s|^https?\://([^/]+)||;
12963:     $uri=~s|^/||;
12964:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
12965:     my $token=$1;
12966:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
12967:     if ($udom && $uname && $file) {
12968: 	$file=~s|(\?\.*)*$||;
12969:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12970:         my $homeserver = &homeserver($uname,$udom);
12971:         my $protocol = $protocol{$homeserver};
12972:         $protocol = 'http' if ($protocol ne 'https');
12973:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12974:                (($uri=~/\?/)?'&':'?').'token='.$token.
12975:                                '&tokenissued='.$perlvar{'lonHostID'};
12976:     } else {
12977:         return '/adm/notfound.html';
12978:     }
12979: }
12980: 
12981: # call with reqtype HEAD: get last modification time
12982: # call with reqtype GET: get the file contents
12983: # Do not call this with reqtype GET for large files! It loads everything into memory
12984: #
12985: sub getuploaded {
12986:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12987:     $uri=~s/^\///;
12988:     my $homeserver = &homeserver($cnum,$cdom);
12989:     my $protocol = $protocol{$homeserver};
12990:     $protocol = 'http' if ($protocol ne 'https');
12991:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
12992:     my $request=new HTTP::Request($reqtype,$uri);
12993:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
12994:     $$rtncode = $response->code;
12995:     if (! $response->is_success()) {
12996: 	return 'failed';
12997:     }      
12998:     if ($reqtype eq 'HEAD') {
12999: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13000:     } elsif ($reqtype eq 'GET') {
13001: 	$$info = $response->content;
13002:     }
13003:     return 'ok';
13004: }
13005: 
13006: sub readfile {
13007:     my $file = shift;
13008:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13009:     my $fh;
13010:     open($fh,"<$file");
13011:     my $a='';
13012:     while (my $line = <$fh>) { $a .= $line; }
13013:     return $a;
13014: }
13015: 
13016: sub filelocation {
13017:     my ($dir,$file) = @_;
13018:     my $location;
13019:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13020: 
13021:     if ($file =~ m-^/adm/-) {
13022: 	$file=~s-^/adm/wrapper/-/-;
13023: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13024:     }
13025: 
13026:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13027:         $location = $file;
13028:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13029:         my ($udom,$uname,$filename)=
13030:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13031:         my $home=&homeserver($uname,$udom);
13032:         my $is_me=0;
13033:         my @ids=&current_machine_ids();
13034:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13035:         if ($is_me) {
13036:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13037:         } else {
13038:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13039:   	      $udom.'/'.$uname.'/'.$filename;
13040:         }
13041:     } elsif ($file =~ m-^/adm/-) {
13042: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13043:     } else {
13044:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13045:         $file=~s:^/(res|priv)/:/:;
13046:         my $space=$1;
13047:         if ( !( $file =~ m:^/:) ) {
13048:             $location = $dir. '/'.$file;
13049:         } else {
13050:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13051:         }
13052:     }
13053:     $location=~s://+:/:g; # remove duplicate /
13054:     while ($location=~m{/\.\./}) {
13055: 	if ($location =~ m{/[^/]+/\.\./}) {
13056: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13057: 	} else {
13058: 	    $location=~ s{/\.\./}{/}g;
13059: 	}
13060:     } #remove dir/..
13061:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13062:     return $location;
13063: }
13064: 
13065: sub hreflocation {
13066:     my ($dir,$file)=@_;
13067:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13068: 	$file=filelocation($dir,$file);
13069:     } elsif ($file=~m-^/adm/-) {
13070: 	$file=~s-^/adm/wrapper/-/-;
13071: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13072:     }
13073:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13074: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13075:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13076: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13077: 	        {/uploaded/$1/$2/}x;
13078:     }
13079:     if ($file=~ m{^/userfiles/}) {
13080: 	$file =~ s{^/userfiles/}{/uploaded/};
13081:     }
13082:     return $file;
13083: }
13084: 
13085: 
13086: 
13087: 
13088: 
13089: sub current_machine_domains {
13090:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13091: }
13092: 
13093: sub machine_domains {
13094:     my ($hostname) = @_;
13095:     my @domains;
13096:     my %hostname = &all_hostnames();
13097:     while( my($id, $name) = each(%hostname)) {
13098: #	&logthis("-$id-$name-$hostname-");
13099: 	if ($hostname eq $name) {
13100: 	    push(@domains,&host_domain($id));
13101: 	}
13102:     }
13103:     return @domains;
13104: }
13105: 
13106: sub current_machine_ids {
13107:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13108: }
13109: 
13110: sub machine_ids {
13111:     my ($hostname) = @_;
13112:     $hostname ||= &hostname($perlvar{'lonHostID'});
13113:     my @ids;
13114:     my %name_to_host = &all_names();
13115:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13116: 	return @{ $name_to_host{$hostname} };
13117:     }
13118:     return;
13119: }
13120: 
13121: sub additional_machine_domains {
13122:     my @domains;
13123:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
13124:     while( my $line = <$fh>) {
13125:         $line =~ s/\s//g;
13126:         push(@domains,$line);
13127:     }
13128:     return @domains;
13129: }
13130: 
13131: sub default_login_domain {
13132:     my $domain = $perlvar{'lonDefDomain'};
13133:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13134:     foreach my $posdom (&current_machine_domains(),
13135:                         &additional_machine_domains()) {
13136:         if (lc($posdom) eq lc($testdomain)) {
13137:             $domain=$posdom;
13138:             last;
13139:         }
13140:     }
13141:     return $domain;
13142: }
13143: 
13144: # ------------------------------------------------------------- Declutters URLs
13145: 
13146: sub declutter {
13147:     my $thisfn=shift;
13148:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13149:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13150:         $thisfn=~s{^/home/httpd/html}{};
13151:     }
13152:     $thisfn=~s/^\///;
13153:     $thisfn=~s|^adm/wrapper/||;
13154:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13155:     $thisfn=~s/^res\///;
13156:     $thisfn=~s/^priv\///;
13157:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13158:         $thisfn=~s/\?.+$//;
13159:     }
13160:     return $thisfn;
13161: }
13162: 
13163: # ------------------------------------------------------------- Clutter up URLs
13164: 
13165: sub clutter {
13166:     my $thisfn='/'.&declutter(shift);
13167:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13168: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13169:        $thisfn='/res'.$thisfn; 
13170:     }
13171:     if ($thisfn !~m|^/adm|) {
13172: 	if ($thisfn =~ m|^/ext/|) {
13173: 	    $thisfn='/adm/wrapper'.$thisfn;
13174: 	} else {
13175: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13176: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13177: 	    if ($embstyle eq 'ssi'
13178: 		|| ($embstyle eq 'hdn')
13179: 		|| ($embstyle eq 'rat')
13180: 		|| ($embstyle eq 'prv')
13181: 		|| ($embstyle eq 'ign')) {
13182: 		#do nothing with these
13183: 	    } elsif (($embstyle eq 'img') 
13184: 		|| ($embstyle eq 'emb')
13185: 		|| ($embstyle eq 'wrp')) {
13186: 		$thisfn='/adm/wrapper'.$thisfn;
13187: 	    } elsif ($embstyle eq 'unk'
13188: 		     && $thisfn!~/\.(sequence|page)$/) {
13189: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13190: 	    } else {
13191: #		&logthis("Got a blank emb style");
13192: 	    }
13193: 	}
13194:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13195:         $thisfn='/adm/wrapper'.$thisfn;
13196:     }
13197:     return $thisfn;
13198: }
13199: 
13200: sub clutter_with_no_wrapper {
13201:     my $uri = &clutter(shift);
13202:     if ($uri =~ m-^/adm/-) {
13203: 	$uri =~ s-^/adm/wrapper/-/-;
13204: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13205:     }
13206:     return $uri;
13207: }
13208: 
13209: sub freeze_escape {
13210:     my ($value)=@_;
13211:     if (ref($value)) {
13212: 	$value=&nfreeze($value);
13213: 	return '__FROZEN__'.&escape($value);
13214:     }
13215:     return &escape($value);
13216: }
13217: 
13218: 
13219: sub thaw_unescape {
13220:     my ($value)=@_;
13221:     if ($value =~ /^__FROZEN__/) {
13222: 	substr($value,0,10,undef);
13223: 	$value=&unescape($value);
13224: 	return &thaw($value);
13225:     }
13226:     return &unescape($value);
13227: }
13228: 
13229: sub correct_line_ends {
13230:     my ($result)=@_;
13231:     $$result =~s/\r\n/\n/mg;
13232:     $$result =~s/\r/\n/mg;
13233: }
13234: # ================================================================ Main Program
13235: 
13236: sub goodbye {
13237:    &logthis("Starting Shut down");
13238: #not converted to using infrastruture and probably shouldn't be
13239:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13240: #converted
13241: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13242:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13243: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13244: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13245: #1.1 only
13246: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13247: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13248: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13249: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13250:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13251:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13252:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13253:    &flushcourselogs();
13254:    &logthis("Shutting down");
13255: }
13256: 
13257: sub get_dns {
13258:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13259:     if (!$ignore_cache) {
13260: 	my ($content,$cached)=
13261: 	    &Apache::lonnet::is_cached_new('dns',$url);
13262: 	if ($cached) {
13263: 	    &$func($content,$hashref);
13264: 	    return;
13265: 	}
13266:     }
13267: 
13268:     my %alldns;
13269:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13270:     foreach my $dns (<$config>) {
13271: 	next if ($dns !~ /^\^(\S*)/x);
13272:         my $line = $1;
13273:         my ($host,$protocol) = split(/:/,$line);
13274:         if ($protocol ne 'https') {
13275:             $protocol = 'http';
13276:         }
13277: 	$alldns{$host} = $protocol;
13278:     }
13279:     while (%alldns) {
13280: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13281: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13282:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13283:         delete($alldns{$dns});
13284: 	next if ($response->is_error());
13285: 	my @content = split("\n",$response->content);
13286: 	unless ($nocache) {
13287: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13288: 	}
13289: 	&$func(\@content,$hashref);
13290: 	return;
13291:     }
13292:     close($config);
13293:     my $which = (split('/',$url))[3];
13294:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13295:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
13296:     my @content = <$config>;
13297:     &$func(\@content,$hashref);
13298:     return;
13299: }
13300: 
13301: # ------------------------------------------------------Get DNS checksums file
13302: sub parse_dns_checksums_tab {
13303:     my ($lines,$hashref) = @_;
13304:     my $lonhost = $perlvar{'lonHostID'};
13305:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13306:     my $loncaparev = &get_server_loncaparev($machine_dom);
13307:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13308:     my $webconfdir = '/etc/httpd/conf';
13309:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13310:         $webconfdir = '/etc/apache2';
13311:     } elsif ($distro =~ /^sles(\d+)$/) {
13312:         if ($1 >= 10) {
13313:             $webconfdir = '/etc/apache2';
13314:         }
13315:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13316:         if ($1 >= 10.0) {
13317:             $webconfdir = '/etc/apache2';
13318:         }
13319:     }
13320:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13321:     my (%chksum,%revnum);
13322:     if (ref($lines) eq 'ARRAY') {
13323:         chomp(@{$lines});
13324:         my $version = shift(@{$lines});
13325:         if ($version eq $release) {  
13326:             foreach my $line (@{$lines}) {
13327:                 my ($file,$version,$shasum) = split(/,/,$line);
13328:                 if ($file =~ m{^/etc/httpd/conf}) {
13329:                     if ($webconfdir eq '/etc/apache2') {
13330:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13331:                     }
13332:                 }
13333:                 $chksum{$file} = $shasum;
13334:                 $revnum{$file} = $version;
13335:             }
13336:             if (ref($hashref) eq 'HASH') {
13337:                 %{$hashref} = (
13338:                                 sums     => \%chksum,
13339:                                 versions => \%revnum,
13340:                               );
13341:             }
13342:         }
13343:     }
13344:     return;
13345: }
13346: 
13347: sub fetch_dns_checksums {
13348:     my %checksums;
13349:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13350:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13351:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13352:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13353:              \%checksums);
13354:     return \%checksums;
13355: }
13356: 
13357: # ------------------------------------------------------------ Read domain file
13358: {
13359:     my $loaded;
13360:     my %domain;
13361: 
13362:     sub parse_domain_tab {
13363: 	my ($lines) = @_;
13364: 	foreach my $line (@$lines) {
13365: 	    next if ($line =~ /^(\#|\s*$ )/x);
13366: 
13367: 	    chomp($line);
13368: 	    my ($name,@elements) = split(/:/,$line,9);
13369: 	    my %this_domain;
13370: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13371: 			       'lang_def', 'city', 'longi', 'lati',
13372: 			       'primary') {
13373: 		$this_domain{$field} = shift(@elements);
13374: 	    }
13375: 	    $domain{$name} = \%this_domain;
13376: 	}
13377:     }
13378: 
13379:     sub reset_domain_info {
13380: 	undef($loaded);
13381: 	undef(%domain);
13382:     }
13383: 
13384:     sub load_domain_tab {
13385: 	my ($ignore_cache,$nocache) = @_;
13386: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13387: 	my $fh;
13388: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13389: 	    my @lines = <$fh>;
13390: 	    &parse_domain_tab(\@lines);
13391: 	}
13392: 	close($fh);
13393: 	$loaded = 1;
13394:     }
13395: 
13396:     sub domain {
13397: 	&load_domain_tab() if (!$loaded);
13398: 
13399: 	my ($name,$what) = @_;
13400: 	return if ( !exists($domain{$name}) );
13401: 
13402: 	if (!$what) {
13403: 	    return $domain{$name}{'description'};
13404: 	}
13405: 	return $domain{$name}{$what};
13406:     }
13407: 
13408:     sub domain_info {
13409:         &load_domain_tab() if (!$loaded);
13410:         return %domain;
13411:     }
13412: 
13413: }
13414: 
13415: 
13416: # ------------------------------------------------------------- Read hosts file
13417: {
13418:     my %hostname;
13419:     my %hostdom;
13420:     my %libserv;
13421:     my $loaded;
13422:     my %name_to_host;
13423:     my %internetdom;
13424:     my %LC_dns_serv;
13425: 
13426:     sub parse_hosts_tab {
13427: 	my ($file) = @_;
13428: 	foreach my $configline (@$file) {
13429: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13430:             chomp($configline);
13431: 	    if ($configline =~ /^\^/) {
13432:                 if ($configline =~ /^\^([\w.\-]+)/) {
13433:                     $LC_dns_serv{$1} = 1;
13434:                 }
13435:                 next;
13436:             }
13437: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13438: 	    $name=~s/\s//g;
13439: 	    if ($id && $domain && $role && $name) {
13440:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13441:                     my $curr = $hostname{$id};
13442:                     my $skip;
13443:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13444:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13445:                             $skip = 1;
13446:                         } else {
13447:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13448:                         }
13449:                     }
13450:                     unless ($skip) {
13451:                         push(@{$name_to_host{$name}},$id);
13452:                     }
13453:                 } else {
13454:                     push(@{$name_to_host{$name}},$id);
13455:                 }
13456: 		$hostname{$id}=$name;
13457: 		$hostdom{$id}=$domain;
13458: 		if ($role eq 'library') { $libserv{$id}=$name; }
13459:                 if (defined($protocol)) {
13460:                     if ($protocol eq 'https') {
13461:                         $protocol{$id} = $protocol;
13462:                     } else {
13463:                         $protocol{$id} = 'http'; 
13464:                     }
13465:                 } else {
13466:                     $protocol{$id} = 'http';
13467:                 }
13468:                 if (defined($intdom)) {
13469:                     $internetdom{$id} = $intdom;
13470:                 }
13471: 	    }
13472: 	}
13473:     }
13474:     
13475:     sub reset_hosts_info {
13476: 	&purge_remembered();
13477: 	&reset_domain_info();
13478: 	&reset_hosts_ip_info();
13479:         undef(%internetdom);
13480: 	undef(%name_to_host);
13481: 	undef(%hostname);
13482: 	undef(%hostdom);
13483: 	undef(%libserv);
13484: 	undef($loaded);
13485:     }
13486: 
13487:     sub load_hosts_tab {
13488: 	my ($ignore_cache,$nocache) = @_;
13489: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13490: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13491: 	my @config = <$config>;
13492: 	&parse_hosts_tab(\@config);
13493: 	close($config);
13494: 	$loaded=1;
13495:     }
13496: 
13497:     sub hostname {
13498: 	&load_hosts_tab() if (!$loaded);
13499: 
13500: 	my ($lonid) = @_;
13501: 	return $hostname{$lonid};
13502:     }
13503: 
13504:     sub all_hostnames {
13505: 	&load_hosts_tab() if (!$loaded);
13506: 
13507: 	return %hostname;
13508:     }
13509: 
13510:     sub all_names {
13511:         my ($ignore_cache,$nocache) = @_;
13512: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13513: 
13514: 	return %name_to_host;
13515:     }
13516: 
13517:     sub all_host_domain {
13518:         &load_hosts_tab() if (!$loaded);
13519:         return %hostdom;
13520:     }
13521: 
13522:     sub all_host_intdom {
13523:         &load_hosts_tab() if (!$loaded);
13524:         return %internetdom;
13525:     }
13526: 
13527:     sub is_library {
13528: 	&load_hosts_tab() if (!$loaded);
13529: 
13530: 	return exists($libserv{$_[0]});
13531:     }
13532: 
13533:     sub all_library {
13534: 	&load_hosts_tab() if (!$loaded);
13535: 
13536: 	return %libserv;
13537:     }
13538: 
13539:     sub unique_library {
13540: 	#2x reverse removes all hostnames that appear more than once
13541:         my %unique = reverse &all_library();
13542:         return reverse %unique;
13543:     }
13544: 
13545:     sub get_servers {
13546: 	&load_hosts_tab() if (!$loaded);
13547: 
13548: 	my ($domain,$type) = @_;
13549: 	my %possible_hosts = ($type eq 'library') ? %libserv
13550: 	                                          : %hostname;
13551: 	my %result;
13552: 	if (ref($domain) eq 'ARRAY') {
13553: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13554: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13555: 		    $result{$host} = $hostname;
13556: 		}
13557: 	    }
13558: 	} else {
13559: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13560: 		if ($hostdom{$host} eq $domain) {
13561: 		    $result{$host} = $hostname;
13562: 		}
13563: 	    }
13564: 	}
13565: 	return %result;
13566:     }
13567: 
13568:     sub get_unique_servers {
13569:         my %unique = reverse &get_servers(@_);
13570: 	return reverse %unique;
13571:     }
13572: 
13573:     sub host_domain {
13574: 	&load_hosts_tab() if (!$loaded);
13575: 
13576: 	my ($lonid) = @_;
13577: 	return $hostdom{$lonid};
13578:     }
13579: 
13580:     sub all_domains {
13581: 	&load_hosts_tab() if (!$loaded);
13582: 
13583: 	my %seen;
13584: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13585: 	return @uniq;
13586:     }
13587: 
13588:     sub internet_dom {
13589:         &load_hosts_tab() if (!$loaded);
13590: 
13591:         my ($lonid) = @_;
13592:         return $internetdom{$lonid};
13593:     }
13594: 
13595:     sub is_LC_dns {
13596:         &load_hosts_tab() if (!$loaded);
13597: 
13598:         my ($hostname) = @_;
13599:         return exists($LC_dns_serv{$hostname});
13600:     }
13601: 
13602: }
13603: 
13604: { 
13605:     my %iphost;
13606:     my %name_to_ip;
13607:     my %lonid_to_ip;
13608: 
13609:     sub get_hosts_from_ip {
13610: 	my ($ip) = @_;
13611: 	my %iphosts = &get_iphost();
13612: 	if (ref($iphosts{$ip})) {
13613: 	    return @{$iphosts{$ip}};
13614: 	}
13615: 	return;
13616:     }
13617:     
13618:     sub reset_hosts_ip_info {
13619: 	undef(%iphost);
13620: 	undef(%name_to_ip);
13621: 	undef(%lonid_to_ip);
13622:     }
13623: 
13624:     sub get_host_ip {
13625: 	my ($lonid) = @_;
13626: 	if (exists($lonid_to_ip{$lonid})) {
13627: 	    return $lonid_to_ip{$lonid};
13628: 	}
13629: 	my $name=&hostname($lonid);
13630:    	my $ip = gethostbyname($name);
13631: 	return if (!$ip || length($ip) ne 4);
13632: 	$ip=inet_ntoa($ip);
13633: 	$name_to_ip{$name}   = $ip;
13634: 	$lonid_to_ip{$lonid} = $ip;
13635: 	return $ip;
13636:     }
13637:     
13638:     sub get_iphost {
13639: 	my ($ignore_cache,$nocache) = @_;
13640: 
13641: 	if (!$ignore_cache) {
13642: 	    if (%iphost) {
13643: 		return %iphost;
13644: 	    }
13645: 	    my ($ip_info,$cached)=
13646: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13647: 	    if ($cached) {
13648: 		%iphost      = %{$ip_info->[0]};
13649: 		%name_to_ip  = %{$ip_info->[1]};
13650: 		%lonid_to_ip = %{$ip_info->[2]};
13651: 		return %iphost;
13652: 	    }
13653: 	}
13654: 
13655: 	# get yesterday's info for fallback
13656: 	my %old_name_to_ip;
13657: 	my ($ip_info,$cached)=
13658: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13659: 	if ($cached) {
13660: 	    %old_name_to_ip = %{$ip_info->[1]};
13661: 	}
13662: 
13663: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13664: 	foreach my $name (keys(%name_to_host)) {
13665: 	    my $ip;
13666: 	    if (!exists($name_to_ip{$name})) {
13667: 		$ip = gethostbyname($name);
13668: 		if (!$ip || length($ip) ne 4) {
13669: 		    if (defined($old_name_to_ip{$name})) {
13670: 			$ip = $old_name_to_ip{$name};
13671: 			&logthis("Can't find $name defaulting to old $ip");
13672: 		    } else {
13673: 			&logthis("Name $name no IP found");
13674: 			next;
13675: 		    }
13676: 		} else {
13677: 		    $ip=inet_ntoa($ip);
13678: 		}
13679: 		$name_to_ip{$name} = $ip;
13680: 	    } else {
13681: 		$ip = $name_to_ip{$name};
13682: 	    }
13683: 	    foreach my $id (@{ $name_to_host{$name} }) {
13684: 		$lonid_to_ip{$id} = $ip;
13685: 	    }
13686: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13687: 	}
13688:         unless ($nocache) {
13689: 	    &do_cache_new('iphost','iphost',
13690: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13691: 		          48*60*60);
13692:         }
13693: 
13694: 	return %iphost;
13695:     }
13696: 
13697:     #
13698:     #  Given a DNS returns the loncapa host name for that DNS 
13699:     # 
13700:     sub host_from_dns {
13701:         my ($dns) = @_;
13702:         my @hosts;
13703:         my $ip;
13704: 
13705:         if (exists($name_to_ip{$dns})) {
13706:             $ip = $name_to_ip{$dns};
13707:         }
13708:         if (!$ip) {
13709:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13710:             if (length($ip) == 4) { 
13711: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13712:             }
13713:         }
13714:         if ($ip) {
13715: 	    @hosts = get_hosts_from_ip($ip);
13716: 	    return $hosts[0];
13717:         }
13718:         return undef;
13719:     }
13720: 
13721:     sub get_internet_names {
13722:         my ($lonid) = @_;
13723:         return if ($lonid eq '');
13724:         my ($idnref,$cached)=
13725:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
13726:         if ($cached) {
13727:             return $idnref;
13728:         }
13729:         my $ip = &get_host_ip($lonid);
13730:         my @hosts = &get_hosts_from_ip($ip);
13731:         my %iphost = &get_iphost();
13732:         my (@idns,%seen);
13733:         foreach my $id (@hosts) {
13734:             my $dom = &host_domain($id);
13735:             my $prim_id = &domain($dom,'primary');
13736:             my $prim_ip = &get_host_ip($prim_id);
13737:             next if ($seen{$prim_ip});
13738:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13739:                 foreach my $id (@{$iphost{$prim_ip}}) {
13740:                     my $intdom = &internet_dom($id);
13741:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
13742:                         push(@idns,$intdom);
13743:                     }
13744:                 }
13745:             }
13746:             $seen{$prim_ip} = 1;
13747:         }
13748:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13749:     }
13750: 
13751: }
13752: 
13753: sub all_loncaparevs {
13754:     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);
13755: }
13756: 
13757: # ---------------------------------------------------------- Read loncaparev table
13758: {
13759:     sub load_loncaparevs { 
13760:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13761:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13762:                 while (my $configline=<$config>) {
13763:                     chomp($configline);
13764:                     my ($hostid,$loncaparev)=split(/:/,$configline);
13765:                     $loncaparevs{$hostid}=$loncaparev;
13766:                 }
13767:                 close($config);
13768:             }
13769:         }
13770:     }
13771: }
13772: 
13773: # ---------------------------------------------------------- Read serverhostID table
13774: {
13775:     sub load_serverhomeIDs {
13776:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13777:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13778:                 while (my $configline=<$config>) {
13779:                     chomp($configline);
13780:                     my ($name,$id)=split(/:/,$configline);
13781:                     $serverhomeIDs{$name}=$id;
13782:                 }
13783:                 close($config);
13784:             }
13785:         }
13786:     }
13787: }
13788: 
13789: 
13790: BEGIN {
13791: 
13792: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13793:     unless ($readit) {
13794: {
13795:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13796:     %perlvar = (%perlvar,%{$configvars});
13797: }
13798: 
13799: 
13800: # ------------------------------------------------------ Read spare server file
13801: {
13802:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
13803: 
13804:     while (my $configline=<$config>) {
13805:        chomp($configline);
13806:        if ($configline) {
13807: 	   my ($host,$type) = split(':',$configline,2);
13808: 	   if (!defined($type) || $type eq '') { $type = 'default' };
13809: 	   push(@{ $spareid{$type} }, $host);
13810:        }
13811:     }
13812:     close($config);
13813: }
13814: # ------------------------------------------------------------ Read permissions
13815: {
13816:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
13817: 
13818:     while (my $configline=<$config>) {
13819: 	chomp($configline);
13820: 	if ($configline) {
13821: 	    my ($role,$perm)=split(/ /,$configline);
13822: 	    if ($perm ne '') { $pr{$role}=$perm; }
13823: 	}
13824:     }
13825:     close($config);
13826: }
13827: 
13828: # -------------------------------------------- Read plain texts for permissions
13829: {
13830:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
13831: 
13832:     while (my $configline=<$config>) {
13833: 	chomp($configline);
13834: 	if ($configline) {
13835: 	    my ($short,@plain)=split(/:/,$configline);
13836:             %{$prp{$short}} = ();
13837: 	    if (@plain > 0) {
13838:                 $prp{$short}{'std'} = $plain[0];
13839:                 for (my $i=1; $i<@plain; $i++) {
13840:                     $prp{$short}{'alt'.$i} = $plain[$i];  
13841:                 }
13842:             }
13843: 	}
13844:     }
13845:     close($config);
13846: }
13847: 
13848: # ---------------------------------------------------------- Read package table
13849: {
13850:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
13851: 
13852:     while (my $configline=<$config>) {
13853: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13854: 	chomp($configline);
13855: 	my ($short,$plain)=split(/:/,$configline);
13856: 	my ($pack,$name)=split(/\&/,$short);
13857: 	if ($plain ne '') {
13858: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
13859: 	    $packagetab{$short}=$plain; 
13860: 	}
13861:     }
13862:     close($config);
13863: }
13864: 
13865: # ---------------------------------------------------------- Read loncaparev table
13866: 
13867: &load_loncaparevs();
13868: 
13869: # ---------------------------------------------------------- Read serverhostID table
13870: 
13871: &load_serverhomeIDs();
13872: 
13873: # ---------------------------------------------------------- Read releaseslist XML
13874: {
13875:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13876:     if (-e $file) {
13877:         my $parser = HTML::LCParser->new($file);
13878:         while (my $token = $parser->get_token()) {
13879:             if ($token->[0] eq 'S') {
13880:                 my $item = $token->[1];
13881:                 my $name = $token->[2]{'name'};
13882:                 my $value = $token->[2]{'value'};
13883:                 my $valuematch = $token->[2]{'valuematch'};
13884:                 my $namematch = $token->[2]{'namematch'};
13885:                 if ($item eq 'parameter') {
13886:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13887:                         my $release = $parser->get_text();
13888:                         $release =~ s/(^\s*|\s*$ )//gx;
13889:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13890:                     }
13891:                 } elsif ($item ne '' && $name ne '') {
13892:                     my $release = $parser->get_text();
13893:                     $release =~ s/(^\s*|\s*$ )//gx;
13894:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
13895:                 }
13896:             }
13897:         }
13898:     }
13899: }
13900: 
13901: # ---------------------------------------------------------- Read managers table
13902: {
13903:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13904:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13905:             while (my $configline=<$config>) {
13906:                 chomp($configline);
13907:                 next if ($configline =~ /^\#/);
13908:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13909:                     $managerstab{$configline} = 1;
13910:                 }
13911:             }
13912:             close($config);
13913:         }
13914:     }
13915: }
13916: 
13917: # ------------- set up temporary directory
13918: {
13919:     $tmpdir = LONCAPA::tempdir();
13920: 
13921: }
13922: 
13923: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
13924: 				'compress_threshold'=> 20_000,
13925:  			        });
13926: 
13927: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13928: $dumpcount=0;
13929: $locknum=0;
13930: 
13931: &logtouch();
13932: &logthis('<font color="yellow">INFO: Read configuration</font>');
13933: $readit=1;
13934:     {
13935: 	use integer;
13936: 	my $test=(2**32)+1;
13937: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13938: 	&logthis(" Detected 64bit platform ($_64bit)");
13939:     }
13940: }
13941: }
13942: 
13943: 1;
13944: __END__
13945: 
13946: =pod
13947: 
13948: =head1 NAME
13949: 
13950: Apache::lonnet - Subroutines to ask questions about things in the network.
13951: 
13952: =head1 SYNOPSIS
13953: 
13954: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13955: 
13956:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13957: 
13958: Common parameters:
13959: 
13960: =over 4
13961: 
13962: =item *
13963: 
13964: $uname : an internal username (if $cname expecting a course Id specifically)
13965: 
13966: =item *
13967: 
13968: $udom : a domain (if $cdom expecting a course's domain specifically)
13969: 
13970: =item *
13971: 
13972: $symb : a resource instance identifier
13973: 
13974: =item *
13975: 
13976: $namespace : the name of a .db file that contains the data needed or
13977: being set.
13978: 
13979: =back
13980: 
13981: =head1 OVERVIEW
13982: 
13983: lonnet provides subroutines which interact with the
13984: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13985: about classes, users, and resources.
13986: 
13987: For many of these objects you can also use this to store data about
13988: them or modify them in various ways.
13989: 
13990: =head2 Symbs
13991: 
13992: To identify a specific instance of a resource, LON-CAPA uses symbols
13993: or "symbs"X<symb>. These identifiers are built from the URL of the
13994: map, the resource number of the resource in the map, and the URL of
13995: the resource itself. The latter is somewhat redundant, but might help
13996: if maps change.
13997: 
13998: An example is
13999: 
14000:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14001: 
14002: The respective map entry is
14003: 
14004:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14005:   title="Problem 2">
14006:  </resource>
14007: 
14008: Symbs are used by the random number generator, as well as to store and
14009: restore data specific to a certain instance of for example a problem.
14010: 
14011: =head2 Storing And Retrieving Data
14012: 
14013: X<store()>X<cstore()>X<restore()>Three of the most important functions
14014: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14015: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14016: is is the non-critical message twin of cstore. These functions are for
14017: handlers to store a perl hash to a user's permanent data space in an
14018: easy manner, and to retrieve it again on another call. It is expected
14019: that a handler would use this once at the beginning to retrieve data,
14020: and then again once at the end to send only the new data back.
14021: 
14022: The data is stored in the user's data directory on the user's
14023: homeserver under the ID of the course.
14024: 
14025: The hash that is returned by restore will have all of the previous
14026: value for all of the elements of the hash.
14027: 
14028: Example:
14029: 
14030:  #creating a hash
14031:  my %hash;
14032:  $hash{'foo'}='bar';
14033: 
14034:  #storing it
14035:  &Apache::lonnet::cstore(\%hash);
14036: 
14037:  #changing a value
14038:  $hash{'foo'}='notbar';
14039: 
14040:  #adding a new value
14041:  $hash{'bar'}='foo';
14042:  &Apache::lonnet::cstore(\%hash);
14043: 
14044:  #retrieving the hash
14045:  my %history=&Apache::lonnet::restore();
14046: 
14047:  #print the hash
14048:  foreach my $key (sort(keys(%history))) {
14049:    print("\%history{$key} = $history{$key}");
14050:  }
14051: 
14052: Will print out:
14053: 
14054:  %history{1:foo} = bar
14055:  %history{1:keys} = foo:timestamp
14056:  %history{1:timestamp} = 990455579
14057:  %history{2:bar} = foo
14058:  %history{2:foo} = notbar
14059:  %history{2:keys} = foo:bar:timestamp
14060:  %history{2:timestamp} = 990455580
14061:  %history{bar} = foo
14062:  %history{foo} = notbar
14063:  %history{timestamp} = 990455580
14064:  %history{version} = 2
14065: 
14066: Note that the special hash entries C<keys>, C<version> and
14067: C<timestamp> were added to the hash. C<version> will be equal to the
14068: total number of versions of the data that have been stored. The
14069: C<timestamp> attribute will be the UNIX time the hash was
14070: stored. C<keys> is available in every historical section to list which
14071: keys were added or changed at a specific historical revision of a
14072: hash.
14073: 
14074: B<Warning>: do not store the hash that restore returns directly. This
14075: will cause a mess since it will restore the historical keys as if the
14076: were new keys. I.E. 1:foo will become 1:1:foo etc.
14077: 
14078: Calling convention:
14079: 
14080:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14081:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14082: 
14083: For more detailed information, see lonnet specific documentation.
14084: 
14085: =head1 RETURN MESSAGES
14086: 
14087: =over 4
14088: 
14089: =item * B<con_lost>: unable to contact remote host
14090: 
14091: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14092: when the connection is brought back up
14093: 
14094: =item * B<con_failed>: unable to contact remote host and unable to save message
14095: for later delivery
14096: 
14097: =item * B<error:>: an error a occurred, a description of the error follows the :
14098: 
14099: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14100: that was requested
14101: 
14102: =back
14103: 
14104: =head1 PUBLIC SUBROUTINES
14105: 
14106: =head2 Session Environment Functions
14107: 
14108: =over 4
14109: 
14110: =item * 
14111: X<appenv()>
14112: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14113: the user envirnoment file, and will be restored for each access this
14114: user makes during this session, also modifies the %env for the current
14115: process. Optional rolesarrayref - if defined contains a reference to an array
14116: of roles which are exempt from the restriction on modifying user.role entries 
14117: in the user's environment.db and in %env.    
14118: 
14119: =item *
14120: X<delenv()>
14121: B<delenv($delthis,$regexp)>: removes all items from the session
14122: environment file that begin with $delthis. If the 
14123: optional second arg - $regexp - is true, $delthis is treated as a 
14124: regular expression, otherwise \Q$delthis\E is used. 
14125: The values are also deleted from the current processes %env.
14126: 
14127: =item * get_env_multiple($name) 
14128: 
14129: gets $name from the %env hash, it seemlessly handles the cases where multiple
14130: values may be defined and end up as an array ref.
14131: 
14132: returns an array of values
14133: 
14134: =back
14135: 
14136: =head2 User Information
14137: 
14138: =over 4
14139: 
14140: =item *
14141: X<queryauthenticate()>
14142: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14143: authentication scheme
14144: 
14145: =item *
14146: X<authenticate()>
14147: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14148: authenticate user from domain's lib servers (first use the current
14149: one). C<$upass> should be the users password.
14150: $checkdefauth is optional (value is 1 if a check should be made to
14151:    authenticate user using default authentication method, and allow
14152:    account creation if username does not have account in the domain).
14153: $clientcancheckhost is optional (value is 1 if checking whether the
14154:    server can host will occur on the client side in lonauth.pm).   
14155: 
14156: =item *
14157: X<homeserver()>
14158: B<homeserver($uname,$udom)>: find the server which has
14159: the user's directory and files (there must be only one), this caches
14160: the answer, and also caches if there is a borken connection.
14161: 
14162: =item *
14163: X<idget()>
14164: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14165: a list of student/employee IDs or clicker IDs
14166: (student/employee IDs are a unique resource in a domain, there must be 
14167: only 1 ID per username, and only 1 username per ID in a specific domain).
14168: clickerIDs are not necessarily unique, as students might share clickers.
14169: (returns hash: id=>name,id=>name)
14170: 
14171: =item *
14172: X<idrget()>
14173: B<idrget($udom,@unames)>: find the IDs behind a list of
14174: usernames (returns hash: name=>id,name=>id)
14175: 
14176: =item *
14177: X<idput()>
14178: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14179: names and associated student/employee IDs or clicker IDs.
14180: 
14181: =item *
14182: X<iddel()>
14183: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14184: student/employee ID or clicker ID username look-ups from domain.
14185: The homeserver ($uhome) and namespace ($namespace) are optional.
14186: If no $uhome is provided, it will be determined usig &homeserver()
14187: for each user.  If no $namespace is provided, the default is ids.
14188: 
14189: =item *
14190: X<updateclickers()>
14191: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14192: clicker ID-to-username look-ups in clickers.db on library server.
14193: Permitted actions are add or del (i.e., add or delete). The 
14194: clickers.db contains clickerID as keys (escaped), and each corresponding
14195: value is an escaped comma-separated list of usernames (for whom the
14196: library server is the homeserver), who registered that particular ID.
14197: If $critical is true, the update will be sent via &critical, otherwise
14198: &reply() will be used.
14199: 
14200: =item *
14201: X<rolesinit()>
14202: B<rolesinit($udom,$username)>: get user privileges.
14203: returns user role, first access and timer interval hashes
14204: 
14205: =item *
14206: X<privileged()>
14207: B<privileged($username,$domain)>: returns a true if user has a
14208: privileged and active role (i.e. su or dc), false otherwise.
14209: 
14210: =item *
14211: X<getsection()>
14212: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14213: course $cname, return section name/number or '' for "not in course"
14214: and '-1' for "no section"
14215: 
14216: =item *
14217: X<userenvironment()>
14218: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14219: passed in @what from the requested user's environment, returns a hash
14220: 
14221: =item * 
14222: X<userlog_query()>
14223: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14224: activity.log file. %filters defines filters applied when parsing the
14225: log file. These can be start or end timestamps, or the type of action
14226: - log to look for Login or Logout events, check for Checkin or
14227: Checkout, role for role selection. The response is in the form
14228: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14229: escaped strings of the action recorded in the activity.log file.
14230: 
14231: =back
14232: 
14233: =head2 User Roles
14234: 
14235: =over 4
14236: 
14237: =item *
14238: 
14239: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14240: returns codes for allowed actions.
14241: 
14242: The first argument is required, all others are optional.
14243: 
14244: $priv is the privilege being checked.
14245: $uri contains additional information about what is being checked for access (e.g.,
14246: URL, course ID etc.). 
14247: $symb is the unique resource instance identifier in a course; if needed,
14248: but not provided, it will be retrieved via a call to &symbread(). 
14249: $role is the role for which a priv is being checked (only used if priv is evb). 
14250: $clientip is the user's IP address (only used when checking for access to portfolio 
14251: files).
14252: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14253: prevents recursive calls to &allowed.
14254: 
14255:  F: full access
14256:  U,I,K: authentication modes (cxx only)
14257:  '': forbidden
14258:  1: user needs to choose course
14259:  2: browse allowed
14260:  A: passphrase authentication needed
14261:  B: access temporarily blocked because of a blocking event in a course.
14262: 
14263: =item *
14264: 
14265: constructaccess($url,$setpriv) : check for access to construction space URL
14266: 
14267: See if the owner domain and name in the URL match those in the
14268: expected environment.  If so, return three element list
14269: ($ownername,$ownerdomain,$ownerhome).
14270: 
14271: Otherwise return the null string.
14272: 
14273: If second argument 'setpriv' is true, it assigns the privileges,
14274: and returns the same three element list, unless the owner has
14275: blocked "ad hoc" Domain Coordinator access to the Author Space,
14276: in which case the null string is returned.
14277: 
14278: =item *
14279: 
14280: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14281: define a custom role rolename set privileges in format of lonTabs/roles.tab
14282: for system, domain, and course level. $uname and $udom are optional (current
14283: user's username and domain will be used when either of $uname or $udom are absent.
14284: 
14285: =item *
14286: 
14287: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14288: (rolesplain.tab); plain text explanation of a user role term.
14289: $type is Course (default) or Community.
14290: If $forcedefault evaluates to true, text returned will be default 
14291: text for $type. Otherwise, if this is a course, the text returned 
14292: will be a custom name for the role (if defined in the course's 
14293: environment).  If no custom name is defined the default is returned.
14294:    
14295: =item *
14296: 
14297: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14298: All arguments are optional. Returns a hash of a roles, either for
14299: co-author/assistant author roles for a user's Construction Space
14300: (default), or if $context is 'userroles', roles for the user himself,
14301: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14302: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14303: For each key, value is set to colon-separated start and end times for
14304: the role.  If no username and domain are specified, will default to
14305: current user/domain. Types, roles, and roledoms are references to arrays
14306: of role statuses (active, future or previous), roles 
14307: (e.g., cc,in, st etc.) and domains of the roles which can be used
14308: to restrict the list of roles reported. If no array ref is 
14309: provided for types, will default to return only active roles.
14310: 
14311: =item *
14312: 
14313: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14314: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14315: 
14316: Additional optional arguments are: $type (if role checking is to be restricted 
14317: to certain user status types -- previous (expired roles), active (currently
14318: available roles) or future (roles available in the future), and
14319: $hideprivileged -- if true will not report course roles for users who
14320: have active Domain Coordinator role in course's domain or in additional
14321: domains (specified in 'Domains to check for privileged users' in course
14322: environment -- set via:  Course Settings -> Classlists and staff listing).
14323: 
14324: =item *
14325: 
14326: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14327: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14328: $possdomains and $possroles are optional array refs -- to domains to check and
14329: roles to check.  If $possdomains is not specified, a dump will be done of the
14330: users' roles.db to check for a dc or su role in any domain. This can be
14331: time consuming if &privileged is called repeatedly (e.g., when displaying a
14332: classlist), so in such cases, supplying a $possdomains array is preferred, as
14333: this then allows &privileged_by_domain() to be used, which caches the identity
14334: of privileged users, eliminating the need for repeated calls to &dump().
14335: 
14336: =item *
14337: 
14338: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14339: where the outer hash keys are domains specified in the $possdomains array ref,
14340: next inner hash keys are privileged roles specified in the $roles array ref,
14341: and the innermost hash contains key = value pairs for username:domain = end:start
14342: for active or future "privileged" users with that role in that domain. To avoid
14343: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14344: innerhash are cached using priv_$role and $dom as the identifiers.
14345: 
14346: =back
14347: 
14348: =head2 User Modification
14349: 
14350: =over 4
14351: 
14352: =item *
14353: 
14354: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14355: user for the level given by URL.  Optional start and end dates (leave empty
14356: string or zero for "no date")
14357: 
14358: =item *
14359: 
14360: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14361: change a users, password, possible return values are: ok,
14362: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14363: refused
14364: 
14365: =item *
14366: 
14367: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14368: 
14369: =item *
14370: 
14371: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14372:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14373: 
14374: will update user information (firstname,middlename,lastname,generation,
14375: permanentemail), and if forceid is true, student/employee ID also.
14376: A user's institutional affiliation(s) can also be updated.
14377: User information fields will not be overwritten with empty entries 
14378: unless the field is included in the $candelete array reference.
14379: This array is included when a single user is modified via "Manage Users",
14380: or when Autoupdate.pl is run by cron in a domain.
14381: 
14382: =item *
14383: 
14384: modifystudent
14385: 
14386: modify a student's enrollment and identification information.
14387: The course id is resolved based on the current user's environment.  
14388: This means the invoking user must be a course coordinator or otherwise
14389: associated with a course.
14390: 
14391: This call is essentially a wrapper for lonnet::modifyuser and
14392: lonnet::modify_student_enrollment
14393: 
14394: Inputs: 
14395: 
14396: =over 4
14397: 
14398: =item B<$udom> Student's loncapa domain
14399: 
14400: =item B<$uname> Student's loncapa login name
14401: 
14402: =item B<$uid> Student/Employee ID
14403: 
14404: =item B<$umode> Student's authentication mode
14405: 
14406: =item B<$upass> Student's password
14407: 
14408: =item B<$first> Student's first name
14409: 
14410: =item B<$middle> Student's middle name
14411: 
14412: =item B<$last> Student's last name
14413: 
14414: =item B<$gene> Student's generation
14415: 
14416: =item B<$usec> Student's section in course
14417: 
14418: =item B<$end> Unix time of the roles expiration
14419: 
14420: =item B<$start> Unix time of the roles start date
14421: 
14422: =item B<$forceid> If defined, allow $uid to be changed
14423: 
14424: =item B<$desiredhome> server to use as home server for student
14425: 
14426: =item B<$email> Student's permanent e-mail address
14427: 
14428: =item B<$type> Type of enrollment (auto or manual)
14429: 
14430: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14431: 
14432: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14433: 
14434: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14435: 
14436: =item B<$context> role change context (shown in User Management Logs display in a course)
14437: 
14438: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14439: 
14440: =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.
14441: 
14442: =back
14443: 
14444: =item *
14445: 
14446: modify_student_enrollment
14447: 
14448: Change a student's enrollment status in a class.  The environment variable
14449: 'role.request.course' must be defined for this function to proceed.
14450: 
14451: Inputs:
14452: 
14453: =over 4
14454: 
14455: =item $udom, student's domain
14456: 
14457: =item $uname, student's name
14458: 
14459: =item $uid, student's user id
14460: 
14461: =item $first, student's first name
14462: 
14463: =item $middle
14464: 
14465: =item $last
14466: 
14467: =item $gene
14468: 
14469: =item $usec
14470: 
14471: =item $end
14472: 
14473: =item $start
14474: 
14475: =item $type
14476: 
14477: =item $locktype
14478: 
14479: =item $cid
14480: 
14481: =item $selfenroll
14482: 
14483: =item $context
14484: 
14485: =item $credits, number of credits student will earn from this class
14486: 
14487: =item $instsec, institutional course section code for student
14488: 
14489: =back
14490: 
14491: 
14492: =item *
14493: 
14494: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14495: custom role; give a custom role to a user for the level given by URL.  Specify
14496: name and domain of role author, and role name
14497: 
14498: =item *
14499: 
14500: revokerole($udom,$uname,$url,$role) : revoke a role for url
14501: 
14502: =item *
14503: 
14504: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14505: 
14506: =back
14507: 
14508: =head2 Course Infomation
14509: 
14510: =over 4
14511: 
14512: =item *
14513: 
14514: coursedescription($courseid,$options) : returns a hash of information about the
14515: specified course id, including all environment settings for the
14516: course, the description of the course will be in the hash under the
14517: key 'description'
14518: 
14519: $options is an optional parameter that if supplied is a hash reference that controls
14520: what how this function works.  It has the following key/values:
14521: 
14522: =over 4
14523: 
14524: =item freshen_cache
14525: 
14526: If defined, and the environment cache for the course is valid, it is 
14527: returned in the returned hash.
14528: 
14529: =item one_time
14530: 
14531: If defined, the last cache time is set to _now_
14532: 
14533: =item user
14534: 
14535: If defined, the supplied username is used instead of the current user.
14536: 
14537: 
14538: =back
14539: 
14540: =item *
14541: 
14542: resdata($name,$domain,$type,@which) : request for current parameter
14543: setting for a specific $type, where $type is either 'course' or 'user',
14544: @what should be a list of parameters to ask about. This routine caches
14545: answers for 10 minutes.
14546: 
14547: =item *
14548: 
14549: get_courseresdata($courseid, $domain) : dump the entire course resource
14550: data base, returning a hash that is keyed by the resource name and has
14551: values that are the resource value.  I believe that the timestamps and
14552: versions are also returned.
14553: 
14554: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14555: supplemental content area. This routine caches the number of files for 
14556: 10 minutes.
14557: 
14558: =back
14559: 
14560: =head2 Course Modification
14561: 
14562: =over 4
14563: 
14564: =item *
14565: 
14566: writecoursepref($courseid,%prefs) : write preferences (environment
14567: database) for a course
14568: 
14569: =item *
14570: 
14571: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14572: 
14573: =item *
14574: 
14575: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14576: 
14577: =item *
14578: 
14579: is_course($courseid), is_course($cdom, $cnum)
14580: 
14581: Accepts either a combined $courseid (in the form of domain_courseid) or the
14582: two component version $cdom, $cnum. It checks if the specified course exists.
14583: 
14584: Returns:
14585:     undef if the course doesn't exist, otherwise
14586:     in scalar context the combined courseid.
14587:     in list context the two components of the course identifier, domain and 
14588:     courseid.    
14589: 
14590: =back
14591: 
14592: =head2 Resource Subroutines
14593: 
14594: =over 4
14595: 
14596: =item *
14597: 
14598: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14599: 
14600: =item *
14601: 
14602: repcopy($filename) : subscribes to the requested file, and attempts to
14603: replicate from the owning library server, Might return
14604: 'unavailable', 'not_found', 'forbidden', 'ok', or
14605: 'bad_request', also attempts to grab the metadata for the
14606: resource. Expects the local filesystem pathname
14607: (/home/httpd/html/res/....)
14608: 
14609: =back
14610: 
14611: =head2 Resource Information
14612: 
14613: =over 4
14614: 
14615: =item *
14616: 
14617: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14618: and returns the value of a variety of different possible values,
14619: $varname should be a request string, and the other parameters can be
14620: used to specify who and what one is asking about. Ordinarily, $cid 
14621: does not need to be specified, as it is retrived from 
14622: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14623: within lonuserstate::loadmap() when initializing a course, before
14624: $env{'request.course.id'} has been set, so it needs to be provided
14625: in that one case.
14626: 
14627: Possible values for $varname are environment.lastname (or other item
14628: from the envirnment hash), user.name (or someother aspect about the
14629: user), resource.0.maxtries (or some other part and parameter of a
14630: resource)
14631: 
14632: =item *
14633: 
14634: directcondval($number) : get current value of a condition; reads from a state
14635: string
14636: 
14637: =item *
14638: 
14639: condval($condidx) : value of condition index based on state
14640: 
14641: =item *
14642: 
14643: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14644: resource's metadata, $what should be either a specific key, or either
14645: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14646: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14647: 
14648: this function automatically caches all requests
14649: 
14650: =item *
14651: 
14652: metadata_query($query,$custom,$customshow) : make a metadata query against the
14653: network of library servers; returns file handle of where SQL and regex results
14654: will be stored for query
14655: 
14656: =item *
14657: 
14658: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
14659: return symbolic list entry (all arguments optional). 
14660: 
14661: Args: filename is the filename (including path) for the file for which a symb 
14662: is required; donotrecurse, if true will prevent calls to allowed() being made 
14663: to check access status if more than one resource was found in the bighash 
14664: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
14665: a randompick); ignorecachednull, if true will prevent a symb of '' being 
14666: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14667: cause possible symbs to be checked to determine if they are subject to content
14668: blocking, if so they will not be included as possible symbs; possibles is a
14669: ref to a hash, which, as a side effect, will be populated with all possible 
14670: symbs (content blocking not tested).
14671:  
14672: returns the data handle
14673: 
14674: =item *
14675: 
14676: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14677: and is a possible symb for the URL in $thisfn, and if is an encrypted
14678: resource that the user accessed using /enc/ returns a 1 on success, 0
14679: on failure, user must be in a course, as it assumes the existence of
14680: the course initial hash, and uses $env('request.course.id'}.  The third
14681: arg is an optional reference to a scalar.  If this arg is passed in the 
14682: call to symbverify, it will be set to 1 if the symb has been set to be 
14683: encrypted; otherwise it will be null.  
14684: 
14685: =item *
14686: 
14687: symbclean($symb) : removes versions numbers from a symb, returns the
14688: cleaned symb
14689: 
14690: =item *
14691: 
14692: is_on_map($uri) : checks if the $uri is somewhere on the current
14693: course map, user must be in a course for it to work.
14694: 
14695: =item *
14696: 
14697: numval($salt) : return random seed value (addend for rndseed)
14698: 
14699: =item *
14700: 
14701: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14702: a random seed, all arguments are optional, if they aren't sent it uses the
14703: environment to derive them. Note: if symb isn't sent and it can't get one
14704: from &symbread it will use the current time as its return value
14705: 
14706: =item *
14707: 
14708: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14709: unfakeable, receipt
14710: 
14711: =item *
14712: 
14713: receipt() : API to ireceipt working off of env values; given out to users
14714: 
14715: =item *
14716: 
14717: countacc($url) : count the number of accesses to a given URL
14718: 
14719: =item *
14720: 
14721: 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
14722: 
14723: =item *
14724: 
14725: 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)
14726: 
14727: =item *
14728: 
14729: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14730: 
14731: =item *
14732: 
14733: devalidate($symb) : devalidate temporary spreadsheet calculations,
14734: forcing spreadsheet to reevaluate the resource scores next time.
14735: 
14736: =item * 
14737: 
14738: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14739: when viewing in course context.
14740: 
14741:  input: six args -- filename (decluttered), course number, course domain,
14742:                     url, symb (if registered) and group (if this is a 
14743:                     group item -- e.g., bulletin board, group page etc.).
14744: 
14745:  output: array of five scalars --
14746:          $cfile -- url for file editing if editable on current server
14747:          $home -- homeserver of resource (i.e., for author if published,
14748:                                           or course if uploaded.).
14749:          $switchserver --  1 if server switch will be needed.
14750:          $forceedit -- 1 if icon/link should be to go to edit mode 
14751:          $forceview -- 1 if icon/link should be to go to view mode
14752: 
14753: =item *
14754: 
14755: is_course_upload($file,$cnum,$cdom)
14756: 
14757: Used in course context to determine if current file was uploaded to 
14758: the course (i.e., would be found in /userfiles/docs on the course's 
14759: homeserver.
14760: 
14761:   input: 3 args -- filename (decluttered), course number and course domain.
14762:   output: boolean -- 1 if file was uploaded.
14763: 
14764: =back
14765: 
14766: =head2 Storing/Retreiving Data
14767: 
14768: =over 4
14769: 
14770: =item *
14771: 
14772: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14773: permanently for this url; hashref needs to be given and should be a \%hashname;
14774: the remaining args aren't required and if they aren't passed or are '' they will
14775: be derived from the env (with the exception of $laststore, which is an 
14776: optional arg used when a user's submission is stored in grading).
14777: $laststore is $version=$timestamp, where $version is the most recent version
14778: number retrieved for the corresponding $symb in the $namespace db file, and
14779: $timestamp is the timestamp for that transaction (UNIX time).
14780: $laststore is currently only passed when cstore() is called by 
14781: structuretags::finalize_storage().
14782: 
14783: =item *
14784: 
14785: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14786: but uses critical subroutine
14787: 
14788: =item *
14789: 
14790: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14791: all args are optional
14792: 
14793: =item *
14794: 
14795: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
14796: dumps the complete (or key matching regexp) namespace into a hash
14797: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14798: normally &store()ed into
14799: 
14800: $range should be either an integer '100' (give me the first 100
14801:                                            matching records)
14802:               or be  two integers sperated by a - with no spaces
14803:                  '30-50' (give me the 30th through the 50th matching
14804:                           records)
14805: 
14806: 
14807: =item *
14808: 
14809: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14810: replaces a &store() version of data with a replacement set of data
14811: for a particular resource in a namespace passed in the $storehash hash 
14812: reference. If $tolog is true, the transaction is logged in the courselog
14813: with an action=PUTSTORE.
14814: 
14815: =item *
14816: 
14817: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14818: works very similar to store/cstore, but all data is stored in a
14819: temporary location and can be reset using tmpreset, $storehash should
14820: be a hash reference, returns nothing on success
14821: 
14822: =item *
14823: 
14824: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14825: similar to restore, but all data is stored in a temporary location and
14826: can be reset using tmpreset. Returns a hash of values on success,
14827: error string otherwise.
14828: 
14829: =item *
14830: 
14831: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14832: deltes all keys for $symb form the temporary storage hash.
14833: 
14834: =item *
14835: 
14836: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14837: reference filled in from namesp ($udom and $uname are optional)
14838: 
14839: =item *
14840: 
14841: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14842: namesp ($udom and $uname are optional)
14843: 
14844: =item *
14845: 
14846: dump($namespace,$udom,$uname,$regexp,$range) : 
14847: dumps the complete (or key matching regexp) namespace into a hash
14848: ($udom, $uname, $regexp, $range are optional)
14849: 
14850: $range should be either an integer '100' (give me the first 100
14851:                                            matching records)
14852:               or be  two integers sperated by a - with no spaces
14853:                  '30-50' (give me the 30th through the 50th matching
14854:                           records)
14855: =item *
14856: 
14857: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14858: $store can be a scalar, an array reference, or if the amount to be 
14859: incremented is > 1, a hash reference.
14860: 
14861: ($udom and $uname are optional)
14862: 
14863: =item *
14864: 
14865: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14866: ($udom and $uname are optional)
14867: 
14868: =item *
14869: 
14870: cput($namespace,$storehash,$udom,$uname) : critical put
14871: ($udom and $uname are optional)
14872: 
14873: =item *
14874: 
14875: newput($namespace,$storehash,$udom,$uname) :
14876: 
14877: Attempts to store the items in the $storehash, but only if they don't
14878: currently exist, if this succeeds you can be certain that you have 
14879: successfully created a new key value pair in the $namespace db.
14880: 
14881: 
14882: Args:
14883:  $namespace: name of database to store values to
14884:  $storehash: hashref to store to the db
14885:  $udom: (optional) domain of user containing the db
14886:  $uname: (optional) name of user caontaining the db
14887: 
14888: Returns:
14889:  'ok' -> succeeded in storing all keys of $storehash
14890:  'key_exists: <key>' -> failed to anything out of $storehash, as at
14891:                         least <key> already existed in the db (other
14892:                         requested keys may also already exist)
14893:  'error: <msg>' -> unable to tie the DB or other error occurred
14894:  'con_lost' -> unable to contact request server
14895:  'refused' -> action was not allowed by remote machine
14896: 
14897: 
14898: =item *
14899: 
14900: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14901: reference filled in from namesp (encrypts the return communication)
14902: ($udom and $uname are optional)
14903: 
14904: =item *
14905: 
14906: log($udom,$name,$home,$message) : write to permanent log for user; use
14907: critical subroutine
14908: 
14909: =item *
14910: 
14911: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14912: array reference filled in from namespace found in domain level on either
14913: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14914: 
14915: =item *
14916: 
14917: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
14918: domain level either on specified domain server ($uhome) or primary domain 
14919: server ($udom and $uhome are optional)
14920: 
14921: =item * 
14922: 
14923: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
14924: for: authentication, language, quotas, timezone, date locale, and portal URL in
14925: the target domain.
14926: 
14927: May also include additional key => value pairs for the following groups:
14928: 
14929: =over
14930: 
14931: =item
14932: disk quotas (MB allocated by default to portfolios and authoring spaces).
14933: 
14934: =over
14935: 
14936: =item defaultquota, authorquota
14937: 
14938: =back
14939: 
14940: =item
14941: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14942: portfolio for users).
14943: 
14944: =over
14945: 
14946: =item
14947: aboutme, blog, webdav, portfolio
14948: 
14949: =back
14950: 
14951: =item
14952: requestcourses: ability to request courses, and how requests are processed.
14953: 
14954: =over
14955: 
14956: =item
14957: official, unofficial, community, textbook, placement
14958: 
14959: =back
14960: 
14961: =item
14962: inststatus: types of institutional affiliation, and order in which they are displayed.
14963: 
14964: =over
14965: 
14966: =item
14967: inststatustypes, inststatusorder, inststatusguest
14968: 
14969: =back
14970: 
14971: =item
14972: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14973: for course's uploaded content.
14974: 
14975: =over
14976: 
14977: =item
14978: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
14979: communityquota, textbookquota, placementquota
14980: 
14981: =back
14982: 
14983: =item
14984: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14985: on your servers.
14986: 
14987: =over
14988: 
14989: =item 
14990: remotesessions, hostedsessions
14991: 
14992: =back
14993: 
14994: =back
14995: 
14996: In cases where a domain coordinator has never used the "Set Domain Configuration"
14997: utility to create a configuration.db file on a domain's primary library server 
14998: only the following domain defaults: auth_def, auth_arg_def, lang_def
14999: -- corresponding values are authentication type (internal, krb4, krb5,
15000: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15001: will be available. Values are retrieved from cache (if current), unless the
15002: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15003: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15004: 
15005: Typical usage:
15006: 
15007: %domdefaults = &get_domain_defaults($target_domain);
15008: 
15009: =back
15010: 
15011: =head2 Network Status Functions
15012: 
15013: =over 4
15014: 
15015: =item *
15016: 
15017: dirlist() : return directory list based on URI (first arg).
15018: 
15019: Inputs: 1 required, 5 optional.
15020: 
15021: =over
15022: 
15023: =item 
15024: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15025: 
15026: =item
15027: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15028: 
15029: =item
15030: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15031: 
15032: =item
15033: $getpropath - boolean: 1 if prepend path using &propath(). 
15034: 
15035: =item
15036: $getuserdir - boolean: 1 if prepend path for "userfiles".
15037: 
15038: =item 
15039: $alternateRoot - path to prepend in place of path from $uri.
15040: 
15041: =back
15042: 
15043: Returns: Array of up to two items.
15044: 
15045: =over
15046: 
15047: a reference to an array of files/subdirectories
15048: 
15049: =over
15050: 
15051: Each element in the array of files/subdirectories is a & separated list of
15052: item name and the result of running stat on the item.  If dirlist was requested
15053: for a file instead of a directory, the item name will be ''. For a directory 
15054: listing, if the item is a metadata file, the element will end &N&M 
15055: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15056: default copyright set (1).  
15057: 
15058: =back
15059: 
15060: a scalar containing error condition (if encountered).
15061: 
15062: =over
15063: 
15064: =item 
15065: no_host (no homeserver identified for $username:$domain).
15066: 
15067: =item 
15068: no_such_host (server contacted for listing not identified as valid host).
15069: 
15070: =item 
15071: con_lost (connection to remote server failed).
15072: 
15073: =item 
15074: refused (invalid $username:$domain received on lond side).
15075: 
15076: =item 
15077: no_such_dir (directory at specified path on lond side does not exist). 
15078: 
15079: =item 
15080: empty (directory at specified path on lond side is empty).
15081: 
15082: =over
15083: 
15084: This is currently not encountered because the &ls3, &ls2, 
15085: &ls (_handler) routines on the lond side do not filter out
15086: . and .. from a directory listing. 
15087: 
15088: =back
15089: 
15090: =back
15091: 
15092: =back
15093: 
15094: =item *
15095: 
15096: spareserver() : find server with least workload from spare.tab
15097: 
15098: 
15099: =item *
15100: 
15101: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15102: if there is no corresponding loncapa host.
15103: 
15104: =back
15105: 
15106: 
15107: =head2 Apache Request
15108: 
15109: =over 4
15110: 
15111: =item *
15112: 
15113: ssi($url,%hash) : server side include, does a complete request cycle on url to
15114: localhost, posts hash
15115: 
15116: =back
15117: 
15118: =head2 Data to String to Data
15119: 
15120: =over 4
15121: 
15122: =item *
15123: 
15124: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15125: and '&' separators, supports elements that are arrayrefs and hashrefs
15126: 
15127: =item *
15128: 
15129: hashref2str($hashref) : convert a hashref into a string complete with
15130: escaping and '=' and '&' separators, supports elements that are
15131: arrayrefs and hashrefs
15132: 
15133: =item *
15134: 
15135: arrayref2str($arrayref) : convert an arrayref into a string complete
15136: with escaping and '&' separators, supports elements that are arrayrefs
15137: and hashrefs
15138: 
15139: =item *
15140: 
15141: str2hash($string) : convert string to hash using unescaping and
15142: splitting on '=' and '&', supports elements that are arrayrefs and
15143: hashrefs
15144: 
15145: =item *
15146: 
15147: str2array($string) : convert string to hash using unescaping and
15148: splitting on '&', supports elements that are arrayrefs and hashrefs
15149: 
15150: =back
15151: 
15152: =head2 Logging Routines
15153: 
15154: 
15155: These routines allow one to make log messages in the lonnet.log and
15156: lonnet.perm logfiles.
15157: 
15158: =over 4
15159: 
15160: =item *
15161: 
15162: logtouch() : make sure the logfile, lonnet.log, exists
15163: 
15164: =item *
15165: 
15166: logthis() : append message to the normal lonnet.log file, it gets
15167: preiodically rolled over and deleted.
15168: 
15169: =item *
15170: 
15171: logperm() : append a permanent message to lonnet.perm.log, this log
15172: file never gets deleted by any automated portion of the system, only
15173: messages of critical importance should go in here.
15174: 
15175: 
15176: =back
15177: 
15178: =head2 General File Helper Routines
15179: 
15180: =over 4
15181: 
15182: =item *
15183: 
15184: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15185: (a) files in /uploaded
15186:   (i) If a local copy of the file exists - 
15187:       compares modification date of local copy with last-modified date for 
15188:       definitive version stored on home server for course. If local copy is 
15189:       stale, requests a new version from the home server and stores it. 
15190:       If the original has been removed from the home server, then local copy 
15191:       is unlinked.
15192:   (ii) If local copy does not exist -
15193:       requests the file from the home server and stores it. 
15194:   
15195:   If $caller is 'uploadrep':  
15196:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15197:     for request for files originally uploaded via DOCS. 
15198:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15199:   
15200:   Otherwise:
15201:      This indicates a call from the content generation phase of the request.
15202:      -  returns the entire contents of the file or -1.
15203:      
15204: (b) files in /res
15205:    - returns the entire contents of a file or -1; 
15206:    it properly subscribes to and replicates the file if neccessary.
15207: 
15208: 
15209: =item *
15210: 
15211: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15212:                   reference
15213: 
15214: returns either a stat() list of data about the file or an empty list
15215: if the file doesn't exist or couldn't find out about it (connection
15216: problems or user unknown)
15217: 
15218: =item *
15219: 
15220: filelocation($dir,$file) : returns file system location of a file
15221: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15222: directory that relative $file lookups are to looked in ($dir of /a/dir
15223: and a file of ../bob will become /a/bob)
15224: 
15225: =item *
15226: 
15227: hreflocation($dir,$file) : returns file system location or a URL; same as
15228: filelocation except for hrefs
15229: 
15230: =item *
15231: 
15232: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15233: also removes beginning /home/httpd/html unless /priv/ follows it.
15234: 
15235: =back
15236: 
15237: =head2 Usererfile file routines (/uploaded*)
15238: 
15239: =over 4
15240: 
15241: =item *
15242: 
15243: userfileupload(): main rotine for putting a file in a user or course's
15244:                   filespace, arguments are,
15245: 
15246:  formname - required - this is the name of the element in $env where the
15247:            filename, and the contents of the file to create/modifed exist
15248:            the filename is in $env{'form.'.$formname.'.filename'} and the
15249:            contents of the file is located in $env{'form.'.$formname}
15250:  context - if coursedoc, store the file in the course of the active role
15251:              of the current user; 
15252:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15253:            if 'canceloverwrite': delete file in tmp/overwrites directory
15254:  subdir - required - subdirectory to put the file in under ../userfiles/
15255:          if undefined, it will be placed in "unknown"
15256: 
15257:  (This routine calls clean_filename() to remove any dangerous
15258:  characters from the filename, and then calls finuserfileupload() to
15259:  complete the transaction)
15260: 
15261:  returns either the url of the uploaded file (/uploaded/....) if successful
15262:  and /adm/notfound.html if unsuccessful
15263: 
15264: =item *
15265: 
15266: clean_filename(): routine for cleaing a filename up for storage in
15267:                  userfile space, argument is:
15268: 
15269:  filename - proposed filename
15270: 
15271: returns: the new clean filename
15272: 
15273: =item *
15274: 
15275: finishuserfileupload(): routine that creates and sends the file to
15276: userspace, probably shouldn't be called directly
15277: 
15278:   docuname: username or courseid of destination for the file
15279:   docudom: domain of user/course of destination for the file
15280:   formname: same as for userfileupload()
15281:   fname: filename (including subdirectories) for the file
15282:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15283:   allfiles: reference to hash used to store objects found by parser
15284:   codebase: reference to hash used for codebases of java objects found by parser
15285:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15286:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15287:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15288:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15289:   context: if 'overwrite', will move the uploaded file from its temporary location to
15290:             userfiles to facilitate overwriting a previously uploaded file with same name.
15291:   mimetype: reference to scalar to accommodate mime type determined
15292:             from File::MMagic if $parser = parse.
15293: 
15294:  returns either the url of the uploaded file (/uploaded/....) if successful
15295:  and /adm/notfound.html if unsuccessful (or an error message if context 
15296:  was 'overwrite').
15297:  
15298: 
15299: =item *
15300: 
15301: renameuserfile(): renames an existing userfile to a new name
15302: 
15303:   Args:
15304:    docuname: username or courseid of destination for the file
15305:    docudom: domain of user/course of destination for the file
15306:    old: current file name (including any subdirs under userfiles)
15307:    new: desired file name (including any subdirs under userfiles)
15308: 
15309: =item *
15310: 
15311: mkdiruserfile(): creates a directory is a userfiles dir
15312: 
15313:   Args:
15314:    docuname: username or courseid of destination for the file
15315:    docudom: domain of user/course of destination for the file
15316:    dir: dir to create (including any subdirs under userfiles)
15317: 
15318: =item *
15319: 
15320: removeuserfile(): removes a file that exists in userfiles
15321: 
15322:   Args:
15323:    docuname: username or courseid of destination for the file
15324:    docudom: domain of user/course of destination for the file
15325:    fname: filname to delete (including any subdirs under userfiles)
15326: 
15327: =item *
15328: 
15329: removeuploadedurl(): convience function for removeuserfile()
15330: 
15331:   Args:
15332:    url:  a full /uploaded/... url to delete
15333: 
15334: =item * 
15335: 
15336: get_portfile_permissions():
15337:   Args:
15338:     domain: domain of user or course contain the portfolio files
15339:     user: name of user or num of course contain the portfolio files
15340:   Returns:
15341:     hashref of a dump of the proper file_permissions.db
15342:    
15343: 
15344: =item * 
15345: 
15346: get_access_controls():
15347: 
15348: Args:
15349:   current_permissions: the hash ref returned from get_portfile_permissions()
15350:   group: (optional) the group you want the files associated with
15351:   file: (optional) the file you want access info on
15352: 
15353: Returns:
15354:     a hash (keys are file names) of hashes containing
15355:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15356:         values are XML containing access control settings (see below) 
15357: 
15358: Internal notes:
15359: 
15360:  access controls are stored in file_permissions.db as key=value pairs.
15361:     key -> path to file/file_name\0uniqueID:scope_end_start
15362:         where scope -> public,guest,course,group,domains or users.
15363:               end -> UNIX time for end of access (0 -> no end date)
15364:               start -> UNIX time for start of access
15365: 
15366:     value -> XML description of access control
15367:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15368:             <start></start>
15369:             <end></end>
15370: 
15371:             <password></password>  for scope type = guest
15372: 
15373:             <domain></domain>     for scope type = course or group
15374:             <number></number>
15375:             <roles id="">
15376:              <role></role>
15377:              <access></access>
15378:              <section></section>
15379:              <group></group>
15380:             </roles>
15381: 
15382:             <dom></dom>         for scope type = domains
15383: 
15384:             <users>             for scope type = users
15385:              <user>
15386:               <uname></uname>
15387:               <udom></udom>
15388:              </user>
15389:             </users>
15390:            </scope> 
15391:               
15392:  Access data is also aggregated for each file in an additional key=value pair:
15393:  key -> path to file/file_name\0accesscontrol 
15394:  value -> reference to hash
15395:           hash contains key = value pairs
15396:           where key = uniqueID:scope_end_start
15397:                 value = UNIX time record was last updated
15398: 
15399:           Used to improve speed of look-ups of access controls for each file.  
15400:  
15401:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15402: 
15403: =item *
15404: 
15405: modify_access_controls():
15406: 
15407: Modifies access controls for a portfolio file
15408: Args
15409: 1. file name
15410: 2. reference to hash of required changes,
15411: 3. domain
15412: 4. username
15413:   where domain,username are the domain of the portfolio owner 
15414:   (either a user or a course) 
15415: 
15416: Returns:
15417: 1. result of additions or updates ('ok' or 'error', with error message). 
15418: 2. result of deletions ('ok' or 'error', with error message).
15419: 3. reference to hash of any new or updated access controls.
15420: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15421:    key = integer (inbound ID)
15422:    value = uniqueID
15423: 
15424: =item *
15425: 
15426: get_timebased_id():
15427: 
15428: Attempts to get a unique timestamp-based suffix for use with items added to a 
15429: course via the Course Editor (e.g., folders, composite pages, 
15430: group bulletin boards).
15431: 
15432: Args: (first three required; six others optional)
15433: 
15434: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15435:    docssequence, or name of group
15436: 
15437: 2. keyid (alphanumeric): name of temporary locking key in hash,
15438:    e.g., num, boardids
15439: 
15440: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15441:    file will be named nohist_namespace.db
15442: 
15443: 4. cdom: domain of course; default is current course domain from %env
15444: 
15445: 5. cnum: course number; default is current course number from %env
15446: 
15447: 6. idtype: set to concat if an additional digit is to be appended to the 
15448:    unix timestamp to form the suffix, if the plain timestamp is already
15449:    in use.  Default is to not do this, but simply increment the unix 
15450:    timestamp by 1 until a unique key is obtained.
15451: 
15452: 7. who: holder of locking key; defaults to user:domain for user.
15453: 
15454: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15455:    retrying); default is 3.
15456: 
15457: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15458: 
15459: Returns:
15460: 
15461: 1. suffix obtained (numeric)
15462: 
15463: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15464: 
15465: 3. error: contains (localized) error message if an error occurred.
15466: 
15467: 
15468: =back
15469: 
15470: =head2 HTTP Helper Routines
15471: 
15472: =over 4
15473: 
15474: =item *
15475: 
15476: escape() : unpack non-word characters into CGI-compatible hex codes
15477: 
15478: =item *
15479: 
15480: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15481: 
15482: =back
15483: 
15484: =head1 PRIVATE SUBROUTINES
15485: 
15486: =head2 Underlying communication routines (Shouldn't call)
15487: 
15488: =over 4
15489: 
15490: =item *
15491: 
15492: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15493: 
15494: =item *
15495: 
15496: reply() : uses subreply to send a message to remote machine, logs all failures
15497: 
15498: =item *
15499: 
15500: critical() : passes a critical message to another server; if cannot
15501: get through then place message in connection buffer directory and
15502: returns con_delayed, if incapable of saving message, returns
15503: con_failed
15504: 
15505: =item *
15506: 
15507: reconlonc() : tries to reconnect lonc client processes.
15508: 
15509: =back
15510: 
15511: =head2 Resource Access Logging
15512: 
15513: =over 4
15514: 
15515: =item *
15516: 
15517: flushcourselogs() : flush (save) buffer logs and access logs
15518: 
15519: =item *
15520: 
15521: courselog($what) : save message for course in hash
15522: 
15523: =item *
15524: 
15525: courseacclog($what) : save message for course using &courselog().  Perform
15526: special processing for specific resource types (problems, exams, quizzes, etc).
15527: 
15528: =item *
15529: 
15530: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15531: as a PerlChildExitHandler
15532: 
15533: =back
15534: 
15535: =head2 Other
15536: 
15537: =over 4
15538: 
15539: =item *
15540: 
15541: symblist($mapname,%newhash) : update symbolic storage links
15542: 
15543: =back
15544: 
15545: =cut
15546: 

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