File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1491: download - view: text, annotated - select for diffs
Tue Sep 13 12:22:15 2022 UTC (22 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- In course context, switch server to resource's home server opens new tab
  when editing published resource, and ca role is loaded,  when user's domain
  (by default) disallows session hosting of domain's users in resource's domain.
- New arg (skip_enc_check) in redirect args , used by loncommon::headtag()
  it true, omit application of check_encrypt().
- New seventh item ($shownsymb) in args for lonhtmlcommon::jump_to_editres()

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1491 2022/09/13 12:22:15 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: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   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 Net::CIDR;
  100: use Sys::Hostname::FQDN();
  101: use LONCAPA qw(:DEFAULT :match);
  102: use LONCAPA::Configuration;
  103: use LONCAPA::lonmetadata;
  104: use LONCAPA::Lond;
  105: use LONCAPA::LWPReq;
  106: use LONCAPA::transliterate;
  107: 
  108: use File::Copy;
  109: 
  110: my $readit;
  111: my $max_connection_retries = 20;     # Or some such value.
  112: 
  113: require Exporter;
  114: 
  115: our @ISA = qw (Exporter);
  116: our @EXPORT = qw(%env);
  117: 
  118: 
  119: # ------------------------------------ Logging (parameters, docs, slots, roles)
  120: {
  121:     my $logid;
  122:     sub write_log {
  123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  124:         if ($context eq 'course') {
  125:             if (($cnum eq '') || ($cdom eq '')) {
  126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  128:             }
  129:         }
  130: 	$logid ++;
  131:         my $now = time();
  132: 	my $id=$now.'00000'.$$.'00000'.$logid;
  133:         my $ip = &get_requestor_ip();
  134:         my $logentry = { 
  135:                           $id => {
  136:                                    'exe_uname' => $env{'user.name'},
  137:                                    'exe_udom'  => $env{'user.domain'},
  138:                                    'exe_time'  => $now,
  139:                                    'exe_ip'    => $ip,
  140:                                    'delflag'   => $delflag,
  141:                                    'logentry'  => $storehash,
  142:                                    'uname'     => $uname,
  143:                                    'udom'      => $udom,
  144:                                   }
  145:                        };
  146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  147:     }
  148: }
  149: 
  150: sub logtouch {
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     unless (-e "$execdir/logs/lonnet.log") {	
  153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  154: 	close $fh;
  155:     }
  156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  158: }
  159: 
  160: sub logthis {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  167: 	print $fh $logstring;
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub logperm {
  174:     my $message=shift;
  175:     my $execdir=$perlvar{'lonDaemons'};
  176:     my $now=time;
  177:     my $local=localtime($now);
  178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  179: 	print $fh "$now:$message:$local\n";
  180: 	close($fh);
  181:     }
  182:     return 1;
  183: }
  184: 
  185: sub create_connection {
  186:     my ($hostname,$lonid) = @_;
  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  188: 				     Type    => SOCK_STREAM,
  189: 				     Timeout => 10);
  190:     return 0 if (!$client);
  191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  192:     my $result = <$client>;
  193:     chomp($result);
  194:     return 1 if ($result eq 'done');
  195:     return 0;
  196: }
  197: 
  198: sub get_server_timezone {
  199:     my ($cnum,$cdom) = @_;
  200:     my $home=&homeserver($cnum,$cdom);
  201:     if ($home ne 'no_host') {
  202:         my $cachetime = 24*3600;
  203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  204:         if (defined($cached)) {
  205:             return $timezone;
  206:         } else {
  207:             my $timezone = &reply('servertimezone',$home);
  208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  209:         }
  210:     }
  211: }
  212: 
  213: sub get_server_distarch {
  214:     my ($lonhost,$ignore_cache) = @_;
  215:     if (defined($lonhost)) {
  216:         if (!defined(&hostname($lonhost))) {
  217:             return;
  218:         }
  219:         my $cachetime = 12*3600;
  220:         if (!$ignore_cache) {
  221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  222:             if (defined($cached)) {
  223:                 return $distarch;
  224:             }
  225:         }
  226:         my $rep = &reply('serverdistarch',$lonhost);
  227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  229:                 $rep eq '') {
  230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  231:         }
  232:     }
  233:     return;
  234: }
  235: 
  236: sub get_servercerts_info {
  237:     my ($lonhost,$hostname,$context) = @_;
  238:     return if ($lonhost eq '');
  239:     if ($hostname eq '') {
  240:         $hostname = &hostname($lonhost);
  241:     }
  242:     return if ($hostname eq '');
  243:     my ($rep,$uselocal);
  244:     if ($context eq 'install') {
  245:         $uselocal = 1;
  246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  247:         $uselocal = 1;
  248:     }
  249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  251:         if ($distro eq '') {
  252:             $uselocal = 0;
  253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  254:             if ($1 < 6) {
  255:                 $uselocal = 0;
  256:             }
  257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  258:             if ($1 < 12) {
  259:                 $uselocal = 0;
  260:             }
  261:         }
  262:     }
  263:     if ($uselocal) {
  264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  265:     } else {
  266:         $rep=&reply('servercerts',$lonhost);
  267:     }
  268:     my ($result,%returnhash);
  269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  270:         ($rep eq 'unknown_cmd')) {
  271:         $result = $rep;
  272:     } else {
  273:         $result = 'ok';
  274:         my @pairs=split(/\&/,$rep);
  275:         foreach my $item (@pairs) {
  276:             my ($key,$value)=split(/=/,$item,2);
  277:             my $what = &unescape($key);
  278:             $returnhash{$what}=&thaw_unescape($value);
  279:         }
  280:     }
  281:     return ($result,\%returnhash);
  282: }
  283: 
  284: sub get_server_loncaparev {
  285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  286:     if (defined($lonhost)) {
  287:         if (!defined(&hostname($lonhost))) {
  288:             undef($lonhost);
  289:         }
  290:     }
  291:     if (!defined($lonhost)) {
  292:         if (defined(&domain($dom,'primary'))) {
  293:             $lonhost=&domain($dom,'primary');
  294:             if ($lonhost eq 'no_host') {
  295:                 undef($lonhost);
  296:             }
  297:         }
  298:     }
  299:     if (defined($lonhost)) {
  300:         my $cachetime = 12*3600;
  301:         if (!$ignore_cache) {
  302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  303:             if (defined($cached)) {
  304:                 return $loncaparev;
  305:             }
  306:         }
  307:         my ($answer,$loncaparev);
  308:         my @ids=&current_machine_ids();
  309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  310:             $answer = $perlvar{'lonVersion'};
  311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  312:                 $loncaparev = $1;
  313:             }
  314:         } else {
  315:             $answer = &reply('serverloncaparev',$lonhost);
  316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  317:                 if ($caller eq 'loncron') {
  318:                     my $hostname = &hostname($lonhost);
  319:                     my $protocol = $protocol{$lonhost};
  320:                     $protocol = 'http' if ($protocol ne 'https');
  321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  322:                     my $request=new HTTP::Request('GET',$url);
  323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  324:                     unless ($response->is_error()) {
  325:                         my $content = $response->content;
  326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  327:                             $loncaparev = $1;
  328:                         }
  329:                     }
  330:                 } else {
  331:                     $loncaparev = $loncaparevs{$lonhost};
  332:                 }
  333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  334:                 $loncaparev = $1;
  335:             }
  336:         }
  337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  338:     }
  339: }
  340: 
  341: sub get_server_homeID {
  342:     my ($hostname,$ignore_cache,$caller) = @_;
  343:     unless ($ignore_cache) {
  344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  345:         if (defined($cached)) {
  346:             return $serverhomeID;
  347:         }
  348:     }
  349:     my $cachetime = 12*3600;
  350:     my $serverhomeID;
  351:     if ($caller eq 'loncron') { 
  352:         my @machine_ids = &machine_ids($hostname);
  353:         foreach my $id (@machine_ids) {
  354:             my $response = &reply('serverhomeID',$id);
  355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  356:                 $serverhomeID = $response;
  357:                 last;
  358:             }
  359:         }
  360:         if ($serverhomeID eq '') {
  361:             $serverhomeID = $machine_ids[-1];
  362:         }
  363:     } else {
  364:         $serverhomeID = $serverhomeIDs{$hostname};
  365:     }
  366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  367: }
  368: 
  369: sub get_remote_globals {
  370:     my ($lonhost,$whathash,$ignore_cache) = @_;
  371:     my ($result,%returnhash,%whatneeded);
  372:     if (ref($whathash) eq 'HASH') {
  373:         foreach my $what (sort(keys(%{$whathash}))) {
  374:             my $hashid = $lonhost.'-'.$what;
  375:             my ($response,$cached);
  376:             unless ($ignore_cache) {
  377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  378:             }
  379:             if (defined($cached)) {
  380:                 $returnhash{$what} = $response;
  381:             } else {
  382:                 $whatneeded{$what} = 1;
  383:             }
  384:         }
  385:         if (keys(%whatneeded) == 0) {
  386:             $result = 'ok';
  387:         } else {
  388:             my $requested = &freeze_escape(\%whatneeded);
  389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  391:                 ($rep eq 'unknown_cmd')) {
  392:                 $result = $rep;
  393:             } else {
  394:                 $result = 'ok';
  395:                 my @pairs=split(/\&/,$rep);
  396:                 foreach my $item (@pairs) {
  397:                     my ($key,$value)=split(/=/,$item,2);
  398:                     my $what = &unescape($key);
  399:                     my $hashid = $lonhost.'-'.$what;
  400:                     $returnhash{$what}=&thaw_unescape($value);
  401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  402:                 }
  403:             }
  404:         }
  405:     }
  406:     return ($result,\%returnhash);
  407: }
  408: 
  409: sub remote_devalidate_cache {
  410:     my ($lonhost,$cachekeys) = @_;
  411:     my $items;
  412:     return unless (ref($cachekeys) eq 'ARRAY');
  413:     my $cachestr = join('&',@{$cachekeys});
  414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  415:     return $response;
  416: }
  417: 
  418: # -------------------------------------------------- Non-critical communication
  419: sub subreply {
  420:     my ($cmd,$server)=@_;
  421:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  422:     #
  423:     #  With loncnew process trimming, there's a timing hole between lonc server
  424:     #  process exit and the master server picking up the listen on the AF_UNIX
  425:     #  socket.  In that time interval, a lock file will exist:
  426: 
  427:     my $lockfile=$peerfile.".lock";
  428:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  429: 	sleep(0.1);
  430:     }
  431:     # At this point, either a loncnew parent is listening or an old lonc
  432:     # or loncnew child is listening so we can connect or everything's dead.
  433:     #
  434:     #   We'll give the connection a few tries before abandoning it.  If
  435:     #   connection is not possible, we'll con_lost back to the client.
  436:     #   
  437:     my $client;
  438:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  439: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  440: 				      Type    => SOCK_STREAM,
  441: 				      Timeout => 10);
  442: 	if ($client) {
  443: 	    last;		# Connected!
  444: 	} else {
  445: 	    &create_connection(&hostname($server),$server);
  446: 	}
  447:         sleep(0.1);	# Try again later if failed connection.
  448:     }
  449:     my $answer;
  450:     if ($client) {
  451: 	print $client "sethost:$server:$cmd\n";
  452: 	$answer=<$client>;
  453: 	if (!$answer) { $answer="con_lost"; }
  454: 	chomp($answer);
  455:     } else {
  456: 	$answer = 'con_lost';	# Failed connection.
  457:     }
  458:     return $answer;
  459: }
  460: 
  461: sub reply {
  462:     my ($cmd,$server)=@_;
  463:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  464:     my $answer=subreply($cmd,$server);
  465:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  466:         my $logged = $cmd;
  467:         if ($cmd =~ /^encrypt:([^:]+):/) {
  468:             my $subcmd = $1;
  469:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  470:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  471:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  472:                 ($subcmd eq 'put')) {
  473:                 (undef,undef,my @rest) = split(/:/,$cmd);
  474:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  475:                     splice(@rest,2,1,'Hidden');
  476:                 } elsif ($subcmd eq 'passwd') {
  477:                     splice(@rest,2,2,('Hidden','Hidden'));
  478:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  479:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  480:                     splice(@rest,3,1,'Hidden');
  481:                 }
  482:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  483:             }
  484:         }
  485:         &logthis("<font color=\"blue\">WARNING:".
  486:                  " $logged to $server returned $answer</font>");
  487:     }
  488:     return $answer;
  489: }
  490: 
  491: # ----------------------------------------------------------- Send USR1 to lonc
  492: 
  493: sub reconlonc {
  494:     my ($lonid) = @_;
  495:     if ($lonid) {
  496:         my $hostname = &hostname($lonid);
  497: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  498: 	if ($hostname && -e $peerfile) {
  499: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  500: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  501: 					     Type    => SOCK_STREAM,
  502: 					     Timeout => 10);
  503: 	    if ($client) {
  504: 		print $client ("reset_retries\n");
  505: 		my $answer=<$client>;
  506: 		#reset just this one.
  507: 	    }
  508: 	}
  509: 	return;
  510:     }
  511: 
  512:     &logthis("Trying to reconnect lonc");
  513:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  514:     if (open(my $fh,"<",$loncfile)) {
  515: 	my $loncpid=<$fh>;
  516:         chomp($loncpid);
  517:         if (kill 0 => $loncpid) {
  518: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  519:             kill USR1 => $loncpid;
  520:             sleep 1;
  521:         } else {
  522: 	    &logthis(
  523:                "<font color=\"blue\">WARNING:".
  524:                " lonc at pid $loncpid not responding, giving up</font>");
  525:         }
  526:     } else {
  527: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  528:     }
  529: }
  530: 
  531: # ------------------------------------------------------ Critical communication
  532: 
  533: sub critical {
  534:     my ($cmd,$server)=@_;
  535:     unless (&hostname($server)) {
  536:         &logthis("<font color=\"blue\">WARNING:".
  537:                " Critical message to unknown server ($server)</font>");
  538:         return 'no_such_host';
  539:     }
  540:     my $answer=reply($cmd,$server);
  541:     if ($answer eq 'con_lost') {
  542: 	&reconlonc($server);
  543: 	my $answer=reply($cmd,$server);
  544:         if ($answer eq 'con_lost') {
  545:             my $now=time;
  546:             my $middlename=$cmd;
  547:             $middlename=substr($middlename,0,16);
  548:             $middlename=~s/\W//g;
  549:             my $dfilename=
  550:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  551:             $dumpcount++;
  552:             {
  553: 		my $dfh;
  554: 		if (open($dfh,">",$dfilename)) {
  555: 		    print $dfh "$cmd\n"; 
  556: 		    close($dfh);
  557: 		}
  558:             }
  559:             sleep 1;
  560:             my $wcmd='';
  561:             {
  562: 		my $dfh;
  563: 		if (open($dfh,"<",$dfilename)) {
  564: 		    $wcmd=<$dfh>; 
  565: 		    close($dfh);
  566: 		}
  567:             }
  568:             chomp($wcmd);
  569:             if ($wcmd eq $cmd) {
  570: 		&logthis("<font color=\"blue\">WARNING: ".
  571:                          "Connection buffer $dfilename: $cmd</font>");
  572:                 &logperm("D:$server:$cmd");
  573: 	        return 'con_delayed';
  574:             } else {
  575:                 &logthis("<font color=\"red\">CRITICAL:"
  576:                         ." Critical connection failed: $server $cmd</font>");
  577:                 &logperm("F:$server:$cmd");
  578:                 return 'con_failed';
  579:             }
  580:         }
  581:     }
  582:     return $answer;
  583: }
  584: 
  585: # ------------------------------------------- check if return value is an error
  586: 
  587: sub error {
  588:     my ($result) = @_;
  589:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  590: 	if ($2 == 2) { return undef; }
  591: 	return $1;
  592:     }
  593:     return undef;
  594: }
  595: 
  596: sub convert_and_load_session_env {
  597:     my ($lonidsdir,$handle)=@_;
  598:     my @profile;
  599:     {
  600: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  601: 	if (!$opened) {
  602: 	    return 0;
  603: 	}
  604: 	flock($idf,LOCK_SH);
  605: 	@profile=<$idf>;
  606: 	close($idf);
  607:     }
  608:     my %temp_env;
  609:     foreach my $line (@profile) {
  610: 	if ($line !~ m/=/) {
  611: 	    return 0;
  612: 	}
  613: 	chomp($line);
  614: 	my ($envname,$envvalue)=split(/=/,$line,2);
  615: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  616:     }
  617:     unlink("$lonidsdir/$handle.id");
  618:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  619: 	    0640)) {
  620: 	%disk_env = %temp_env;
  621: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  622: 	untie(%disk_env);
  623:     }
  624:     return 1;
  625: }
  626: 
  627: # ------------------------------------------- Transfer profile into environment
  628: my $env_loaded;
  629: sub transfer_profile_to_env {
  630:     my ($lonidsdir,$handle,$force_transfer) = @_;
  631:     if (!$force_transfer && $env_loaded) { return; } 
  632: 
  633:     if (!defined($lonidsdir)) {
  634: 	$lonidsdir = $perlvar{'lonIDsDir'};
  635:     }
  636:     if (!defined($handle)) {
  637:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  638:     }
  639: 
  640:     my $convert;
  641:     {
  642:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  643: 	if (!$opened) {
  644: 	    return;
  645: 	}
  646: 	flock($idf,LOCK_SH);
  647: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  648: 		&GDBM_READER(),0640)) {
  649: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  650: 	    untie(%disk_env);
  651: 	} else {
  652: 	    $convert = 1;
  653: 	}
  654:     }
  655:     if ($convert) {
  656: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  657: 	    &logthis("Failed to load session, or convert session.");
  658: 	}
  659:     }
  660: 
  661:     my %remove;
  662:     while ( my $envname = each(%env) ) {
  663:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  664:             if ($time < time-300) {
  665:                 $remove{$key}++;
  666:             }
  667:         }
  668:     }
  669: 
  670:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  671:     $env_loaded=1;
  672:     foreach my $expired_key (keys(%remove)) {
  673:         &delenv($expired_key);
  674:     }
  675: }
  676: 
  677: # ---------------------------------------------------- Check for valid session 
  678: sub check_for_valid_session {
  679:     my ($r,$name,$userhashref,$domref) = @_;
  680:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  681:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  682:     if ($name eq 'lonDAV') {
  683:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  684:     } else {
  685:         $lonidsdir=$r->dir_config('lonIDsDir');
  686:         if ($name eq '') {
  687:             $name = 'lonID';
  688:         }
  689:     }
  690:     if ($name eq 'lonID') {
  691:         $secure = 'lonSID';
  692:         $linkname = 'lonLinkID';
  693:         $pubname = 'lonPubID';
  694:         if (exists($cookies{$secure})) {
  695:             $lonid=$cookies{$secure};
  696:         } elsif (exists($cookies{$name})) {
  697:             $lonid=$cookies{$name};
  698:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  699:             $lonid=$cookies{$linkname};
  700:         } elsif (exists($cookies{$pubname})) {
  701:             $lonid=$cookies{$pubname};
  702:         }
  703:     } else {
  704:         $lonid=$cookies{$name};
  705:     }
  706:     return undef if (!$lonid);
  707: 
  708:     my $handle=&LONCAPA::clean_handle($lonid->value);
  709:     if (-l "$lonidsdir/$handle.id") {
  710:         my $link = readlink("$lonidsdir/$handle.id");
  711:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  712:             $handle = $1;
  713:         }
  714:     }
  715:     if (!-e "$lonidsdir/$handle.id") {
  716:         if ((ref($domref)) && ($name eq 'lonID') && 
  717:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  718:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  719:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  720:                 $$domref = $possudom;
  721:             }
  722:         }
  723:         return undef;
  724:     }
  725: 
  726:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  727:     return undef if (!$opened);
  728: 
  729:     flock($idf,LOCK_SH);
  730:     my %disk_env;
  731:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  732: 	    &GDBM_READER(),0640)) {
  733: 	return undef;	
  734:     }
  735: 
  736:     if (!defined($disk_env{'user.name'})
  737: 	|| !defined($disk_env{'user.domain'})) {
  738:         untie(%disk_env);
  739: 	return undef;
  740:     }
  741: 
  742:     if (ref($userhashref) eq 'HASH') {
  743:         $userhashref->{'name'} = $disk_env{'user.name'};
  744:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  745:         if ($disk_env{'request.role'}) {
  746:             $userhashref->{'role'} = $disk_env{'request.role'};
  747:         }
  748:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  749:         if ($userhashref->{'lti'}) {
  750:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  751:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  752:         }
  753:     }
  754:     untie(%disk_env);
  755: 
  756:     return $handle;
  757: }
  758: 
  759: sub timed_flock {
  760:     my ($file,$lock_type) = @_;
  761:     my $failed=0;
  762:     eval {
  763: 	local $SIG{__DIE__}='DEFAULT';
  764: 	local $SIG{ALRM}=sub {
  765: 	    $failed=1;
  766: 	    die("failed lock");
  767: 	};
  768: 	alarm(13);
  769: 	flock($file,$lock_type);
  770: 	alarm(0);
  771:     };
  772:     if ($failed) {
  773: 	return undef;
  774:     } else {
  775: 	return 1;
  776:     }
  777: }
  778: 
  779: sub get_sessionfile_vars {
  780:     my ($handle,$lonidsdir,$storearr) = @_;
  781:     my %returnhash;
  782:     unless (ref($storearr) eq 'ARRAY') {
  783:         return %returnhash;
  784:     }
  785:     if (-l "$lonidsdir/$handle.id") {
  786:         my $link = readlink("$lonidsdir/$handle.id");
  787:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  788:             $handle = $1;
  789:         }
  790:     }
  791:     if ((-e "$lonidsdir/$handle.id") &&
  792:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  793:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  794:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  795:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  796:                 flock($idf,LOCK_SH);
  797:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  798:                         &GDBM_READER(),0640)) {
  799:                     foreach my $item (@{$storearr}) {
  800:                         $returnhash{$item} = $disk_env{$item};
  801:                     }
  802:                     untie(%disk_env);
  803:                 }
  804:             }
  805:         }
  806:     }
  807:     return %returnhash;
  808: }
  809: 
  810: # ---------------------------------------------------------- Append Environment
  811: 
  812: sub appenv {
  813:     my ($newenv,$roles) = @_;
  814:     if (ref($newenv) eq 'HASH') {
  815:         foreach my $key (keys(%{$newenv})) {
  816:             my $refused = 0;
  817: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  818:                 $refused = 1;
  819:                 if (ref($roles) eq 'ARRAY') {
  820:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  821:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  822:                         $refused = 0;
  823:                     }
  824:                 }
  825:             }
  826:             if ($refused) {
  827:                 &logthis("<font color=\"blue\">WARNING: ".
  828:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  829:                          .'</font>');
  830: 	        delete($newenv->{$key});
  831:             } else {
  832:                 $env{$key}=$newenv->{$key};
  833:             }
  834:         }
  835:         my $lonids = $perlvar{'lonIDsDir'};
  836:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  837:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  838:             if ($opened
  839: 	        && &timed_flock($env_file,LOCK_EX)
  840: 	        &&
  841: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  842: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  843: 	        while (my ($key,$value) = each(%{$newenv})) {
  844: 	            $disk_env{$key} = $value;
  845: 	        }
  846: 	        untie(%disk_env);
  847:             }
  848:         }
  849:     }
  850:     return 'ok';
  851: }
  852: # ----------------------------------------------------- Delete from Environment
  853: 
  854: sub delenv {
  855:     my ($delthis,$regexp,$roles) = @_;
  856:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  857:         my $refused = 1;
  858:         if (ref($roles) eq 'ARRAY') {
  859:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  860:             if (grep(/^\Q$role\E$/,@{$roles})) {
  861:                 $refused = 0;
  862:             }
  863:         }
  864:         if ($refused) {
  865:             &logthis("<font color=\"blue\">WARNING: ".
  866:                      "Attempt to delete from environment ".$delthis);
  867:             return 'error';
  868:         }
  869:     }
  870:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  871:     if ($opened
  872: 	&& &timed_flock($env_file,LOCK_EX)
  873: 	&&
  874: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  875: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  876: 	foreach my $key (keys(%disk_env)) {
  877: 	    if ($regexp) {
  878:                 if ($key=~/^$delthis/) {
  879:                     delete($env{$key});
  880:                     delete($disk_env{$key});
  881:                 } 
  882:             } else {
  883:                 if ($key=~/^\Q$delthis\E/) {
  884: 		    delete($env{$key});
  885: 		    delete($disk_env{$key});
  886: 	        }
  887:             }
  888: 	}
  889: 	untie(%disk_env);
  890:     }
  891:     return 'ok';
  892: }
  893: 
  894: sub get_env_multiple {
  895:     my ($name) = @_;
  896:     my @values;
  897:     if (defined($env{$name})) {
  898:         # exists is it an array
  899:         if (ref($env{$name})) {
  900:             @values=@{ $env{$name} };
  901:         } else {
  902:             $values[0]=$env{$name};
  903:         }
  904:     }
  905:     return(@values);
  906: }
  907: 
  908: # ------------------------------------------------------------------- Locking
  909: 
  910: sub set_lock {
  911:     my ($text)=@_;
  912:     $locknum++;
  913:     my $id=$$.'-'.$locknum;
  914:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  915:              'session.lock.'.$id => $text});
  916:     return $id;
  917: }
  918: 
  919: sub get_locks {
  920:     my $num=0;
  921:     my %texts=();
  922:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  923:        if ($lock=~/\w/) {
  924:           $num++;
  925:           $texts{$lock}=$env{'session.lock.'.$lock};
  926:        }
  927:    }
  928:    return ($num,%texts);
  929: }
  930: 
  931: sub remove_lock {
  932:     my ($id)=@_;
  933:     my $newlocks='';
  934:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  935:        if (($lock=~/\w/) && ($lock ne $id)) {
  936:           $newlocks.=','.$lock;
  937:        }
  938:     }
  939:     &appenv({'session.locks' => $newlocks});
  940:     &delenv('session.lock.'.$id);
  941: }
  942: 
  943: sub remove_all_locks {
  944:     my $activelocks=$env{'session.locks'};
  945:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  946:        if ($lock=~/\w/) {
  947:           &remove_lock($lock);
  948:        }
  949:     }
  950: }
  951: 
  952: 
  953: # ------------------------------------------ Find out current server userload
  954: sub userload {
  955:     my $numusers=0;
  956:     {
  957: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  958: 	my $filename;
  959: 	my $curtime=time;
  960: 	while ($filename=readdir(LONIDS)) {
  961: 	    next if ($filename eq '.' || $filename eq '..');
  962: 	    next if ($filename =~ /publicuser_\d+\.id/);
  963:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  964: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  965: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  966: 	}
  967: 	closedir(LONIDS);
  968:     }
  969:     my $userloadpercent=0;
  970:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  971:     if ($maxuserload) {
  972: 	$userloadpercent=100*$numusers/$maxuserload;
  973:     }
  974:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  975:     return $userloadpercent;
  976: }
  977: 
  978: # ------------------------------ Find server with least workload from spare.tab
  979: 
  980: sub spareserver {
  981:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  982:     my $spare_server;
  983:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  984:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  985:                                                      :  $userloadpercent;
  986:     my ($uint_dom,$remotesessions);
  987:     if (($udom ne '') && (&domain($udom) ne '')) {
  988:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  989:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  990:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  991:         $remotesessions = $udomdefaults{'remotesessions'};
  992:     }
  993:     my $spareshash = &this_host_spares($udom);
  994:     if (ref($spareshash) eq 'HASH') {
  995:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  996:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  997:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  998:                                              $try_server));
  999: 	        ($spare_server, $lowest_load) =
 1000: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1001:             }
 1002:         }
 1003: 
 1004:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1005: 
 1006:         if (!$found_server) {
 1007:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1008: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1009:                     next unless (&spare_can_host($udom,$uint_dom,
 1010:                                                  $remotesessions,$try_server));
 1011: 	            ($spare_server, $lowest_load) =
 1012: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1013:                 }
 1014: 	    }
 1015:         }
 1016:     }
 1017: 
 1018:     if (!$want_server_name) {
 1019:         if (defined($spare_server)) {
 1020:             my $hostname = &hostname($spare_server);
 1021:             if (defined($hostname)) {
 1022:                 my $protocol = 'http';
 1023:                 if ($protocol{$spare_server} eq 'https') {
 1024:                     $protocol = $protocol{$spare_server};
 1025:                 }
 1026:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
 1027:                 $hostname = $alias if ($alias ne '');
 1028: 	        $spare_server = $protocol.'://'.$hostname;
 1029:             }
 1030:         }
 1031:     }
 1032:     return $spare_server;
 1033: }
 1034: 
 1035: sub compare_server_load {
 1036:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1037: 
 1038:     if ($required) {
 1039:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1040:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1041:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1042:         if (($major eq '' && $minor eq '') ||
 1043:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1044:             return ($spare_server,$lowest_load);
 1045:         }
 1046:     }
 1047: 
 1048:     my $loadans     = &reply('load',    $try_server);
 1049:     my $userloadans = &reply('userload',$try_server);
 1050: 
 1051:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1052: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1053:     }
 1054: 
 1055:     my $load;
 1056:     if ($loadans =~ /\d/) {
 1057: 	if ($userloadans =~ /\d/) {
 1058: 	    #both are numbers, pick the bigger one
 1059: 	    $load = ($loadans > $userloadans) ? $loadans 
 1060: 		                              : $userloadans;
 1061: 	} else {
 1062: 	    $load = $loadans;
 1063: 	}
 1064:     } else {
 1065: 	$load = $userloadans;
 1066:     }
 1067: 
 1068:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1069: 	$spare_server = $try_server;
 1070: 	$lowest_load  = $load;
 1071:     }
 1072:     return ($spare_server,$lowest_load);
 1073: }
 1074: 
 1075: # --------------------------- ask offload servers if user already has a session
 1076: sub find_existing_session {
 1077:     my ($udom,$uname) = @_;
 1078:     my $spareshash = &this_host_spares($udom);
 1079:     if (ref($spareshash) eq 'HASH') {
 1080:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1081:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1082:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1083:             }
 1084:         }
 1085:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1086:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1087:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1088:             }
 1089:         }
 1090:     }
 1091:     return;
 1092: }
 1093: 
 1094: sub delusersession {
 1095:     my ($lonid,$udom,$uname) = @_;
 1096:     my $uprimary_id = &domain($udom,'primary');
 1097:     my $uintdom = &internet_dom($uprimary_id);
 1098:     my $intdom = &internet_dom($lonid);
 1099:     my $serverhomedom = &host_domain($lonid);
 1100:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1101:         return &reply(join(':','delusersession',
 1102:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1103:     }
 1104:     return;
 1105: }
 1106: 
 1107: # check if user's browser sent load balancer cookie and server still has session
 1108: # and is not overloaded.
 1109: sub check_for_balancer_cookie {
 1110:     my ($r,$update_mtime) = @_;
 1111:     my ($otherserver,$cookie);
 1112:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1113:     if (exists($cookies{'balanceID'})) {
 1114:         my $balid = $cookies{'balanceID'};
 1115:         $cookie=&LONCAPA::clean_handle($balid->value);
 1116:         my $balancedir=$r->dir_config('lonBalanceDir');
 1117:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1118:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1119:                 my ($possudom,$possuname) = ($1,$2);
 1120:                 my $has_session = 0;
 1121:                 if ((&domain($possudom) ne '') &&
 1122:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1123:                     my $try_server;
 1124:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1125:                     if ($opened) {
 1126:                         flock($idf,LOCK_SH);
 1127:                         while (my $line = <$idf>) {
 1128:                             chomp($line);
 1129:                             if (&hostname($line) ne '') {
 1130:                                 $try_server = $line;
 1131:                                 last;
 1132:                             }
 1133:                         }
 1134:                         close($idf);
 1135:                         if (($try_server) &&
 1136:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1137:                             my $lowest_load = 30000;
 1138:                             ($otherserver,$lowest_load) =
 1139:                                 &compare_server_load($try_server,undef,$lowest_load);
 1140:                             if ($otherserver ne '' && $lowest_load < 100) {
 1141:                                 $has_session = 1;
 1142:                             } else {
 1143:                                 undef($otherserver);
 1144:                             }
 1145:                         }
 1146:                     }
 1147:                 }
 1148:                 if ($has_session) {
 1149:                     if ($update_mtime) {
 1150:                         my $atime = my $mtime = time;
 1151:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1152:                     }
 1153:                 } else {
 1154:                     unlink("$balancedir/$cookie.id");
 1155:                 }
 1156:             }
 1157:         }
 1158:     }
 1159:     return ($otherserver,$cookie);
 1160: }
 1161: 
 1162: sub updatebalcookie {
 1163:     my ($cookie,$balancer,$lastentry)=@_;
 1164:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1165:         my ($udom,$uname) = ($1,$2);
 1166:         my $uprimary_id = &domain($udom,'primary');
 1167:         my $uintdom = &internet_dom($uprimary_id);
 1168:         my $intdom = &internet_dom($balancer);
 1169:         my $serverhomedom = &host_domain($balancer);
 1170:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1171:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1172:         }
 1173:     }
 1174:     return;
 1175: }
 1176: 
 1177: sub delbalcookie {
 1178:     my ($cookie,$balancer) =@_;
 1179:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1180:         my ($udom,$uname) = ($1,$2);
 1181:         my $uprimary_id = &domain($udom,'primary');
 1182:         my $uintdom = &internet_dom($uprimary_id);
 1183:         my $intdom = &internet_dom($balancer);
 1184:         my $serverhomedom = &host_domain($balancer);
 1185:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1186:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1187:         }
 1188:     }
 1189: }
 1190: 
 1191: # -------------------------------- ask if server already has a session for user
 1192: sub has_user_session {
 1193:     my ($lonid,$udom,$uname) = @_;
 1194:     my $result = &reply(join(':','userhassession',
 1195: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1196:     return 1 if ($result eq 'ok');
 1197: 
 1198:     return 0;
 1199: }
 1200: 
 1201: # --------- determine least loaded server in a user's domain which allows login
 1202: 
 1203: sub choose_server {
 1204:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1205:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1206:     my %servers = &get_servers($udom);
 1207:     my $lowest_load = 30000;
 1208:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1209:     if ($skiploadbal) {
 1210:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1211:         unless (defined($cached)) {
 1212:             my $cachetime = 60*60*24;
 1213:             my %domconfig =
 1214:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1215:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1216:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1217:                                            $cachetime);
 1218:             }
 1219:         }
 1220:     }
 1221:     foreach my $lonhost (keys(%servers)) {
 1222:         if ($skiploadbal) {
 1223:             if (ref($balancers) eq 'HASH') {
 1224:                 next if (exists($balancers->{$lonhost}));
 1225:             }
 1226:         }
 1227:         my $loginvia;
 1228:         if ($checkloginvia) {
 1229:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1230:             if ($loginvia) {
 1231:                 my ($server,$path) = split(/:/,$loginvia);
 1232:                 ($login_host, $lowest_load) =
 1233:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1234:                 if ($login_host eq $server) {
 1235:                     $portal_path = $path;
 1236:                     $isredirect = 1;
 1237:                 }
 1238:             } else {
 1239:                 ($login_host, $lowest_load) =
 1240:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1241:                 if ($login_host eq $lonhost) {
 1242:                     $portal_path = '';
 1243:                     $isredirect = ''; 
 1244:                 }
 1245:             }
 1246:         } else {
 1247:             ($login_host, $lowest_load) =
 1248:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1249:         }
 1250:     }
 1251:     if ($login_host ne '') {
 1252:         $hostname = &hostname($login_host);
 1253:     }
 1254:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1255: }
 1256: 
 1257: sub get_course_sessions {
 1258:     my ($cnum,$cdom,$lastactivity) = @_;
 1259:     my %servers = &internet_dom_servers($cdom);
 1260:     my %returnhash;
 1261:     foreach my $server (sort(keys(%servers))) {
 1262:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1263:         my @pairs=split(/\&/,$rep);
 1264:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1265:             foreach my $item (@pairs) {
 1266:                 my ($key,$value)=split(/=/,$item,2);
 1267:                 $key = &unescape($key);
 1268:                 next if ($key =~ /^error: 2 /);
 1269:                 if (exists($returnhash{$key})) {
 1270:                     next if ($value < $returnhash{$key});
 1271:                 }
 1272:                 $returnhash{$key}=$value;
 1273:             }
 1274:         }
 1275:     }
 1276:     return %returnhash;
 1277: }
 1278: 
 1279: # --------------------------------------------- Try to change a user's password
 1280: 
 1281: sub changepass {
 1282:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1283:     $currentpass = &escape($currentpass);
 1284:     $newpass     = &escape($newpass);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1287: 		       $server);
 1288:     if (! $answer) {
 1289: 	&logthis("No reply on password change request to $server ".
 1290: 		 "by $uname in domain $udom.");
 1291:     } elsif ($answer =~ "^ok") {
 1292:         &logthis("$uname in $udom successfully changed their password ".
 1293: 		 "on $server.");
 1294:     } elsif ($answer =~ "^pwchange_failure") {
 1295: 	&logthis("$uname in $udom was unable to change their password ".
 1296: 		 "on $server.  The action was blocked by either lcpasswd ".
 1297: 		 "or pwchange");
 1298:     } elsif ($answer =~ "^non_authorized") {
 1299:         &logthis("$uname in $udom did not get their password correct when ".
 1300: 		 "attempting to change it on $server.");
 1301:     } elsif ($answer =~ "^auth_mode_error") {
 1302:         &logthis("$uname in $udom attempted to change their password despite ".
 1303: 		 "not being locally or internally authenticated on $server.");
 1304:     } elsif ($answer =~ "^unknown_user") {
 1305:         &logthis("$uname in $udom attempted to change their password ".
 1306: 		 "on $server but were unable to because $server is not ".
 1307: 		 "their home server.");
 1308:     } elsif ($answer =~ "^refused") {
 1309: 	&logthis("$server refused to change $uname in $udom password because ".
 1310: 		 "it was sent an unencrypted request to change the password.");
 1311:     } elsif ($answer =~ "invalid_client") {
 1312:         &logthis("$server refused to change $uname in $udom password because ".
 1313:                  "it was a reset by e-mail originating from an invalid server.");
 1314:     } elsif ($answer =~ "^prioruse") {
 1315:        &logthis("$server refused to change $uname in $udom password because ".
 1316:                 "the password had been used before");
 1317:     }
 1318:     return $answer;
 1319: }
 1320: 
 1321: # ----------------------- Try to determine user's current authentication scheme
 1322: 
 1323: sub queryauthenticate {
 1324:     my ($uname,$udom)=@_;
 1325:     my $uhome=&homeserver($uname,$udom);
 1326:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1327: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1328: 	return 'no_host';
 1329:     }
 1330:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1331:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1332: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1333:     }
 1334:     return $answer;
 1335: }
 1336: 
 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
 1338: 
 1339: sub authenticate {
 1340:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1341:     $upass=&escape($upass);
 1342:     $uname= &LONCAPA::clean_username($uname);
 1343:     my $uhome=&homeserver($uname,$udom,1);
 1344:     my $newhome;
 1345:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1346: # Maybe the machine was offline and only re-appeared again recently?
 1347:         &reconlonc();
 1348: # One more
 1349: 	$uhome=&homeserver($uname,$udom,1);
 1350:         if (($uhome eq 'no_host') && $checkdefauth) {
 1351:             if (defined(&domain($udom,'primary'))) {
 1352:                 $newhome=&domain($udom,'primary');
 1353:             }
 1354:             if ($newhome ne '') {
 1355:                 $uhome = $newhome;
 1356:             }
 1357:         }
 1358: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1359: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1360: 	    return 'no_host';
 1361:         }
 1362:     }
 1363:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1364:     if ($answer eq 'authorized') {
 1365:         if ($newhome) {
 1366:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1367:             return 'no_account_on_host'; 
 1368:         } else {
 1369:             &logthis("User $uname at $udom authorized by $uhome");
 1370:             return $uhome;
 1371:         }
 1372:     }
 1373:     if ($answer eq 'non_authorized') {
 1374: 	&logthis("User $uname at $udom rejected by $uhome");
 1375: 	return 'no_host';
 1376:     }
 1377:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1378:     return 'no_host';
 1379: }
 1380: 
 1381: sub can_switchserver {
 1382:     my ($udom,$home) = @_;
 1383:     my ($canswitch,@intdoms);
 1384:     my $internet_names = &get_internet_names($home);
 1385:     if (ref($internet_names) eq 'ARRAY') {
 1386:         @intdoms = @{$internet_names};
 1387:     }
 1388:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
 1389:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1390:         $canswitch = 1;
 1391:     } else {
 1392:          my $serverhomeID = &get_server_homeID(&hostname($home));
 1393:          my $serverhomedom = &host_domain($serverhomeID);
 1394:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1395:          my %udomdefaults = &get_domain_defaults($udom);
 1396:          my $remoterev = &get_server_loncaparev('',$home);
 1397:          $canswitch = &can_host_session($udom,$home,$remoterev,
 1398:                                         $udomdefaults{'remotesessions'},
 1399:                                         $defdomdefaults{'hostedsessions'});
 1400:     }
 1401:     return $canswitch;
 1402: }
 1403: 
 1404: sub can_host_session {
 1405:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1406:     my $canhost = 1;
 1407:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1408:     if (ref($remotesessions) eq 'HASH') {
 1409:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1410:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1411:                 $canhost = 0;
 1412:             } else {
 1413:                 $canhost = 1;
 1414:             }
 1415:         }
 1416:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1417:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1418:                 $canhost = 1;
 1419:             } else {
 1420:                 $canhost = 0;
 1421:             }
 1422:         }
 1423:         if ($canhost) {
 1424:             if ($remotesessions->{'version'} ne '') {
 1425:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1426:                 if ($reqmajor ne '' && $reqminor ne '') {
 1427:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1428:                         my $major = $1;
 1429:                         my $minor = $2;
 1430:                         if (($major < $reqmajor ) ||
 1431:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1432:                             $canhost = 0;
 1433:                         }
 1434:                     } else {
 1435:                         $canhost = 0;
 1436:                     }
 1437:                 }
 1438:             }
 1439:         }
 1440:     }
 1441:     if ($canhost) {
 1442:         if (ref($hostedsessions) eq 'HASH') {
 1443:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1444:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1445:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1446:                 if (($uint_dom ne '') && 
 1447:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1448:                     $canhost = 0;
 1449:                 } else {
 1450:                     $canhost = 1;
 1451:                 }
 1452:             }
 1453:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1454:                 if (($uint_dom ne '') && 
 1455:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1456:                     $canhost = 1;
 1457:                 } else {
 1458:                     $canhost = 0;
 1459:                 }
 1460:             }
 1461:         }
 1462:     }
 1463:     return $canhost;
 1464: }
 1465: 
 1466: sub spare_can_host {
 1467:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1468:     my $canhost=1;
 1469:     my $try_server_hostname = &hostname($try_server);
 1470:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1471:     my $serverhomedom = &host_domain($serverhomeID);
 1472:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1473:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1474:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1475:             $canhost = 0;
 1476:         }
 1477:     }
 1478:     if ($canhost) {
 1479:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1480:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1481:                 unless (&shared_institution($udom,$try_server)) {
 1482:                     $canhost = 0;
 1483:                 }
 1484:             }
 1485:         }
 1486:     }
 1487:     if (($canhost) && ($uint_dom)) {
 1488:         my @intdoms;
 1489:         my $internet_names = &get_internet_names($try_server);
 1490:         if (ref($internet_names) eq 'ARRAY') {
 1491:             @intdoms = @{$internet_names};
 1492:         }
 1493:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1494:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1495:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1496:                                          $remotesessions,
 1497:                                          $defdomdefaults{'hostedsessions'});
 1498:         }
 1499:     }
 1500:     return $canhost;
 1501: }
 1502: 
 1503: sub this_host_spares {
 1504:     my ($dom) = @_;
 1505:     my ($dom_in_use,$lonhost_in_use,$result);
 1506:     my @hosts = &current_machine_ids();
 1507:     foreach my $lonhost (@hosts) {
 1508:         if (&host_domain($lonhost) eq $dom) {
 1509:             $dom_in_use = $dom;
 1510:             $lonhost_in_use = $lonhost;
 1511:             last;
 1512:         }
 1513:     }
 1514:     if ($dom_in_use ne '') {
 1515:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1516:     }
 1517:     if (ref($result) ne 'HASH') {
 1518:         $lonhost_in_use = $perlvar{'lonHostID'};
 1519:         $dom_in_use = &host_domain($lonhost_in_use);
 1520:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1521:         if (ref($result) ne 'HASH') {
 1522:             $result = \%spareid;
 1523:         }
 1524:     }
 1525:     return $result;
 1526: }
 1527: 
 1528: sub spares_for_offload  {
 1529:     my ($dom_in_use,$lonhost_in_use) = @_;
 1530:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1531:     if (defined($cached)) {
 1532:         return $result;
 1533:     } else {
 1534:         my $cachetime = 60*60*24;
 1535:         my %domconfig =
 1536:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1537:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1538:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1539:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1540:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1541:                 }
 1542:             }
 1543:         }
 1544:     }
 1545:     return;
 1546: }
 1547: 
 1548: sub get_lonbalancer_config {
 1549:     my ($servers) = @_;
 1550:     my ($currbalancer,$currtargets);
 1551:     if (ref($servers) eq 'HASH') {
 1552:         foreach my $server (keys(%{$servers})) {
 1553:             my %what = (
 1554:                          spareid => 1,
 1555:                          perlvar => 1,
 1556:                        );
 1557:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1558:             if ($result eq 'ok') {
 1559:                 if (ref($returnhash) eq 'HASH') {
 1560:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1561:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1562:                             $currbalancer = $server;
 1563:                             $currtargets = {};
 1564:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1565:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1566:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1567:                                 }
 1568:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1569:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1570:                                 }
 1571:                             }
 1572:                             last;
 1573:                         }
 1574:                     }
 1575:                 }
 1576:             }
 1577:         }
 1578:     }
 1579:     return ($currbalancer,$currtargets);
 1580: }
 1581: 
 1582: sub check_loadbalancing {
 1583:     my ($uname,$udom,$caller) = @_;
 1584:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1585:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1586:     my $lonhost = $perlvar{'lonHostID'};
 1587:     my @hosts = &current_machine_ids();
 1588:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1589:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1590:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1591:     my $serverhomedom = &host_domain($lonhost);
 1592:     my $domneedscache;
 1593:     my $cachetime = 60*60*24;
 1594: 
 1595:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1596:         $dom_in_use = $udom;
 1597:         $homeintdom = 1;
 1598:     } else {
 1599:         $dom_in_use = $serverhomedom;
 1600:     }
 1601:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1602:     unless (defined($cached)) {
 1603:         my %domconfig =
 1604:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1605:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1606:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1607:         } else {
 1608:             $domneedscache = $dom_in_use;
 1609:         }
 1610:     }
 1611:     if (ref($result) eq 'HASH') {
 1612:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1613:             &check_balancer_result($result,@hosts);
 1614:         if ($is_balancer) {
 1615:             if (ref($currrules) eq 'HASH') {
 1616:                 if ($homeintdom) {
 1617:                     if ($uname ne '') {
 1618:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1619:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1620:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1621:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1622:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1623:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1624:                             }
 1625:                         }
 1626:                         if ($rule_in_effect eq '') {
 1627:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1628:                             if ($userenv{'inststatus'} ne '') {
 1629:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1630:                                 my ($othertitle,$usertypes,$types) =
 1631:                                     &Apache::loncommon::sorted_inst_types($udom);
 1632:                                 if (ref($types) eq 'ARRAY') {
 1633:                                     foreach my $type (@{$types}) {
 1634:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1635:                                             if (exists($currrules->{$type})) {
 1636:                                                 $rule_in_effect = $currrules->{$type};
 1637:                                             }
 1638:                                         }
 1639:                                     }
 1640:                                 }
 1641:                             } else {
 1642:                                 if (exists($currrules->{'default'})) {
 1643:                                     $rule_in_effect = $currrules->{'default'};
 1644:                                 }
 1645:                             }
 1646:                         }
 1647:                     } else {
 1648:                         if (exists($currrules->{'default'})) {
 1649:                             $rule_in_effect = $currrules->{'default'};
 1650:                         }
 1651:                     }
 1652:                 } else {
 1653:                     if ($currrules->{'_LC_external'} ne '') {
 1654:                         $rule_in_effect = $currrules->{'_LC_external'};
 1655:                     }
 1656:                 }
 1657:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1658:                                                        $uname,$udom);
 1659:             }
 1660:         }
 1661:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1662:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1663:         unless (defined($cached)) {
 1664:             my %domconfig =
 1665:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1666:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1667:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1668:             } else {
 1669:                 $domneedscache = $serverhomedom;
 1670:             }
 1671:         }
 1672:         if (ref($result) eq 'HASH') {
 1673:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1674:                 &check_balancer_result($result,@hosts);
 1675:             if ($is_balancer) {
 1676:                 if (ref($currrules) eq 'HASH') {
 1677:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1678:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1679:                     }
 1680:                 }
 1681:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1682:                                                        $uname,$udom);
 1683:             }
 1684:         } else {
 1685:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1686:                 $is_balancer = 1;
 1687:                 $offloadto = &this_host_spares($dom_in_use);
 1688:             }
 1689:             unless (defined($cached)) {
 1690:                 $domneedscache = $serverhomedom;
 1691:             }
 1692:         }
 1693:     } else {
 1694:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1695:             $is_balancer = 1;
 1696:             $offloadto = &this_host_spares($dom_in_use);
 1697:         }
 1698:         unless (defined($cached)) {
 1699:             $domneedscache = $serverhomedom;
 1700:         }
 1701:     }
 1702:     if ($domneedscache) {
 1703:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1704:     }
 1705:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1706:         my $lowest_load = 30000;
 1707:         if (ref($offloadto) eq 'HASH') {
 1708:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1709:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1710:                     ($otherserver,$lowest_load) =
 1711:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1712:                 }
 1713:             }
 1714:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1715: 
 1716:             if (!$found_server) {
 1717:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1718:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1719:                         ($otherserver,$lowest_load) =
 1720:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1721:                     }
 1722:                 }
 1723:             }
 1724:         } elsif (ref($offloadto) eq 'ARRAY') {
 1725:             if (@{$offloadto} == 1) {
 1726:                 $otherserver = $offloadto->[0];
 1727:             } elsif (@{$offloadto} > 1) {
 1728:                 foreach my $try_server (@{$offloadto}) {
 1729:                     ($otherserver,$lowest_load) =
 1730:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1731:                 }
 1732:             }
 1733:         }
 1734:         unless ($caller eq 'login') {
 1735:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1736:                 $is_balancer = 0;
 1737:                 if ($uname ne '' && $udom ne '') {
 1738:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1739:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1740:                                  'user.loadbalcheck.time' => time});
 1741:                     }
 1742:                 }
 1743:             }
 1744:         }
 1745:     }
 1746:     if (($is_balancer) && (!$homeintdom)) {
 1747:         undef($setcookie);
 1748:     }
 1749:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1750: }
 1751: 
 1752: sub check_balancer_result {
 1753:     my ($result,@hosts) = @_;
 1754:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1755:     if (ref($result) eq 'HASH') {
 1756:         if ($result->{'lonhost'} ne '') {
 1757:             my $currbalancer = $result->{'lonhost'};
 1758:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1759:                 $is_balancer = 1;
 1760:                 $currtargets = $result->{'targets'};
 1761:                 $currrules = $result->{'rules'};
 1762:             }
 1763:             $dom_balancers = $currbalancer;
 1764:         } else {
 1765:             if (keys(%{$result})) {
 1766:                 foreach my $key (keys(%{$result})) {
 1767:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1768:                         (ref($result->{$key}) eq 'HASH')) {
 1769:                         $is_balancer = 1;
 1770:                         $currrules = $result->{$key}{'rules'};
 1771:                         $currtargets = $result->{$key}{'targets'};
 1772:                         $setcookie = $result->{$key}{'cookie'};
 1773:                         last;
 1774:                     }
 1775:                 }
 1776:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1777:             }
 1778:         }
 1779:     }
 1780:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1781: }
 1782: 
 1783: sub get_loadbalancer_targets {
 1784:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1785:     my $offloadto;
 1786:     if ($rule_in_effect eq 'none') {
 1787:         return [$perlvar{'lonHostID'}];
 1788:     } elsif ($rule_in_effect eq '') {
 1789:         $offloadto = $currtargets;
 1790:     } else {
 1791:         if ($rule_in_effect eq 'homeserver') {
 1792:             my $homeserver = &homeserver($uname,$udom);
 1793:             if ($homeserver ne 'no_host') {
 1794:                 $offloadto = [$homeserver];
 1795:             }
 1796:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1797:             my %domconfig =
 1798:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1799:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1800:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1801:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1802:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1803:                     }
 1804:                 }
 1805:             } else {
 1806:                 my %servers = &internet_dom_servers($udom);
 1807:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1808:                 if (&hostname($remotebalancer) ne '') {
 1809:                     $offloadto = [$remotebalancer];
 1810:                 }
 1811:             }
 1812:         } elsif (&hostname($rule_in_effect) ne '') {
 1813:             $offloadto = [$rule_in_effect];
 1814:         }
 1815:     }
 1816:     return $offloadto;
 1817: }
 1818: 
 1819: sub internet_dom_servers {
 1820:     my ($dom) = @_;
 1821:     my (%uniqservers,%servers);
 1822:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1823:     my @machinedoms = &machine_domains($primaryserver);
 1824:     foreach my $mdom (@machinedoms) {
 1825:         my %currservers = %servers;
 1826:         my %server = &get_servers($mdom);
 1827:         %servers = (%currservers,%server);
 1828:     }
 1829:     my %by_hostname;
 1830:     foreach my $id (keys(%servers)) {
 1831:         push(@{$by_hostname{$servers{$id}}},$id);
 1832:     }
 1833:     foreach my $hostname (sort(keys(%by_hostname))) {
 1834:         if (@{$by_hostname{$hostname}} > 1) {
 1835:             my $match = 0;
 1836:             foreach my $id (@{$by_hostname{$hostname}}) {
 1837:                 if (&host_domain($id) eq $dom) {
 1838:                     $uniqservers{$id} = $hostname;
 1839:                     $match = 1;
 1840:                 }
 1841:             }
 1842:             unless ($match) {
 1843:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1844:             }
 1845:         } else {
 1846:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1847:         }
 1848:     }
 1849:     return %uniqservers;
 1850: }
 1851: 
 1852: sub trusted_domains {
 1853:     my ($cmdtype,$calldom) = @_;
 1854:     my ($trusted,$untrusted);
 1855:     if (&domain($calldom) eq '') {
 1856:         return ($trusted,$untrusted);
 1857:     }
 1858:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1859:         return ($trusted,$untrusted);
 1860:     }
 1861:     my $callprimary = &domain($calldom,'primary');
 1862:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1863:     if ($intcalldom eq '') {
 1864:         return ($trusted,$untrusted);
 1865:     }
 1866: 
 1867:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1868:     unless (defined($cached)) {
 1869:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1870:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1871:         $trustconfig = $domconfig{'trust'};
 1872:     }
 1873:     if (ref($trustconfig)) {
 1874:         my (%possexc,%possinc,@allexc,@allinc); 
 1875:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1876:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1877:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1878:             }
 1879:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1880:                 $possinc{$intcalldom} = 1;
 1881:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1882:             }
 1883:         }
 1884:         if (keys(%possexc)) {
 1885:             if (keys(%possinc)) {
 1886:                 foreach my $key (sort(keys(%possexc))) {
 1887:                     next if ($key eq $intcalldom);
 1888:                     unless ($possinc{$key}) {
 1889:                         push(@allexc,$key);
 1890:                     }
 1891:                 }
 1892:             } else {
 1893:                 @allexc = sort(keys(%possexc));
 1894:             }
 1895:         }
 1896:         if (keys(%possinc)) {
 1897:             $possinc{$intcalldom} = 1;
 1898:             @allinc = sort(keys(%possinc));
 1899:         }
 1900:         if ((@allexc > 0) || (@allinc > 0)) {
 1901:             my %doms_by_intdom;
 1902:             my %allintdoms = &all_host_intdom();
 1903:             my %alldoms = &all_host_domain();
 1904:             foreach my $key (%allintdoms) {
 1905:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1906:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1907:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1908:                     }
 1909:                 } else {
 1910:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1911:                 }
 1912:             }
 1913:             foreach my $exc (@allexc) {
 1914:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1915:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1916:                 }
 1917:             }
 1918:             foreach my $inc (@allinc) {
 1919:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1920:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1921:                 }
 1922:             }
 1923:         }
 1924:     }
 1925:     return ($trusted,$untrusted);
 1926: }
 1927: 
 1928: sub will_trust {
 1929:     my ($cmdtype,$domain,$possdom) = @_;
 1930:     return 1 if ($domain eq $possdom);
 1931:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1932:     my $willtrust; 
 1933:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1934:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1935:             $willtrust = 1;
 1936:         }
 1937:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1938:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1939:             $willtrust = 1;
 1940:         }
 1941:     } else {
 1942:         $willtrust = 1;
 1943:     }
 1944:     return $willtrust;
 1945: }
 1946: 
 1947: # ---------------------- Find the homebase for a user from domain's lib servers
 1948: 
 1949: my %homecache;
 1950: sub homeserver {
 1951:     my ($uname,$udom,$ignoreBadCache)=@_;
 1952:     my $index="$uname:$udom";
 1953: 
 1954:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1955: 
 1956:     my %servers = &get_servers($udom,'library');
 1957:     foreach my $tryserver (keys(%servers)) {
 1958:         next if ($ignoreBadCache ne 'true' && 
 1959: 		 exists($badServerCache{$tryserver}));
 1960: 
 1961: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1962: 	if ($answer eq 'found') {
 1963: 	    delete($badServerCache{$tryserver}); 
 1964: 	    return $homecache{$index}=$tryserver;
 1965: 	} elsif ($answer eq 'no_host') {
 1966: 	    $badServerCache{$tryserver}=1;
 1967: 	}
 1968:     }    
 1969:     return 'no_host';
 1970: }
 1971: 
 1972: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1973: 
 1974: sub idget {
 1975:     my ($udom,$idsref,$namespace)=@_;
 1976:     my %returnhash=();
 1977:     my @ids=(); 
 1978:     if (ref($idsref) eq 'ARRAY') {
 1979:         @ids = @{$idsref};
 1980:     } else {
 1981:         return %returnhash; 
 1982:     }
 1983:     if ($namespace eq '') {
 1984:         $namespace = 'ids';
 1985:     }
 1986:     
 1987:     my %servers = &get_servers($udom,'library');
 1988:     foreach my $tryserver (keys(%servers)) {
 1989: 	my $idlist=join('&', map { &escape($_); } @ids);
 1990: 	if ($namespace eq 'ids') {
 1991: 	    $idlist=~tr/A-Z/a-z/;
 1992: 	}
 1993: 	my $reply;
 1994: 	if ($namespace eq 'ids') {
 1995: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1996: 	} else {
 1997: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1998: 	}
 1999: 	my @answer=();
 2000: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 2001: 	    @answer=split(/\&/,$reply);
 2002: 	}                    ;
 2003: 	my $i;
 2004: 	for ($i=0;$i<=$#ids;$i++) {
 2005: 	    if ($answer[$i]) {
 2006: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 2007: 	    }
 2008: 	}
 2009:     }
 2010:     return %returnhash;
 2011: }
 2012: 
 2013: # ------------------------------------- Find the IDs behind a list of usernames
 2014: 
 2015: sub idrget {
 2016:     my ($udom,@unames)=@_;
 2017:     my %returnhash=();
 2018:     foreach my $uname (@unames) {
 2019:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 2020:     }
 2021:     return %returnhash;
 2022: }
 2023: 
 2024: # Store away a list of names and associated student/employee IDs or clicker IDs
 2025: 
 2026: sub idput {
 2027:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2028:     my %servers=();
 2029:     my %ids=();
 2030:     my %byid = ();
 2031:     if (ref($idsref) eq 'HASH') {
 2032:         %ids=%{$idsref};
 2033:     }
 2034:     if ($namespace eq '') {
 2035:         $namespace = 'ids'; 
 2036:     }
 2037:     foreach my $uname (keys(%ids)) {
 2038: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2039:         if ($uhom eq '') {
 2040:             $uhom=&homeserver($uname,$udom);
 2041:         }
 2042:         if ($uhom ne 'no_host') {
 2043:             my $esc_unam=&escape($uname);
 2044:             if ($namespace eq 'ids') {
 2045:                 my $id=&escape($ids{$uname});
 2046:                 $id=~tr/A-Z/a-z/;
 2047:                 my $esc_unam=&escape($uname);
 2048:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2049:             } else {
 2050:                 my @currids = split(/,/,$ids{$uname});
 2051:                 foreach my $id (@currids) {
 2052:                     $byid{$uhom}{$id} .= $uname.',';
 2053:                 }
 2054:             }
 2055:         }
 2056:     }
 2057:     if ($namespace eq 'clickers') {
 2058:         foreach my $server (keys(%byid)) {
 2059:             if (ref($byid{$server}) eq 'HASH') {
 2060:                 foreach my $id (keys(%{$byid{$server}})) {
 2061:                     $byid{$server} =~ s/,$//;
 2062:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2063:                 }
 2064:             }
 2065:         }
 2066:     }
 2067:     foreach my $server (keys(%servers)) {
 2068:         $servers{$server} =~ s/\&$//;
 2069:         if ($namespace eq 'ids') {     
 2070:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2071:         } else {
 2072:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2073:         }
 2074:     }
 2075: }
 2076: 
 2077: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2078: 
 2079: sub iddel {
 2080:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2081:     my %result=();
 2082:     my %ids=();
 2083:     my %byid = ();
 2084:     if (ref($idshashref) eq 'HASH') {
 2085:         %ids=%{$idshashref};
 2086:     } else {
 2087:         return %result;
 2088:     }
 2089:     if ($namespace eq '') {
 2090:         $namespace = 'ids';
 2091:     }
 2092:     my %servers=();
 2093:     while (my ($id,$unamestr) = each(%ids)) {
 2094:         if ($namespace eq 'ids') {
 2095:             my $uhom = $uhome;
 2096:             if ($uhom eq '') { 
 2097:                 $uhom=&homeserver($unamestr,$udom);
 2098:             }
 2099:             if ($uhom ne 'no_host') {
 2100:                 $servers{$uhom}.='&'.&escape($id);
 2101:             }
 2102:          } else {
 2103:             my @curritems = split(/,/,$ids{$id});
 2104:             foreach my $uname (@curritems) {
 2105:                 my $uhom = $uhome;
 2106:                 if ($uhom eq '') {
 2107:                     $uhom=&homeserver($uname,$udom);
 2108:                 }
 2109:                 if ($uhom ne 'no_host') { 
 2110:                     $byid{$uhom}{$id} .= $uname.',';
 2111:                 }
 2112:             }
 2113:         }
 2114:     }
 2115:     if ($namespace eq 'clickers') {
 2116:         foreach my $server (keys(%byid)) {
 2117:             if (ref($byid{$server}) eq 'HASH') {
 2118:                 foreach my $id (keys(%{$byid{$server}})) {
 2119:                     $byid{$server}{$id} =~ s/,$//;
 2120:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2121:                 }
 2122:             }
 2123:         }
 2124:     }
 2125:     foreach my $server (keys(%servers)) {
 2126:         $servers{$server} =~ s/\&$//;
 2127:         if ($namespace eq 'ids') {
 2128:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2129:         } elsif ($namespace eq 'clickers') {
 2130:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2131:         }
 2132:     }
 2133:     return %result;
 2134: }
 2135: 
 2136: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2137: 
 2138: sub updateclickers {
 2139:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2140:     my %clickers;
 2141:     if (ref($idshashref) eq 'HASH') {
 2142:         %clickers=%{$idshashref};
 2143:     } else {
 2144:         return;
 2145:     }
 2146:     my $items='';
 2147:     foreach my $item (keys(%clickers)) {
 2148:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2149:     }
 2150:     $items=~s/\&$//;
 2151:     my $request = "updateclickers:$udom:$action:$items";
 2152:     if ($critical) {
 2153:         return &critical($request,$uhome);
 2154:     } else {
 2155:         return &reply($request,$uhome);
 2156:     }
 2157: }
 2158: 
 2159: # ------------------------------dump from db file owned by domainconfig user
 2160: sub dump_dom {
 2161:     my ($namespace, $udom, $regexp) = @_;
 2162: 
 2163:     $udom ||= $env{'user.domain'};
 2164: 
 2165:     return () unless $udom;
 2166: 
 2167:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2168: }
 2169: 
 2170: # ------------------------------------------ get items from domain db files   
 2171: 
 2172: sub get_dom {
 2173:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2174:     return if ($udom eq 'public');
 2175:     my $items='';
 2176:     foreach my $item (@$storearr) {
 2177:         $items.=&escape($item).'&';
 2178:     }
 2179:     $items=~s/\&$//;
 2180:     if (!$udom) {
 2181:         $udom=$env{'user.domain'};
 2182:         return if ($udom eq 'public');
 2183:         if (defined(&domain($udom,'primary'))) {
 2184:             $uhome=&domain($udom,'primary');
 2185:         } else {
 2186:             undef($uhome);
 2187:         }
 2188:     } else {
 2189:         if (!$uhome) {
 2190:             if (defined(&domain($udom,'primary'))) {
 2191:                 $uhome=&domain($udom,'primary');
 2192:             }
 2193:         }
 2194:     }
 2195:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2196:         my $rep;
 2197:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2198:             # domain information is hosted on this machine
 2199:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2200:         } else {
 2201:             if ($encrypt) {
 2202:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2203:             } else {
 2204:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2205:             }
 2206:         }
 2207:         my %returnhash;
 2208:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2209:             return %returnhash;
 2210:         }
 2211:         my @pairs=split(/\&/,$rep);
 2212:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2213:             return @pairs;
 2214:         }
 2215:         my $i=0;
 2216:         foreach my $item (@$storearr) {
 2217:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2218:             $i++;
 2219:         }
 2220:         return %returnhash;
 2221:     } else {
 2222:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2223:     }
 2224: }
 2225: 
 2226: # -------------------------------------------- put items in domain db files 
 2227: 
 2228: sub put_dom {
 2229:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2230:     if (!$udom) {
 2231:         $udom=$env{'user.domain'};
 2232:         if (defined(&domain($udom,'primary'))) {
 2233:             $uhome=&domain($udom,'primary');
 2234:         } else {
 2235:             undef($uhome);
 2236:         }
 2237:     } else {
 2238:         if (!$uhome) {
 2239:             if (defined(&domain($udom,'primary'))) {
 2240:                 $uhome=&domain($udom,'primary');
 2241:             }
 2242:         }
 2243:     } 
 2244:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2245:         my $items='';
 2246:         foreach my $item (keys(%$storehash)) {
 2247:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2248:         }
 2249:         $items=~s/\&$//;
 2250:         if ($encrypt) {
 2251:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2252:         } else {
 2253:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2254:         }
 2255:     } else {
 2256:         &logthis("put_dom failed - no homeserver and/or domain");
 2257:     }
 2258: }
 2259: 
 2260: # --------------------- newput for items in db file owned by domainconfig user
 2261: sub newput_dom {
 2262:     my ($namespace,$storehash,$udom) = @_;
 2263:     my $result;
 2264:     if (!$udom) {
 2265:         $udom=$env{'user.domain'};
 2266:     }
 2267:     if ($udom) {
 2268:         my $uname = &get_domainconfiguser($udom);
 2269:         $result = &newput($namespace,$storehash,$udom,$uname);
 2270:     }
 2271:     return $result;
 2272: }
 2273: 
 2274: # --------------------- delete for items in db file owned by domainconfig user
 2275: sub del_dom {
 2276:     my ($namespace,$storearr,$udom)=@_;
 2277:     if (ref($storearr) eq 'ARRAY') {
 2278:         if (!$udom) {
 2279:             $udom=$env{'user.domain'};
 2280:         }
 2281:         if ($udom) {
 2282:             my $uname = &get_domainconfiguser($udom); 
 2283:             return &del($namespace,$storearr,$udom,$uname);
 2284:         }
 2285:     }
 2286: }
 2287: 
 2288: sub store_dom {
 2289:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
 2290:     $$storehash{'ip'}=&get_requestor_ip();
 2291:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2292:     my $namevalue='';
 2293:     foreach my $key (keys(%{$storehash})) {
 2294:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2295:     }
 2296:     $namevalue=~s/\&$//;
 2297:     if (grep { $_ eq $home } current_machine_ids()) {
 2298:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
 2299:     } else {
 2300:         if ($namespace eq 'private') {
 2301:             return 'refused';
 2302:         } elsif ($encrypt) {
 2303:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
 2304:         } else {
 2305:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
 2306:         }
 2307:     }
 2308: }
 2309: 
 2310: sub restore_dom {
 2311:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
 2312:     my $answer;
 2313:     if (grep { $_ eq $home } current_machine_ids()) {
 2314:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
 2315:     } elsif ($namespace ne 'private') {
 2316:         if ($encrypt) {
 2317:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
 2318:         } else {
 2319:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
 2320:         }
 2321:     }
 2322:     my %returnhash=();
 2323:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
 2324:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
 2325:         foreach my $line (split(/\&/,$answer)) {
 2326:             my ($name,$value)=split(/\=/,$line);
 2327:             $returnhash{&unescape($name)}=&thaw_unescape($value);
 2328:         }
 2329:         my $version;
 2330:         for ($version=1;$version<=$returnhash{'version'};$version++) {
 2331:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2332:                 $returnhash{$item}=$returnhash{$version.':'.$item};
 2333:             }
 2334:         }
 2335:     }
 2336:     return %returnhash;
 2337: }
 2338: 
 2339: # ----------------------------------construct domainconfig user for a domain 
 2340: sub get_domainconfiguser {
 2341:     my ($udom) = @_;
 2342:     return $udom.'-domainconfig';
 2343: }
 2344: 
 2345: sub retrieve_inst_usertypes {
 2346:     my ($udom) = @_;
 2347:     my (%returnhash,@order);
 2348:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2349:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2350:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2351:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2352:     } else {
 2353:         if (defined(&domain($udom,'primary'))) {
 2354:             my $uhome=&domain($udom,'primary');
 2355:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2356:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2357:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2358:                 return (\%returnhash,\@order);
 2359:             }
 2360:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2361:             my @pairs=split(/\&/,$hashitems);
 2362:             foreach my $item (@pairs) {
 2363:                 my ($key,$value)=split(/=/,$item,2);
 2364:                 $key = &unescape($key);
 2365:                 next if ($key =~ /^error: 2 /);
 2366:                 $returnhash{$key}=&thaw_unescape($value);
 2367:             }
 2368:             my @esc_order = split(/\&/,$orderitems);
 2369:             foreach my $item (@esc_order) {
 2370:                 push(@order,&unescape($item));
 2371:             }
 2372:         } else {
 2373:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2374:         }
 2375:         return (\%returnhash,\@order);
 2376:     }
 2377: }
 2378: 
 2379: sub is_domainimage {
 2380:     my ($url) = @_;
 2381:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2382:         if (&domain($1) ne '') {
 2383:             return '1';
 2384:         }
 2385:     }
 2386:     return;
 2387: }
 2388: 
 2389: sub inst_directory_query {
 2390:     my ($srch) = @_;
 2391:     my $udom = $srch->{'srchdomain'};
 2392:     my %results;
 2393:     my $homeserver = &domain($udom,'primary');
 2394:     my $outcome;
 2395:     if ($homeserver ne '') {
 2396:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2397:             if ($srch->{'srchby'} eq 'email') {
 2398:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2399:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2400:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2401:                     (($major == 2) && ($minor < 12))) {
 2402:                     return;
 2403:                 }
 2404:             }
 2405:         }
 2406: 	my $queryid=&reply("querysend:instdirsearch:".
 2407: 			   &escape($srch->{'srchby'}).':'.
 2408: 			   &escape($srch->{'srchterm'}).':'.
 2409: 			   &escape($srch->{'srchtype'}),$homeserver);
 2410: 	my $host=&hostname($homeserver);
 2411: 	if ($queryid !~/^\Q$host\E\_/) {
 2412: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2413: 	    return;
 2414: 	}
 2415: 	my $response = &get_query_reply($queryid);
 2416: 	my $maxtries = 5;
 2417: 	my $tries = 1;
 2418: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2419: 	    $response = &get_query_reply($queryid);
 2420: 	    $tries ++;
 2421: 	}
 2422: 
 2423:         if (!&error($response) && $response ne 'refused') {
 2424:             if ($response eq 'unavailable') {
 2425:                 $outcome = $response;
 2426:             } else {
 2427:                 $outcome = 'ok';
 2428:                 my @matches = split(/\n/,$response);
 2429:                 foreach my $match (@matches) {
 2430:                     my ($key,$value) = split(/=/,$match);
 2431:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2432:                 }
 2433:             }
 2434:         }
 2435:     }
 2436:     return ($outcome,%results);
 2437: }
 2438: 
 2439: sub usersearch {
 2440:     my ($srch) = @_;
 2441:     my $dom = $srch->{'srchdomain'};
 2442:     my %results;
 2443:     my %libserv = &all_library();
 2444:     my $query = 'usersearch';
 2445:     foreach my $tryserver (keys(%libserv)) {
 2446:         if (&host_domain($tryserver) eq $dom) {
 2447:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2448:                 if ($srch->{'srchby'} eq 'email') {
 2449:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2450:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2451:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2452:                              (($major == 2) && ($minor < 12)));
 2453:                 }
 2454:             }
 2455:             my $host=&hostname($tryserver);
 2456:             my $queryid=
 2457:                 &reply("querysend:".&escape($query).':'.
 2458:                        &escape($srch->{'srchby'}).':'.
 2459:                        &escape($srch->{'srchtype'}).':'.
 2460:                        &escape($srch->{'srchterm'}),$tryserver);
 2461:             if ($queryid !~/^\Q$host\E\_/) {
 2462:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2463:                 next;
 2464:             }
 2465:             my $reply = &get_query_reply($queryid);
 2466:             my $maxtries = 1;
 2467:             my $tries = 1;
 2468:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2469:                 $reply = &get_query_reply($queryid);
 2470:                 $tries ++;
 2471:             }
 2472:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2473:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2474:             } else {
 2475:                 my @matches;
 2476:                 if ($reply =~ /\n/) {
 2477:                     @matches = split(/\n/,$reply);
 2478:                 } else {
 2479:                     @matches = split(/\&/,$reply);
 2480:                 }
 2481:                 foreach my $match (@matches) {
 2482:                     my ($uname,$udom,%userhash);
 2483:                     foreach my $entry (split(/:/,$match)) {
 2484:                         my ($key,$value) =
 2485:                             map {&unescape($_);} split(/=/,$entry);
 2486:                         $userhash{$key} = $value;
 2487:                         if ($key eq 'username') {
 2488:                             $uname = $value;
 2489:                         } elsif ($key eq 'domain') {
 2490:                             $udom = $value;
 2491:                         }
 2492:                     }
 2493:                     $results{$uname.':'.$udom} = \%userhash;
 2494:                 }
 2495:             }
 2496:         }
 2497:     }
 2498:     return %results;
 2499: }
 2500: 
 2501: sub get_instuser {
 2502:     my ($udom,$uname,$id) = @_;
 2503:     my $homeserver = &domain($udom,'primary');
 2504:     my ($outcome,%results);
 2505:     if ($homeserver ne '') {
 2506:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2507:                            &escape($id).':'.&escape($udom),$homeserver);
 2508:         my $host=&hostname($homeserver);
 2509:         if ($queryid !~/^\Q$host\E\_/) {
 2510:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2511:             return;
 2512:         }
 2513:         my $response = &get_query_reply($queryid);
 2514:         my $maxtries = 5;
 2515:         my $tries = 1;
 2516:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2517:             $response = &get_query_reply($queryid);
 2518:             $tries ++;
 2519:         }
 2520:         if (!&error($response) && $response ne 'refused') {
 2521:             if ($response eq 'unavailable') {
 2522:                 $outcome = $response;
 2523:             } else {
 2524:                 $outcome = 'ok';
 2525:                 my @matches = split(/\n/,$response);
 2526:                 foreach my $match (@matches) {
 2527:                     my ($key,$value) = split(/=/,$match);
 2528:                     $results{&unescape($key)} = &thaw_unescape($value);
 2529:                 }
 2530:             }
 2531:         }
 2532:     }
 2533:     my %userinfo;
 2534:     if (ref($results{$uname}) eq 'HASH') {
 2535:         %userinfo = %{$results{$uname}};
 2536:     } 
 2537:     return ($outcome,%userinfo);
 2538: }
 2539: 
 2540: sub get_multiple_instusers {
 2541:     my ($udom,$users,$caller) = @_;
 2542:     my ($outcome,$results);
 2543:     if (ref($users) eq 'HASH') {
 2544:         my $count = keys(%{$users}); 
 2545:         my $requested = &freeze_escape($users);
 2546:         my $homeserver = &domain($udom,'primary');
 2547:         if ($homeserver ne '') {
 2548:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2549:             my $host=&hostname($homeserver);
 2550:             if ($queryid !~/^\Q$host\E\_/) {
 2551:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2552:                          ' for host: '.$homeserver.'in domain '.$udom);
 2553:                 return ($outcome,$results);
 2554:             }
 2555:             my $response = &get_query_reply($queryid);
 2556:             my $maxtries = 5;
 2557:             if ($count > 100) {
 2558:                 $maxtries = 1+int($count/20);
 2559:             }
 2560:             my $tries = 1;
 2561:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2562:                 $response = &get_query_reply($queryid);
 2563:                 $tries ++;
 2564:             }
 2565:             if ($response eq '') {
 2566:                 $results = {};
 2567:                 foreach my $key (keys(%{$users})) {
 2568:                     my ($uname,$id);
 2569:                     if ($caller eq 'id') {
 2570:                         $id = $key;
 2571:                     } else {
 2572:                         $uname = $key;
 2573:                     }
 2574:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2575:                     $outcome = $resp;
 2576:                     if ($resp eq 'ok') {
 2577:                         %{$results} = (%{$results}, %info);
 2578:                     } else {
 2579:                         last;
 2580:                     }
 2581:                 }
 2582:             } elsif(!&error($response) && ($response ne 'refused')) {
 2583:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2584:                     $outcome = $response;
 2585:                 } else {
 2586:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2587:                     if ($outcome eq 'ok') {
 2588:                         $results = &thaw_unescape($userdata); 
 2589:                     }
 2590:                 }
 2591:             }
 2592:         }
 2593:     }
 2594:     return ($outcome,$results);
 2595: }
 2596: 
 2597: sub inst_rulecheck {
 2598:     my ($udom,$uname,$id,$item,$rules) = @_;
 2599:     my %returnhash;
 2600:     if ($udom ne '') {
 2601:         if (ref($rules) eq 'ARRAY') {
 2602:             @{$rules} = map {&escape($_);} (@{$rules});
 2603:             my $rulestr = join(':',@{$rules});
 2604:             my $homeserver=&domain($udom,'primary');
 2605:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2606:                 my $response;
 2607:                 if ($item eq 'username') {                
 2608:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2609:                                               ':'.&escape($uname).':'.$rulestr,
 2610:                                               $homeserver));
 2611:                 } elsif ($item eq 'id') {
 2612:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2613:                                               ':'.&escape($id).':'.$rulestr,
 2614:                                               $homeserver));
 2615:                 } elsif ($item eq 'selfcreate') {
 2616:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2617:                                                &escape($udom).':'.&escape($uname).
 2618:                                               ':'.$rulestr,$homeserver));
 2619:                 } elsif ($item eq 'unamemap') {
 2620:                     $response=&unescape(&reply('instunamemapcheck:'.
 2621:                                                &escape($udom).':'.&escape($uname).
 2622:                                               ':'.$rulestr,$homeserver));
 2623:                 }
 2624:                 if ($response ne 'refused') {
 2625:                     my @pairs=split(/\&/,$response);
 2626:                     foreach my $item (@pairs) {
 2627:                         my ($key,$value)=split(/=/,$item,2);
 2628:                         $key = &unescape($key);
 2629:                         next if ($key =~ /^error: 2 /);
 2630:                         $returnhash{$key}=&thaw_unescape($value);
 2631:                     }
 2632:                 }
 2633:             }
 2634:         }
 2635:     }
 2636:     return %returnhash;
 2637: }
 2638: 
 2639: sub inst_userrules {
 2640:     my ($udom,$check) = @_;
 2641:     my (%ruleshash,@ruleorder);
 2642:     if ($udom ne '') {
 2643:         my $homeserver=&domain($udom,'primary');
 2644:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2645:             my $response;
 2646:             if ($check eq 'id') {
 2647:                 $response=&reply('instidrules:'.&escape($udom),
 2648:                                  $homeserver);
 2649:             } elsif ($check eq 'email') {
 2650:                 $response=&reply('instemailrules:'.&escape($udom),
 2651:                                  $homeserver);
 2652:             } elsif ($check eq 'unamemap') {
 2653:                 $response=&reply('unamemaprules:'.&escape($udom),
 2654:                                  $homeserver); 
 2655:             } else {
 2656:                 $response=&reply('instuserrules:'.&escape($udom),
 2657:                                  $homeserver);
 2658:             }
 2659:             if (($response ne 'refused') && ($response ne 'error') && 
 2660:                 ($response ne 'unknown_cmd') && 
 2661:                 ($response ne 'no_such_host')) {
 2662:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2663:                 my @pairs=split(/\&/,$hashitems);
 2664:                 foreach my $item (@pairs) {
 2665:                     my ($key,$value)=split(/=/,$item,2);
 2666:                     $key = &unescape($key);
 2667:                     next if ($key =~ /^error: 2 /);
 2668:                     $ruleshash{$key}=&thaw_unescape($value);
 2669:                 }
 2670:                 my @esc_order = split(/\&/,$orderitems);
 2671:                 foreach my $item (@esc_order) {
 2672:                     push(@ruleorder,&unescape($item));
 2673:                 }
 2674:             }
 2675:         }
 2676:     }
 2677:     return (\%ruleshash,\@ruleorder);
 2678: }
 2679: 
 2680: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2681: 
 2682: sub get_domain_defaults {
 2683:     my ($domain,$ignore_cache) = @_;
 2684:     return if (($domain eq '') || ($domain eq 'public'));
 2685:     my $cachetime = 60*60*24;
 2686:     unless ($ignore_cache) {
 2687:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2688:         if (defined($cached)) {
 2689:             if (ref($result) eq 'HASH') {
 2690:                 return %{$result};
 2691:             }
 2692:         }
 2693:     }
 2694:     my %domdefaults;
 2695:     my %domconfig =
 2696:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2697:                                   'requestcourses','inststatus',
 2698:                                   'coursedefaults','usersessions',
 2699:                                   'requestauthor','selfenrollment',
 2700:                                   'coursecategories','ssl','autoenroll',
 2701:                                   'trust','helpsettings','wafproxy','ltisec'],$domain);
 2702:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2703:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2704:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2705:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2706:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2707:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2708:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2709:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2710:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2711:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2712:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2713:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2714:     } else {
 2715:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2716:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2717:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2718:     }
 2719:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2720:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2721:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2722:         } else {
 2723:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2724:         }
 2725:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2726:         foreach my $item (@usertools) {
 2727:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2728:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2729:             }
 2730:         }
 2731:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2732:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2733:         }
 2734:     }
 2735:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2736:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2737:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2738:         }
 2739:     }
 2740:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2741:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2742:     }
 2743:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2744:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2745:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2746:         }
 2747:     }
 2748:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2749:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2750:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2751:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2752:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2753:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2754:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2755:         }
 2756:         foreach my $type (@coursetypes) {
 2757:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2758:                 unless ($type eq 'community') {
 2759:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2760:                 }
 2761:             }
 2762:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2763:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2764:             }
 2765:             if ($domdefaults{'postsubmit'} eq 'on') {
 2766:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2767:                     $domdefaults{$type.'postsubtimeout'} = 
 2768:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2769:                 }
 2770:             }
 2771:         }
 2772:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2773:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2774:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2775:                 if (@clonecodes) {
 2776:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2777:                 }
 2778:             }
 2779:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2780:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2781:         }
 2782:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2783:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2784:         }
 2785:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2786:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2787:         }
 2788:     }
 2789:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2790:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2791:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2792:         }
 2793:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2794:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2795:         }
 2796:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2797:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2798:         }
 2799:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2800:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2801:         }
 2802:     }
 2803:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2804:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2805:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2806:                             'approval','limit');
 2807:             foreach my $type (@coursetypes) {
 2808:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2809:                     my @mgrdc = ();
 2810:                     foreach my $item (@settings) {
 2811:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2812:                             push(@mgrdc,$item);
 2813:                         }
 2814:                     }
 2815:                     if (@mgrdc) {
 2816:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2817:                     }
 2818:                 }
 2819:             }
 2820:         }
 2821:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2822:             foreach my $type (@coursetypes) {
 2823:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2824:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2825:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2826:                     }
 2827:                 }
 2828:             }
 2829:         }
 2830:     }
 2831:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2832:         $domdefaults{'catauth'} = 'std';
 2833:         $domdefaults{'catunauth'} = 'std';
 2834:         if ($domconfig{'coursecategories'}{'auth'}) {
 2835:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2836:         }
 2837:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2838:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2839:         }
 2840:     }
 2841:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2842:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2843:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2844:         }
 2845:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2846:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2847:         }
 2848:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2849:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2850:         }
 2851:     }
 2852:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2853:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2854:         foreach my $prefix (@prefixes) {
 2855:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2856:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2857:             }
 2858:         }
 2859:     }
 2860:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2861:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2862:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2863:     }
 2864:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2865:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2866:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2867:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2868:         }
 2869:     }
 2870:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2871:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2872:             if ($domconfig{'wafproxy'}{$item}) {
 2873:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2874:             }
 2875:         }
 2876:     }
 2877:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2878:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2879:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2880:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2881:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2882:         }
 2883:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2884:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2885:                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2886:             }
 2887:         }
 2888:     }
 2889:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2890:     return %domdefaults;
 2891: }
 2892: 
 2893: sub get_dom_cats {
 2894:     my ($dom) = @_;
 2895:     return unless (&domain($dom));
 2896:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2897:     unless (defined($cached)) {
 2898:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2899:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2900:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2901:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2902:             } else {
 2903:                 $cats = {};
 2904:             }
 2905:         } else {
 2906:             $cats = {};
 2907:         }
 2908:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2909:     }
 2910:     return $cats;
 2911: }
 2912: 
 2913: sub get_dom_instcats {
 2914:     my ($dom) = @_;
 2915:     return unless (&domain($dom));
 2916:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2917:     unless (defined($cached)) {
 2918:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2919:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2920:         if ($totcodes > 0) {
 2921:             my $caller = 'global';
 2922:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2923:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2924:                 $instcats = {
 2925:                                 codes => \%codes,
 2926:                                 codetitles => \@codetitles,
 2927:                                 cat_titles => \%cat_titles,
 2928:                                 cat_order => \%cat_order,
 2929:                             };
 2930:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2931:             }
 2932:         }
 2933:     }
 2934:     return $instcats;
 2935: }
 2936: 
 2937: sub retrieve_instcodes {
 2938:     my ($coursecodes,$dom) = @_;
 2939:     my $totcodes;
 2940:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2941:     foreach my $course (keys(%courses)) {
 2942:         if (ref($courses{$course}) eq 'HASH') {
 2943:             if ($courses{$course}{'inst_code'} ne '') {
 2944:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2945:                 $totcodes ++;
 2946:             }
 2947:         }
 2948:     }
 2949:     return $totcodes;
 2950: }
 2951: 
 2952: sub course_portal_url {
 2953:     my ($cnum,$cdom,$r) = @_;
 2954:     my $chome = &homeserver($cnum,$cdom);
 2955:     my $hostname = &hostname($chome);
 2956:     my $protocol = $protocol{$chome};
 2957:     $protocol = 'http' if ($protocol ne 'https');
 2958:     my %domdefaults = &get_domain_defaults($cdom);
 2959:     my $firsturl;
 2960:     if ($domdefaults{'portal_def'}) {
 2961:         $firsturl = $domdefaults{'portal_def'};
 2962:     } else {
 2963:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
 2964:         $hostname = $alias if ($alias ne '');
 2965:         $firsturl = $protocol.'://'.$hostname;
 2966:     }
 2967:     return $firsturl;
 2968: }
 2969: 
 2970: # --------------------------------------------- Get domain config for passwords
 2971: 
 2972: sub get_passwdconf {
 2973:     my ($dom) = @_;
 2974:     my (%passwdconf,$gotconf,$lookup);
 2975:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2976:     if (defined($cached)) {
 2977:         if (ref($result) eq 'HASH') {
 2978:             %passwdconf = %{$result};
 2979:             $gotconf = 1;
 2980:         }
 2981:     }
 2982:     unless ($gotconf) {
 2983:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2984:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2985:             %passwdconf = %{$domconfig{'passwords'}};
 2986:         }
 2987:         my $cachetime = 24*60*60;
 2988:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2989:     }
 2990:     return %passwdconf;
 2991: }
 2992: 
 2993: # --------------------------------------------------- Assign a key to a student
 2994: 
 2995: sub assign_access_key {
 2996: #
 2997: # a valid key looks like uname:udom#comments
 2998: # comments are being appended
 2999: #
 3000:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3001:     $kdom=
 3002:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3003:     $knum=
 3004:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3005:     $cdom=
 3006:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3007:     $cnum=
 3008:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3009:     $udom=$env{'user.name'} unless (defined($udom));
 3010:     $uname=$env{'user.domain'} unless (defined($uname));
 3011:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3012:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3013:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3014:                                                   # assigned to this person
 3015:                                                   # - this should not happen,
 3016:                                                   # unless something went wrong
 3017:                                                   # the first time around
 3018: # ready to assign
 3019:         $logentry=$1.'; '.$logentry;
 3020:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3021:                                                  $kdom,$knum) eq 'ok') {
 3022: # key now belongs to user
 3023: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3024:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3025:                 &appenv({'environment.'.$envkey => $ckey});
 3026:                 return 'ok';
 3027:             } else {
 3028:                 return 
 3029:   'error: Count not permanently assign key, will need to be re-entered later.';
 3030: 	    }
 3031:         } else {
 3032:             return 'error: Could not assign key, try again later.';
 3033:         }
 3034:     } elsif (!$existing{$ckey}) {
 3035: # the key does not exist
 3036: 	return 'error: The key does not exist';
 3037:     } else {
 3038: # the key is somebody else's
 3039: 	return 'error: The key is already in use';
 3040:     }
 3041: }
 3042: 
 3043: # ------------------------------------------ put an additional comment on a key
 3044: 
 3045: sub comment_access_key {
 3046: #
 3047: # a valid key looks like uname:udom#comments
 3048: # comments are being appended
 3049: #
 3050:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3051:     $cdom=
 3052:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3053:     $cnum=
 3054:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3055:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3056:     if ($existing{$ckey}) {
 3057:         $existing{$ckey}.='; '.$logentry;
 3058: # ready to assign
 3059:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3060:                                                  $cdom,$cnum) eq 'ok') {
 3061: 	    return 'ok';
 3062:         } else {
 3063: 	    return 'error: Count not store comment.';
 3064:         }
 3065:     } else {
 3066: # the key does not exist
 3067: 	return 'error: The key does not exist';
 3068:     }
 3069: }
 3070: 
 3071: # ------------------------------------------------------ Generate a set of keys
 3072: 
 3073: sub generate_access_keys {
 3074:     my ($number,$cdom,$cnum,$logentry)=@_;
 3075:     $cdom=
 3076:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3077:     $cnum=
 3078:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3079:     unless (&allowed('mky',$cdom)) { return 0; }
 3080:     unless (($cdom) && ($cnum)) { return 0; }
 3081:     if ($number>10000) { return 0; }
 3082:     sleep(2); # make sure don't get same seed twice
 3083:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3084:     my $total=0;
 3085:     for (my $i=1;$i<=$number;$i++) {
 3086:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3087:                   sprintf("%lx",int(100000*rand)).'-'.
 3088:                   sprintf("%lx",int(100000*rand));
 3089:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3090:        $newkey=~s/0/h/g; # and also 0 and O
 3091:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3092:        if ($existing{$newkey}) {
 3093:            $i--;
 3094:        } else {
 3095: 	  if (&put('accesskeys',
 3096:               { $newkey => '# generated '.localtime().
 3097:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3098:                            '; '.$logentry },
 3099: 		   $cdom,$cnum) eq 'ok') {
 3100:               $total++;
 3101: 	  }
 3102:        }
 3103:     }
 3104:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3105:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3106:     return $total;
 3107: }
 3108: 
 3109: # ------------------------------------------------------- Validate an accesskey
 3110: 
 3111: sub validate_access_key {
 3112:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3113:     $cdom=
 3114:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3115:     $cnum=
 3116:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3117:     $udom=$env{'user.domain'} unless (defined($udom));
 3118:     $uname=$env{'user.name'} unless (defined($uname));
 3119:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3120:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3121: }
 3122: 
 3123: # ------------------------------------- Find the section of student in a course
 3124: sub devalidate_getsection_cache {
 3125:     my ($udom,$unam,$courseid)=@_;
 3126:     my $hashid="$udom:$unam:$courseid";
 3127:     &devalidate_cache_new('getsection',$hashid);
 3128: }
 3129: 
 3130: sub courseid_to_courseurl {
 3131:     my ($courseid) = @_;
 3132:     #already url style courseid
 3133:     return $courseid if ($courseid =~ m{^/});
 3134: 
 3135:     if (exists($env{'course.'.$courseid.'.num'})) {
 3136: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3137: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3138: 	return "/$cdom/$cnum";
 3139:     }
 3140: 
 3141:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3142:     if (exists($courseinfo{'num'})) {
 3143: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3144:     }
 3145: 
 3146:     return undef;
 3147: }
 3148: 
 3149: sub getsection {
 3150:     my ($udom,$unam,$courseid)=@_;
 3151:     my $cachetime=1800;
 3152: 
 3153:     my $hashid="$udom:$unam:$courseid";
 3154:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3155:     if (defined($cached)) { return $result; }
 3156: 
 3157:     my %Pending; 
 3158:     my %Expired;
 3159:     #
 3160:     # Each role can either have not started yet (pending), be active, 
 3161:     #    or have expired.
 3162:     #
 3163:     # If there is an active role, we are done.
 3164:     #
 3165:     # If there is more than one role which has not started yet, 
 3166:     #     choose the one which will start sooner
 3167:     # If there is one role which has not started yet, return it.
 3168:     #
 3169:     # If there is more than one expired role, choose the one which ended last.
 3170:     # If there is a role which has expired, return it.
 3171:     #
 3172:     $courseid = &courseid_to_courseurl($courseid);
 3173:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3174:     foreach my $key (keys(%roleshash)) {
 3175:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3176:         my $section=$1;
 3177:         if ($key eq $courseid.'_st') { $section=''; }
 3178:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3179:         my $now=time;
 3180:         if (defined($end) && $end && ($now > $end)) {
 3181:             $Expired{$end}=$section;
 3182:             next;
 3183:         }
 3184:         if (defined($start) && $start && ($now < $start)) {
 3185:             $Pending{$start}=$section;
 3186:             next;
 3187:         }
 3188:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3189:     }
 3190:     #
 3191:     # Presumedly there will be few matching roles from the above
 3192:     # loop and the sorting time will be negligible.
 3193:     if (scalar(keys(%Pending))) {
 3194:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3195:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3196:     } 
 3197:     if (scalar(keys(%Expired))) {
 3198:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3199:         my $time = pop(@sorted);
 3200:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3201:     }
 3202:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3203: }
 3204: 
 3205: sub save_cache {
 3206:     &purge_remembered();
 3207:     #&Apache::loncommon::validate_page();
 3208:     undef(%env);
 3209:     undef($env_loaded);
 3210: }
 3211: 
 3212: my $to_remember=-1;
 3213: my %remembered;
 3214: my %accessed;
 3215: my $kicks=0;
 3216: my $hits=0;
 3217: sub make_key {
 3218:     my ($name,$id) = @_;
 3219:     if (length($id) > 65 
 3220: 	&& length(&escape($id)) > 200) {
 3221: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3222:     }
 3223:     return &escape($name.':'.$id);
 3224: }
 3225: 
 3226: sub devalidate_cache_new {
 3227:     my ($name,$id,$debug) = @_;
 3228:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3229:     my $remembered_id=$name.':'.$id;
 3230:     $id=&make_key($name,$id);
 3231:     $memcache->delete($id);
 3232:     delete($remembered{$remembered_id});
 3233:     delete($accessed{$remembered_id});
 3234: }
 3235: 
 3236: sub is_cached_new {
 3237:     my ($name,$id,$debug) = @_;
 3238:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3239:     if (exists($remembered{$remembered_id})) {
 3240: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3241: 	$accessed{$remembered_id}=[&gettimeofday()];
 3242: 	$hits++;
 3243: 	return ($remembered{$remembered_id},1);
 3244:     }
 3245:     $id=&make_key($name,$id);
 3246:     my $value = $memcache->get($id);
 3247:     if (!(defined($value))) {
 3248: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3249: 	return (undef,undef);
 3250:     }
 3251:     if ($value eq '__undef__') {
 3252: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3253: 	$value=undef;
 3254:     }
 3255:     &make_room($remembered_id,$value,$debug);
 3256:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3257:     return ($value,1);
 3258: }
 3259: 
 3260: sub do_cache_new {
 3261:     my ($name,$id,$value,$time,$debug) = @_;
 3262:     my $remembered_id=$name.':'.$id;
 3263:     $id=&make_key($name,$id);
 3264:     my $setvalue=$value;
 3265:     if (!defined($setvalue)) {
 3266: 	$setvalue='__undef__';
 3267:     }
 3268:     if (!defined($time) ) {
 3269: 	$time=600;
 3270:     }
 3271:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3272:     my $result = $memcache->set($id,$setvalue,$time);
 3273:     if (! $result) {
 3274: 	&logthis("caching of id -> $id  failed");
 3275: 	$memcache->disconnect_all();
 3276:     }
 3277:     # need to make a copy of $value
 3278:     &make_room($remembered_id,$value,$debug);
 3279:     return $value;
 3280: }
 3281: 
 3282: sub make_room {
 3283:     my ($remembered_id,$value,$debug)=@_;
 3284: 
 3285:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3286:                                     : $value;
 3287:     if ($to_remember<0) { return; }
 3288:     $accessed{$remembered_id}=[&gettimeofday()];
 3289:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3290:     my $to_kick;
 3291:     my $max_time=0;
 3292:     foreach my $other (keys(%accessed)) {
 3293: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3294: 	    $to_kick=$other;
 3295: 	    $max_time=&tv_interval($accessed{$other});
 3296: 	}
 3297:     }
 3298:     delete($remembered{$to_kick});
 3299:     delete($accessed{$to_kick});
 3300:     $kicks++;
 3301:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3302:     return;
 3303: }
 3304: 
 3305: sub purge_remembered {
 3306:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3307:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3308:     undef(%remembered);
 3309:     undef(%accessed);
 3310: }
 3311: # ------------------------------------- Read an entry from a user's environment
 3312: 
 3313: sub userenvironment {
 3314:     my ($udom,$unam,@what)=@_;
 3315:     my $items;
 3316:     foreach my $item (@what) {
 3317:         $items.=&escape($item).'&';
 3318:     }
 3319:     $items=~s/\&$//;
 3320:     my %returnhash=();
 3321:     my $uhome = &homeserver($unam,$udom);
 3322:     unless ($uhome eq 'no_host') {
 3323:         my @answer=split(/\&/, 
 3324:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3325:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3326:             return %returnhash;
 3327:         }
 3328:         my $i;
 3329:         for ($i=0;$i<=$#what;$i++) {
 3330: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3331:         }
 3332:     }
 3333:     return %returnhash;
 3334: }
 3335: 
 3336: # ---------------------------------------------------------- Get a studentphoto
 3337: sub studentphoto {
 3338:     my ($udom,$unam,$ext) = @_;
 3339:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3340:     if (defined($env{'request.course.id'})) {
 3341:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3342:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3343:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3344:             } else {
 3345:                 my ($result,$perm_reqd)=
 3346: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3347:                 if ($result eq 'ok') {
 3348:                     if (!($perm_reqd eq 'yes')) {
 3349:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3350:                     }
 3351:                 }
 3352:             }
 3353:         }
 3354:     } else {
 3355:         my ($result,$perm_reqd) = 
 3356: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3357:         if ($result eq 'ok') {
 3358:             if (!($perm_reqd eq 'yes')) {
 3359:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3360:             }
 3361:         }
 3362:     }
 3363:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3364: }
 3365: 
 3366: sub retrievestudentphoto {
 3367:     my ($udom,$unam,$ext,$type) = @_;
 3368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3369:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3370:     if ($ret eq 'ok') {
 3371:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3372:         if ($type eq 'thumbnail') {
 3373:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3374:         }
 3375:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3376:         return $tokenurl;
 3377:     } else {
 3378:         if ($type eq 'thumbnail') {
 3379:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3380:         } else { 
 3381:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3382:         }
 3383:     }
 3384: }
 3385: 
 3386: # -------------------------------------------------------------------- New chat
 3387: 
 3388: sub chatsend {
 3389:     my ($newentry,$anon,$group)=@_;
 3390:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3391:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3392:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3393:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3394: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3395: 		   &escape($newentry)).':'.$group,$chome);
 3396: }
 3397: 
 3398: # ------------------------------------------ Find current version of a resource
 3399: 
 3400: sub getversion {
 3401:     my $fname=&clutter(shift);
 3402:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3403:     return &currentversion(&filelocation('',$fname));
 3404: }
 3405: 
 3406: sub currentversion {
 3407:     my $fname=shift;
 3408:     my $author=$fname;
 3409:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3410:     my ($udom,$uname)=split(/\//,$author);
 3411:     my $home=&homeserver($uname,$udom);
 3412:     if ($home eq 'no_host') { 
 3413:         return -1; 
 3414:     }
 3415:     my $answer=&reply("currentversion:$fname",$home);
 3416:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3417: 	return -1;
 3418:     }
 3419:     return $answer;
 3420: }
 3421: 
 3422: #
 3423: # Return special version number of resource if set by override, empty otherwise
 3424: #
 3425: sub usedversion {
 3426:     my $fname=shift;
 3427:     unless ($fname) { $fname=$env{'request.uri'}; }
 3428:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3429:     if ($urlversion) { return $urlversion; }
 3430:     return '';
 3431: }
 3432: 
 3433: # ----------------------------- Subscribe to a resource, return URL if possible
 3434: 
 3435: sub subscribe {
 3436:     my $fname=shift;
 3437:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3438:     $fname=~s/[\n\r]//g;
 3439:     my $author=$fname;
 3440:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3441:     my ($udom,$uname)=split(/\//,$author);
 3442:     my $home=homeserver($uname,$udom);
 3443:     if ($home eq 'no_host') {
 3444:         return 'not_found';
 3445:     }
 3446:     my $answer=reply("sub:$fname",$home);
 3447:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3448: 	$answer.=' by '.$home;
 3449:     }
 3450:     return $answer;
 3451: }
 3452:     
 3453: # -------------------------------------------------------------- Replicate file
 3454: 
 3455: sub repcopy {
 3456:     my $filename=shift;
 3457:     $filename=~s/\/+/\//g;
 3458:     my $londocroot = $perlvar{'lonDocRoot'};
 3459:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3460:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3461:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3462: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3463: 	return &repcopy_userfile($filename);
 3464:     }
 3465:     $filename=~s/[\n\r]//g;
 3466:     my $transname="$filename.in.transfer";
 3467: # FIXME: this should flock
 3468:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3469:     my $remoteurl=subscribe($filename);
 3470:     if ($remoteurl =~ /^con_lost by/) {
 3471: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3472:            return 'unavailable';
 3473:     } elsif ($remoteurl eq 'not_found') {
 3474: 	   #&logthis("Subscribe returned not_found: $filename");
 3475: 	   return 'not_found';
 3476:     } elsif ($remoteurl =~ /^rejected by/) {
 3477: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3478:            return 'forbidden';
 3479:     } elsif ($remoteurl eq 'directory') {
 3480:            return 'ok';
 3481:     } else {
 3482:         my $author=$filename;
 3483:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3484:         my ($udom,$uname)=split(/\//,$author);
 3485:         my $home=homeserver($uname,$udom);
 3486:         unless ($home eq $perlvar{'lonHostID'}) {
 3487:            my @parts=split(/\//,$filename);
 3488:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3489:            if ($path ne "$londocroot/res") {
 3490:                &logthis("Malconfiguration for replication: $filename");
 3491: 	       return 'bad_request';
 3492:            }
 3493:            my $count;
 3494:            for ($count=5;$count<$#parts;$count++) {
 3495:                $path.="/$parts[$count]";
 3496:                if ((-e $path)!=1) {
 3497: 		   mkdir($path,0777);
 3498:                }
 3499:            }
 3500:            my $request=new HTTP::Request('GET',"$remoteurl");
 3501:            my $response;
 3502:            if ($remoteurl =~ m{/raw/}) {
 3503:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3504:            } else {
 3505:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3506:            }
 3507:            if ($response->is_error()) {
 3508: 	       unlink($transname);
 3509:                my $message=$response->status_line;
 3510:                &logthis("<font color=\"blue\">WARNING:"
 3511:                        ." LWP get: $message: $filename</font>");
 3512:                return 'unavailable';
 3513:            } else {
 3514: 	       if ($remoteurl!~/\.meta$/) {
 3515:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3516:                   my $mresponse;
 3517:                   if ($remoteurl =~ m{/raw/}) {
 3518:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3519:                   } else {
 3520:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3521:                   }
 3522:                   if ($mresponse->is_error()) {
 3523: 		      unlink($filename.'.meta');
 3524:                       &logthis(
 3525:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3526:                   }
 3527: 	       }
 3528:                rename($transname,$filename);
 3529:                return 'ok';
 3530:            }
 3531:        }
 3532:     }
 3533: }
 3534: 
 3535: # ------------------------------------------------- Unsubscribe from a resource
 3536: 
 3537: sub unsubscribe {
 3538:     my ($fname) = @_;
 3539:     my $answer;
 3540:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3541:     $fname=~s/[\n\r]//g;
 3542:     my $author=$fname;
 3543:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3544:     my ($udom,$uname)=split(/\//,$author);
 3545:     my $home=homeserver($uname,$udom);
 3546:     if ($home eq 'no_host') {
 3547:         $answer = 'no_host';
 3548:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3549:         $answer = 'home';
 3550:     } else {
 3551:         my $defdom = $perlvar{'lonDefDomain'};
 3552:         if (&will_trust('content',$defdom,$udom)) {
 3553:             $answer = reply("unsub:$fname",$home);
 3554:         } else {
 3555:             $answer = 'untrusted';
 3556:         }
 3557:     }
 3558:     return $answer;
 3559: }
 3560: 
 3561: # ------------------------------------------------ Get server side include body
 3562: sub ssi_body {
 3563:     my ($filelink,%form)=@_;
 3564:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3565:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3566:     }
 3567:     my $output='';
 3568:     my $response;
 3569:     if ($filelink=~/^https?\:/) {
 3570:        ($output,$response)=&externalssi($filelink);
 3571:     } else {
 3572:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3573:        $filelink .= 'inhibitmenu=yes';
 3574:        ($output,$response)=&ssi($filelink,%form);
 3575:     }
 3576:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3577:     $output=~s/^.*?\<body[^\>]*\>//si;
 3578:     $output=~s/\<\/body\s*\>.*?$//si;
 3579:     if (wantarray) {
 3580:         return ($output, $response);
 3581:     } else {
 3582:         return $output;
 3583:     }
 3584: }
 3585: 
 3586: # --------------------------------------------------------- Server Side Include
 3587: 
 3588: sub absolute_url {
 3589:     my ($host_name,$unalias,$keep_proto) = @_;
 3590:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3591:     if ($host_name eq '') {
 3592: 	$host_name = $ENV{'SERVER_NAME'};
 3593:     }
 3594:     if ($unalias) {
 3595:         my $alias = &get_proxy_alias();
 3596:         if ($alias eq $host_name) {
 3597:             my $lonhost = $perlvar{'lonHostID'};
 3598:             my $hostname = &hostname($lonhost);
 3599:             my $lcproto; 
 3600:             if (($keep_proto) || ($hostname eq '')) {
 3601:                 $lcproto = $protocol;
 3602:             } else {
 3603:                 $lcproto = $protocol{$lonhost};
 3604:                 $lcproto = 'http' if ($lcproto ne 'https');
 3605:                 $lcproto .= '://';
 3606:             }
 3607:             unless ($hostname eq '') {
 3608:                 return $lcproto.$hostname;
 3609:             }
 3610:         }
 3611:     }
 3612:     return $protocol.$host_name;
 3613: }
 3614: 
 3615: #
 3616: #   Server side include.
 3617: # Parameters:
 3618: #  fn     Possibly encrypted resource name/id.
 3619: #  form   Hash that describes how the rendering should be done
 3620: #         and other things.
 3621: # Returns:
 3622: #   Scalar context: The content of the response.
 3623: #   Array context:  2 element list of the content and the full response object.
 3624: #     
 3625: sub ssi {
 3626: 
 3627:     my ($fn,%form)=@_;
 3628:     my ($host,$request,$response);
 3629:     $host = &absolute_url('',1);
 3630: 
 3631:     $form{'no_update_last_known'}=1;
 3632:     &Apache::lonenc::check_encrypt(\$fn);
 3633:     if (%form) {
 3634:       $request=new HTTP::Request('POST',$host.$fn);
 3635:       $request->content(join('&',map { 
 3636:             my $name = escape($_);
 3637:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3638:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3639:             : &escape($form{$_}) );    
 3640:         } keys(%form)));
 3641:     } else {
 3642:       $request=new HTTP::Request('GET',$host.$fn);
 3643:     }
 3644: 
 3645:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3646:     my $lonhost = $perlvar{'lonHostID'};
 3647:     my $islocal;
 3648:     if (($env{'request.course.id'}) &&
 3649:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3650:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3651:         ($form{'grade_symb'} ne '') &&
 3652:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3653:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3654:         $islocal = 1;
 3655:     }
 3656:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3657:                                              '','','',$islocal);
 3658: 
 3659:     if (wantarray) {
 3660: 	return ($response->content, $response);
 3661:     } else {
 3662: 	return $response->content;
 3663:     }
 3664: }
 3665: 
 3666: sub externalssi {
 3667:     my ($url)=@_;
 3668:     my $request=new HTTP::Request('GET',$url);
 3669:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3670:     if (wantarray) {
 3671:         return ($response->content, $response);
 3672:     } else {
 3673:         return $response->content;
 3674:     }
 3675: }
 3676: 
 3677: 
 3678: # If the local copy of a replicated resource is outdated, trigger a  
 3679: # connection from the homeserver to flush the delayed queue. If no update 
 3680: # happens, remove local copies of outdated resource (and corresponding
 3681: # metadata file).
 3682: 
 3683: sub remove_stale_resfile {
 3684:     my ($url) = @_;
 3685:     my $removed;
 3686:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3687:         my $audom = $1;
 3688:         my $auname = $2;
 3689:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3690:             my $homeserver = &homeserver($auname,$audom);
 3691:             unless (($homeserver eq 'no_host') ||
 3692:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3693:                 my $fname = &filelocation('',$url);
 3694:                 if (-e $fname) {
 3695:                     my $hostname = &hostname($homeserver);
 3696:                     if ($hostname) {
 3697:                         my $protocol = $protocol{$homeserver};
 3698:                         $protocol = 'http' if ($protocol ne 'https');
 3699:                         my $uri = &declutter($url);
 3700:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3701:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3702:                         if ($response->is_success()) {
 3703:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3704:                             my $locmodtime = (stat($fname))[9];
 3705:                             if ($locmodtime < $remmodtime) {
 3706:                                 my $stale;
 3707:                                 my $answer = &reply('pong',$homeserver);
 3708:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3709:                                     sleep(0.2);
 3710:                                     $locmodtime = (stat($fname))[9];
 3711:                                     if ($locmodtime < $remmodtime) {
 3712:                                         my $posstransfer = $fname.'.in.transfer';
 3713:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3714:                                             $removed = 1;
 3715:                                         } else {
 3716:                                             $stale = 1;
 3717:                                         }
 3718:                                     } else {
 3719:                                         $removed = 1;
 3720:                                     }
 3721:                                 } else {
 3722:                                     $stale = 1;
 3723:                                 }
 3724:                                 if ($stale) {
 3725:                                     if (unlink($fname)) {
 3726:                                         if ($uri!~/\.meta$/) {
 3727:                                             if (-e $fname.'.meta') {
 3728:                                                 unlink($fname.'.meta');
 3729:                                             }
 3730:                                         }
 3731:                                         my $unsubresult = &unsubscribe($fname);
 3732:                                         unless ($unsubresult eq 'ok') {
 3733:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3734:                                         }
 3735:                                         $removed = 1;
 3736:                                     }
 3737:                                 }
 3738:                             }
 3739:                         }
 3740:                     }
 3741:                 }
 3742:             }
 3743:         }
 3744:     }
 3745:     return $removed;
 3746: }
 3747: 
 3748: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3749: 
 3750: sub allowuploaded {
 3751:     my ($srcurl,$url)=@_;
 3752:     $url=&clutter(&declutter($url));
 3753:     my $dir=$url;
 3754:     $dir=~s/\/[^\/]+$//;
 3755:     my %httpref=();
 3756:     my $httpurl=&hreflocation('',$url);
 3757:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3758:     &Apache::lonnet::appenv(\%httpref);
 3759: }
 3760: 
 3761: #
 3762: # Determine if the current user should be able to edit a particular resource,
 3763: # when viewing in course context.
 3764: # (a) When viewing resource used to determine if "Edit" item is included in 
 3765: #     Functions.
 3766: # (b) When displaying folder contents in course editor, used to determine if
 3767: #     "Edit" link will be displayed alongside resource.
 3768: #
 3769: #  input: six args -- filename (decluttered), course number, course domain,
 3770: #                   url, symb (if registered) and group (if this is a group
 3771: #                   item -- e.g., bulletin board, group page etc.).
 3772: #  output: array of five scalars -- 
 3773: #          $cfile -- url for file editing if editable on current server
 3774: #          $home -- homeserver of resource (i.e., for author if published,
 3775: #                                           or course if uploaded.).
 3776: #          $switchserver --  1 if server switch will be needed.
 3777: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3778: #          $forceview -- 1 if icon/link should be to go to view mode
 3779: #
 3780: 
 3781: sub can_edit_resource {
 3782:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3783:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3784: #
 3785: # For aboutme pages user can only edit his/her own.
 3786: #
 3787:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3788:         my ($sdom,$sname) = ($1,$2);
 3789:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3790:             $home = $env{'user.home'};
 3791:             $cfile = $resurl;
 3792:             if ($env{'form.forceedit'}) {
 3793:                 $forceview = 1;
 3794:             } else {
 3795:                 $forceedit = 1;
 3796:             }
 3797:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3798:         } else {
 3799:             return;
 3800:         }
 3801:     }
 3802: 
 3803:     if ($env{'request.course.id'}) {
 3804:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3805:         if ($group ne '') {
 3806: # if this is a group homepage or group bulletin board, check group privs
 3807:             my $allowed = 0;
 3808:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3809:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3810:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3811:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3812:                     $allowed = 1;
 3813:                 }
 3814:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3815:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3816:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3817:                     $allowed = 1;
 3818:                 }
 3819:             }
 3820:             if ($allowed) {
 3821:                 $home=&homeserver($cnum,$cdom);
 3822:                 if ($env{'form.forceedit'}) {
 3823:                     $forceview = 1;
 3824:                 } else {
 3825:                     $forceedit = 1;
 3826:                 }
 3827:                 $cfile = $resurl;
 3828:             } else {
 3829:                 return;
 3830:             }
 3831:         } else {
 3832:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3833:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3834:                     return;
 3835:                 }
 3836:             } elsif (!$crsedit) {
 3837: #
 3838: # No edit allowed where CC has switched to student role.
 3839: #
 3840:                 return;
 3841:             }
 3842:         }
 3843:     }
 3844: 
 3845:     if ($file ne '') {
 3846:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3847:             if (&is_course_upload($file,$cnum,$cdom)) {
 3848:                 $uploaded = 1;
 3849:                 $incourse = 1;
 3850:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3851:                     $cfile = &hreflocation('',$file);
 3852:                     if ($env{'form.forceedit'}) {
 3853:                         $forceview = 1;
 3854:                     } else {
 3855:                         $forceedit = 1;
 3856:                     }
 3857:                 }
 3858:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3859:                 $incourse = 1;
 3860:                 if ($env{'form.forceedit'}) {
 3861:                     $forceview = 1;
 3862:                 } else {
 3863:                     $forceedit = 1;
 3864:                 }
 3865:                 $cfile = $resurl;
 3866:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3867:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3868:                     $incourse = 1;
 3869:                     if ($env{'form.forceedit'}) {
 3870:                         $forceview = 1;
 3871:                     } else {
 3872:                         $forceedit = 1;
 3873:                     }
 3874:                     $cfile = $resurl;
 3875:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3876:                     $incourse = 1;
 3877:                     $cfile = $resurl.'/smpedit';
 3878:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3879:                     $incourse = 1;
 3880:                     if ($env{'form.forceedit'}) {
 3881:                         $forceview = 1;
 3882:                     } else {
 3883:                         $forceedit = 1;
 3884:                     }
 3885:                     $cfile = $resurl;
 3886:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3887:                     my ($map,$id,$res) = &decode_symb($symb);
 3888:                     if ($map =~ /\.page$/) {
 3889:                         $incourse = 1;
 3890:                         if ($env{'form.forceedit'}) {
 3891:                             $forceview = 1;
 3892:                             $cfile = $map;
 3893:                         } else {
 3894:                             $forceedit = 1;
 3895:                             $cfile =  '/adm/wrapper'.$resurl;
 3896:                         }
 3897:                     }
 3898:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3899:                     $incourse = 1;
 3900:                     if ($env{'form.forceedit'}) {
 3901:                         $forceview = 1;
 3902:                     } else {
 3903:                         $forceedit = 1;
 3904:                     }
 3905:                     $cfile = $resurl;
 3906:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3907:                     $incourse = 1;
 3908:                     if ($env{'form.forceedit'}) {
 3909:                         $forceview = 1;
 3910:                     } else {
 3911:                         $forceedit = 1;
 3912:                     }
 3913:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3914:                 }
 3915:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3916:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3917:                 if (&is_on_map($template)) { 
 3918:                     $incourse = 1;
 3919:                     $forceview = 1;
 3920:                     $cfile = $template;
 3921:                 }
 3922:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3923:                 $incourse = 1;
 3924:                 if ($env{'form.forceedit'}) {
 3925:                     $forceview = 1;
 3926:                 } else {
 3927:                     $forceedit = 1;
 3928:                 }
 3929:                 $cfile = $resurl;
 3930:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3931:                 $incourse = 1;
 3932:                 if ($env{'form.forceedit'}) {
 3933:                     $forceview = 1;
 3934:                 } else {
 3935:                     $forceedit = 1;
 3936:                 }
 3937:                 $cfile = $resurl;
 3938:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3939:                 $incourse = 1;
 3940:                 $forceview = 1;
 3941:                 if ($symb) {
 3942:                     my ($map,$id,$res)=&decode_symb($symb);
 3943:                     $env{'request.symb'} = $symb;
 3944:                     $cfile = &clutter($res);
 3945:                 } else {
 3946:                     $cfile = $env{'form.suppurl'};
 3947:                     my $escfile = &unescape($cfile);
 3948:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3949:                         $cfile = '/adm/wrapper'.$escfile;
 3950:                     } else {
 3951:                         $escfile =~ s{^http://}{};
 3952:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3953:                     }
 3954:                 }
 3955:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3956:                 if ($env{'form.forceedit'}) {
 3957:                     $forceview = 1;
 3958:                 } else {
 3959:                     $forceedit = 1;
 3960:                 }
 3961:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3962:             }
 3963:         }
 3964:         if ($uploaded || $incourse) {
 3965:             $home=&homeserver($cnum,$cdom);
 3966:         } elsif ($file !~ m{/$}) {
 3967:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3968:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3969:             # Check that the user has permission to edit this resource
 3970:             my $setpriv = 1;
 3971:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3972:             if (defined($cfudom)) {
 3973:                 $home=&homeserver($cfuname,$cfudom);
 3974:                 $cfile=$file;
 3975:             }
 3976:         }
 3977:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3978:             (($home ne '') && ($home ne 'no_host'))) {
 3979:             my @ids=&current_machine_ids();
 3980:             unless (grep(/^\Q$home\E$/,@ids)) {
 3981:                 $switchserver=1;
 3982:             }
 3983:         }
 3984:     }
 3985:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3986: }
 3987: 
 3988: sub is_course_upload {
 3989:     my ($file,$cnum,$cdom) = @_;
 3990:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3991:     $uploadpath =~ s{^\/}{};
 3992:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3993:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3994:         return 1;
 3995:     }
 3996:     return;
 3997: }
 3998: 
 3999: sub in_course {
 4000:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4001:     if ($hideprivileged) {
 4002:         my $skipuser;
 4003:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4004:         my @possdoms = ($cdom);  
 4005:         if ($coursehash{'checkforpriv'}) { 
 4006:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4007:         }
 4008:         if (&privileged($uname,$udom,\@possdoms)) {
 4009:             $skipuser = 1;
 4010:             if ($coursehash{'nothideprivileged'}) {
 4011:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4012:                     my $user;
 4013:                     if ($item =~ /:/) {
 4014:                         $user = $item;
 4015:                     } else {
 4016:                         $user = join(':',split(/[\@]/,$item));
 4017:                     }
 4018:                     if ($user eq $uname.':'.$udom) {
 4019:                         undef($skipuser);
 4020:                         last;
 4021:                     }
 4022:                 }
 4023:             }
 4024:             if ($skipuser) {
 4025:                 return 0;
 4026:             }
 4027:         }
 4028:     }
 4029:     $type ||= 'any';
 4030:     if (!defined($cdom) || !defined($cnum)) {
 4031:         my $cid  = $env{'request.course.id'};
 4032:         $cdom = $env{'course.'.$cid.'.domain'};
 4033:         $cnum = $env{'course.'.$cid.'.num'};
 4034:     }
 4035:     my $typesref;
 4036:     if (($type eq 'any') || ($type eq 'all')) {
 4037:         $typesref = ['active','previous','future'];
 4038:     } elsif ($type eq 'previous' || $type eq 'future') {
 4039:         $typesref = [$type];
 4040:     }
 4041:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4042:                               $typesref,undef,[$cdom]);
 4043:     my ($tmp) = keys(%roles);
 4044:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4045:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4046:     if (@course_roles > 0) {
 4047:         return 1;
 4048:     }
 4049:     return 0;
 4050: }
 4051: 
 4052: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4053: # input: action, courseID, current domain, intended
 4054: #        path to file, source of file, instruction to parse file for objects,
 4055: #        ref to hash for embedded objects,
 4056: #        ref to hash for codebase of java objects.
 4057: #        reference to scalar to accommodate mime type determined
 4058: #          from File::MMagic if $parser = parse.
 4059: #
 4060: # output: url to file (if action was uploaddoc), 
 4061: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4062: #
 4063: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4064: # course.
 4065: #
 4066: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4067: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4068: #          course's home server.
 4069: #
 4070: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4071: #          be copied from $source (current location) to 
 4072: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4073: #         and will then be copied to
 4074: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4075: #         course's home server.
 4076: #
 4077: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4078: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4079: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4080: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4081: #         in course's home server.
 4082: #
 4083: 
 4084: sub process_coursefile {
 4085:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4086:         $mimetype)=@_;
 4087:     my $fetchresult;
 4088:     my $home=&homeserver($docuname,$docudom);
 4089:     if ($action eq 'propagate') {
 4090:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4091: 			     $home);
 4092:     } else {
 4093:         my $fpath = '';
 4094:         my $fname = $file;
 4095:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4096:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4097:         my $filepath = &build_filepath($fpath);
 4098:         if ($action eq 'copy') {
 4099:             if ($source eq '') {
 4100:                 $fetchresult = 'no source file';
 4101:                 return $fetchresult;
 4102:             } else {
 4103:                 my $destination = $filepath.'/'.$fname;
 4104:                 rename($source,$destination);
 4105:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4106:                                  $home);
 4107:             }
 4108:         } elsif ($action eq 'uploaddoc') {
 4109:             open(my $fh,'>',$filepath.'/'.$fname);
 4110:             print $fh $env{'form.'.$source};
 4111:             close($fh);
 4112:             if ($parser eq 'parse') {
 4113:                 my $mm = new File::MMagic;
 4114:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4115:                 if ($type eq 'text/html') {
 4116:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4117:                     unless ($parse_result eq 'ok') {
 4118:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4119:                     }
 4120:                 }
 4121:                 if (ref($mimetype)) {
 4122:                     $$mimetype = $type;
 4123:                 } 
 4124:             }
 4125:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4126:                                  $home);
 4127:             if ($fetchresult eq 'ok') {
 4128:                 return '/uploaded/'.$fpath.'/'.$fname;
 4129:             } else {
 4130:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4131:                         ' to host '.$home.': '.$fetchresult);
 4132:                 return '/adm/notfound.html';
 4133:             }
 4134:         }
 4135:     }
 4136:     unless ( $fetchresult eq 'ok') {
 4137:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4138:              ' to host '.$home.': '.$fetchresult);
 4139:     }
 4140:     return $fetchresult;
 4141: }
 4142: 
 4143: sub build_filepath {
 4144:     my ($fpath) = @_;
 4145:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4146:     unless ($fpath eq '') {
 4147:         my @parts=split('/',$fpath);
 4148:         foreach my $part (@parts) {
 4149:             $filepath.= '/'.$part;
 4150:             if ((-e $filepath)!=1) {
 4151:                 mkdir($filepath,0777);
 4152:             }
 4153:         }
 4154:     }
 4155:     return $filepath;
 4156: }
 4157: 
 4158: sub store_edited_file {
 4159:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4160:     my $file = $primary_url;
 4161:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4162:     my $fpath = '';
 4163:     my $fname = $file;
 4164:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4165:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4166:     my $filepath = &build_filepath($fpath);
 4167:     open(my $fh,'>',$filepath.'/'.$fname);
 4168:     print $fh $content;
 4169:     close($fh);
 4170:     my $home=&homeserver($docuname,$docudom);
 4171:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4172: 			  $home);
 4173:     if ($$fetchresult eq 'ok') {
 4174:         return '/uploaded/'.$fpath.'/'.$fname;
 4175:     } else {
 4176:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4177: 		 ' to host '.$home.': '.$$fetchresult);
 4178:         return '/adm/notfound.html';
 4179:     }
 4180: }
 4181: 
 4182: sub clean_filename {
 4183:     my ($fname,$args)=@_;
 4184: # Replace Windows backslashes by forward slashes
 4185:     $fname=~s/\\/\//g;
 4186:     if (!$args->{'keep_path'}) {
 4187:         # Get rid of everything but the actual filename
 4188: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4189:     }
 4190: # Replace spaces by underscores
 4191:     $fname=~s/\s+/\_/g;
 4192: # Transliterate non-ascii text to ascii
 4193:     my $lang = &Apache::lonlocal::current_language();
 4194:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4195: # Replace all other weird characters by nothing
 4196:     $fname=~s{[^/\w\.\-]}{}g;
 4197: # Replace all .\d. sequences with _\d. so they no longer look like version
 4198: # numbers
 4199:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4200: # Replace three or more adjacent underscores with one for consistency 
 4201: # with loncfile::filename_check() so complete url can be extracted by
 4202: # lonnet::decode_symb()
 4203:     $fname=~s/_{3,}/_/g;
 4204:     return $fname;
 4205: }
 4206: 
 4207: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4208: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4209: # image with the same aspect ratio as the original, but with dimensions which do 
 4210: # not exceed $resizewidth and $resizeheight.
 4211:  
 4212: sub resizeImage {
 4213:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4214:     my $ima = Image::Magick->new;
 4215:     my $resized;
 4216:     if (-e $img_path) {
 4217:         $ima->Read($img_path);
 4218:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4219:             my $width = $ima->Get('width');
 4220:             my $height = $ima->Get('height');
 4221:             if ($width > $resizewidth) {
 4222: 	        my $factor = $width/$resizewidth;
 4223:                 my $newheight = $height/$factor;
 4224:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4225:                 $resized = 1;
 4226:             }
 4227:         }
 4228:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4229:             my $width = $ima->Get('width');
 4230:             my $height = $ima->Get('height');
 4231:             if ($height > $resizeheight) {
 4232:                 my $factor = $height/$resizeheight;
 4233:                 my $newwidth = $width/$factor;
 4234:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4235:                 $resized = 1;
 4236:             }
 4237:         }
 4238:         if ($resized) {
 4239:             $ima->Write($img_path);
 4240:         }
 4241:     }
 4242:     return;
 4243: }
 4244: 
 4245: # --------------- Take an uploaded file and put it into the userfiles directory
 4246: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4247: #                    the desired filename is in $env{"form.$formname.filename"}
 4248: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4249: #                                    canceloverwrite, scantron or ''.
 4250: #                   if 'coursedoc': upload to the current course
 4251: #                   if 'existingfile': write file to tmp/overwrites directory 
 4252: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4253: #                   $context is passed as argument to &finishuserfileupload
 4254: #        $subdir - directory in userfile to store the file into
 4255: #        $parser - instruction to parse file for objects ($parser = parse) or
 4256: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4257: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4258: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4259: #        $allfiles - reference to hash for embedded objects
 4260: #        $codebase - reference to hash for codebase of java objects
 4261: #        $desuname - username for permanent storage of uploaded file
 4262: #        $dsetudom - domain for permanaent storage of uploaded file
 4263: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4264: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4265: #        $resizewidth - width (pixels) to which to resize uploaded image
 4266: #        $resizeheight - height (pixels) to which to resize uploaded image
 4267: #        $mimetype - reference to scalar to accommodate mime type determined
 4268: #                    from File::MMagic.
 4269: # 
 4270: # output: url of file in userspace, or error: <message> 
 4271: #             or /adm/notfound.html if failure to upload occurse
 4272: 
 4273: sub userfileupload {
 4274:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4275:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4276:     if (!defined($subdir)) { $subdir='unknown'; }
 4277:     my $fname=$env{'form.'.$formname.'.filename'};
 4278:     $fname=&clean_filename($fname);
 4279:     # See if there is anything left
 4280:     unless ($fname) { return 'error: no uploaded file'; }
 4281:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4282:     if ($fname =~ /^\./) {
 4283:         my ($s,$usec) = &gettimeofday();
 4284:         while (length($usec) < 6) {
 4285:             $usec = '0'.$usec;
 4286:         }
 4287:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4288:     }
 4289:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4290:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4291:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4292:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4293:         my $now = time;
 4294:         my $filepath;
 4295:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4296:              $filepath = 'tmp/helprequests/'.$now;
 4297:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4298:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4299:                          '_'.$env{'user.domain'}.'/pending';
 4300:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4301:             my ($docuname,$docudom);
 4302:             if ($destudom =~ /^$match_domain$/) {
 4303:                 $docudom = $destudom;
 4304:             } else {
 4305:                 $docudom = $env{'user.domain'};
 4306:             }
 4307:             if ($destuname =~ /^$match_username$/) {
 4308:                 $docuname = $destuname;
 4309:             } else {
 4310:                 $docuname = $env{'user.name'};
 4311:             }
 4312:             if (exists($env{'form.group'})) {
 4313:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4314:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4315:             }
 4316:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4317:             if ($context eq 'canceloverwrite') {
 4318:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4319:                 if (-e  $tempfile) {
 4320:                     my @info = stat($tempfile);
 4321:                     if ($info[9] eq $env{'form.timestamp'}) {
 4322:                         unlink($tempfile);
 4323:                     }
 4324:                 }
 4325:                 return;
 4326:             }
 4327:         }
 4328:         # Create the directory if not present
 4329:         my @parts=split(/\//,$filepath);
 4330:         my $fullpath = $perlvar{'lonDaemons'};
 4331:         for (my $i=0;$i<@parts;$i++) {
 4332:             $fullpath .= '/'.$parts[$i];
 4333:             if ((-e $fullpath)!=1) {
 4334:                 mkdir($fullpath,0777);
 4335:             }
 4336:         }
 4337:         open(my $fh,'>',$fullpath.'/'.$fname);
 4338:         print $fh $env{'form.'.$formname};
 4339:         close($fh);
 4340:         if ($context eq 'existingfile') {
 4341:             my @info = stat($fullpath.'/'.$fname);
 4342:             return ($fullpath.'/'.$fname,$info[9]);
 4343:         } else {
 4344:             return $fullpath.'/'.$fname;
 4345:         }
 4346:     }
 4347:     if ($subdir eq 'scantron') {
 4348:         $fname = 'scantron_orig_'.$fname;
 4349:     } else {
 4350:         $fname="$subdir/$fname";
 4351:     }
 4352:     if ($context eq 'coursedoc') {
 4353: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4354: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4355:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4356:             return &finishuserfileupload($docuname,$docudom,
 4357: 					 $formname,$fname,$parser,$allfiles,
 4358: 					 $codebase,$thumbwidth,$thumbheight,
 4359:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4360:         } else {
 4361:             if ($env{'form.folder'}) {
 4362:                 $fname=$env{'form.folder'}.'/'.$fname;
 4363:             }
 4364:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4365: 				       $fname,$formname,$parser,
 4366: 				       $allfiles,$codebase,$mimetype);
 4367:         }
 4368:     } elsif (defined($destuname)) {
 4369:         my $docuname=$destuname;
 4370:         my $docudom=$destudom;
 4371: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4372: 				     $parser,$allfiles,$codebase,
 4373:                                      $thumbwidth,$thumbheight,
 4374:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4375:     } else {
 4376:         my $docuname=$env{'user.name'};
 4377:         my $docudom=$env{'user.domain'};
 4378:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4379:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4380:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4381:         }
 4382: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4383: 				     $parser,$allfiles,$codebase,
 4384:                                      $thumbwidth,$thumbheight,
 4385:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4386:     }
 4387: }
 4388: 
 4389: sub finishuserfileupload {
 4390:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4391:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4392:     my $path=$docudom.'/'.$docuname.'/';
 4393:     my $filepath=$perlvar{'lonDocRoot'};
 4394:   
 4395:     my ($fnamepath,$file,$fetchthumb);
 4396:     $file=$fname;
 4397:     if ($fname=~m|/|) {
 4398:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4399: 	$path.=$fnamepath.'/';
 4400:     }
 4401:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4402:     my $count;
 4403:     for ($count=4;$count<=$#parts;$count++) {
 4404:         $filepath.="/$parts[$count]";
 4405:         if ((-e $filepath)!=1) {
 4406: 	    mkdir($filepath,0777);
 4407:         }
 4408:     }
 4409: 
 4410: # Save the file
 4411:     {
 4412: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4413: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4414: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4415: 	    return '/adm/notfound.html';
 4416: 	}
 4417:         if ($context eq 'overwrite') {
 4418:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4419:             my $target = $filepath.'/'.$file;
 4420:             if (-e $source) {
 4421:                 my @info = stat($source);
 4422:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4423:                     unless (&File::Copy::move($source,$target)) {
 4424:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4425:                         return "Moving from $source failed";
 4426:                     }
 4427:                 } else {
 4428:                     return "Temporary file: $source had unexpected date/time for last modification";
 4429:                 }
 4430:             } else {
 4431:                 return "Temporary file: $source missing";
 4432:             }
 4433:         } elsif (!print FH ($env{'form.'.$formname})) {
 4434: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4435: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4436: 	    return '/adm/notfound.html';
 4437: 	}
 4438: 	close(FH);
 4439:         if ($resizewidth && $resizeheight) {
 4440:             my $mm = new File::MMagic;
 4441:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4442:             if ($mime_type =~ m{^image/}) {
 4443: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4444:             }  
 4445: 	}
 4446:     }
 4447:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4448:         if (ref($mimetype)) {
 4449:             if ($$mimetype eq '') {
 4450:                 my $mm = new File::MMagic;
 4451:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4452:                 $$mimetype = $type;
 4453:             }
 4454:         }
 4455:     }
 4456:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4457:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4458:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4459:                                                        $allfiles,$codebase);
 4460:             unless ($parse_result eq 'ok') {
 4461:                 &logthis('Failed to parse '.$filepath.$file.
 4462: 	   	         ' for embedded media: '.$parse_result); 
 4463:             }
 4464:         }
 4465:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4466:         my $format = $env{'form.scantron_format'};
 4467:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4468:     }
 4469:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4470:         my $input = $filepath.'/'.$file;
 4471:         my $output = $filepath.'/'.'tn-'.$file;
 4472:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4473:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4474:         system({$args[0]} @args);
 4475:         if (-e $filepath.'/'.'tn-'.$file) {
 4476:             $fetchthumb  = 1; 
 4477:         }
 4478:     }
 4479:  
 4480: # Notify homeserver to grep it
 4481: #
 4482:     my $docuhome=&homeserver($docuname,$docudom);	
 4483:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4484:     if ($fetchresult eq 'ok') {
 4485:         if ($fetchthumb) {
 4486:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4487:             if ($thumbresult ne 'ok') {
 4488:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4489:                          $docuhome.': '.$thumbresult);
 4490:             }
 4491:         }
 4492: #
 4493: # Return the URL to it
 4494:         return '/uploaded/'.$path.$file;
 4495:     } else {
 4496:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4497: 		 ': '.$fetchresult);
 4498:         return '/adm/notfound.html';
 4499:     }
 4500: }
 4501: 
 4502: sub extract_embedded_items {
 4503:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4504:     my @state = ();
 4505:     my (%lastids,%related,%shockwave,%flashvars);
 4506:     my %javafiles = (
 4507:                       codebase => '',
 4508:                       code => '',
 4509:                       archive => ''
 4510:                     );
 4511:     my %mediafiles = (
 4512:                       src => '',
 4513:                       movie => '',
 4514:                      );
 4515:     my $p;
 4516:     if ($content) {
 4517:         $p = HTML::LCParser->new($content);
 4518:     } else {
 4519:         $p = HTML::LCParser->new($fullpath);
 4520:     }
 4521:     while (my $t=$p->get_token()) {
 4522: 	if ($t->[0] eq 'S') {
 4523: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4524: 	    push(@state, $tagname);
 4525:             if (lc($tagname) eq 'allow') {
 4526:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4527:             }
 4528: 	    if (lc($tagname) eq 'img') {
 4529: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4530: 	    }
 4531: 	    if (lc($tagname) eq 'a') {
 4532:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4533:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4534:                 }
 4535: 	    }
 4536:             if (lc($tagname) eq 'script') {
 4537:                 my $src;
 4538:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4539:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4540:                 } else {
 4541:                     if ($attr->{'src'} ne '') {
 4542:                         $src = $attr->{'src'};
 4543:                         &add_filetype($allfiles,$src,'src');
 4544:                     }
 4545:                 }
 4546:                 my $text = $p->get_trimmed_text();
 4547:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4548:                     my @swfargs = split(/,/,$1);
 4549:                     foreach my $item (@swfargs) {
 4550:                         $item =~ s/["']//g;
 4551:                         $item =~ s/^\s+//;
 4552:                         $item =~ s/\s+$//;
 4553:                     }
 4554:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4555:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4556:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4557:                         } else {
 4558:                             $related{$swfargs[0]} = [$swfargs[2]];
 4559:                         }
 4560:                     }
 4561:                 }
 4562:             }
 4563:             if (lc($tagname) eq 'link') {
 4564:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4565:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4566:                 }
 4567:             }
 4568: 	    if (lc($tagname) eq 'object' ||
 4569: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4570: 		foreach my $item (keys(%javafiles)) {
 4571: 		    $javafiles{$item} = '';
 4572: 		}
 4573:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4574:                     $lastids{lc($tagname)} = $attr->{'id'};
 4575:                 }
 4576: 	    }
 4577: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4578: 		my $name = lc($attr->{'name'});
 4579: 		foreach my $item (keys(%javafiles)) {
 4580: 		    if ($name eq $item) {
 4581: 			$javafiles{$item} = $attr->{'value'};
 4582: 			last;
 4583: 		    }
 4584: 		}
 4585:                 my $pathfrom;
 4586: 		foreach my $item (keys(%mediafiles)) {
 4587: 		    if ($name eq $item) {
 4588:                         $pathfrom = $attr->{'value'};
 4589:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4590: 			&add_filetype($allfiles,$pathfrom,$name);
 4591: 			last;
 4592: 		    }
 4593: 		}
 4594:                 if ($name eq 'flashvars') {
 4595:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4596:                 }
 4597:                 if ($pathfrom ne '') {
 4598:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4599:                                          $pathfrom);
 4600:                 }
 4601: 	    }
 4602: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4603: 		foreach my $item (keys(%javafiles)) {
 4604: 		    if ($attr->{$item}) {
 4605: 			$javafiles{$item} = $attr->{$item};
 4606: 			last;
 4607: 		    }
 4608: 		}
 4609: 		foreach my $item (keys(%mediafiles)) {
 4610: 		    if ($attr->{$item}) {
 4611: 			&add_filetype($allfiles,$attr->{$item},$item);
 4612: 			last;
 4613: 		    }
 4614: 		}
 4615:                 if (lc($tagname) eq 'embed') {
 4616:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4617:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4618:                                              $attr->{'src'});
 4619:                     }
 4620:                 }
 4621: 	    }
 4622:             if (lc($tagname) eq 'iframe') {
 4623:                 my $src = $attr->{'src'} ;
 4624:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4625:                     &add_filetype($allfiles,$src,'src');
 4626:                 } elsif ($src =~ m{^/}) {
 4627:                     if ($env{'request.course.id'}) {
 4628:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4629:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4630:                         my $url = &hreflocation('',$fullpath);
 4631:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4632:                             my $relpath = $1;
 4633:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4634:                                 &add_filetype($allfiles,$1,'src');
 4635:                             }
 4636:                         }
 4637:                     }
 4638:                 }
 4639:             }
 4640:             if ($t->[4] =~ m{/>$}) {
 4641:                 pop(@state);
 4642:             }
 4643: 	} elsif ($t->[0] eq 'E') {
 4644: 	    my ($tagname) = ($t->[1]);
 4645: 	    if ($javafiles{'codebase'} ne '') {
 4646: 		$javafiles{'codebase'} .= '/';
 4647: 	    }  
 4648: 	    if (lc($tagname) eq 'applet' ||
 4649: 		lc($tagname) eq 'object' ||
 4650: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4651: 		) {
 4652: 		foreach my $item (keys(%javafiles)) {
 4653: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4654: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4655: 			&add_filetype($allfiles,$file,$item);
 4656: 		    }
 4657: 		}
 4658: 	    } 
 4659: 	    pop @state;
 4660: 	}
 4661:     }
 4662:     foreach my $id (sort(keys(%flashvars))) {
 4663:         if ($shockwave{$id} ne '') {
 4664:             my @pairs = split(/\&/,$flashvars{$id});
 4665:             foreach my $pair (@pairs) {
 4666:                 my ($key,$value) = split(/\=/,$pair);
 4667:                 if ($key eq 'thumb') {
 4668:                     &add_filetype($allfiles,$value,$key);
 4669:                 } elsif ($key eq 'content') {
 4670:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4671:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4672:                     if ($ext ne '') {
 4673:                         &add_filetype($allfiles,$path.$value,$ext);
 4674:                     }
 4675:                 }
 4676:             }
 4677:         }
 4678:     }
 4679:     return 'ok';
 4680: }
 4681: 
 4682: sub add_filetype {
 4683:     my ($allfiles,$file,$type)=@_;
 4684:     if (exists($allfiles->{$file})) {
 4685: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4686: 	    push(@{$allfiles->{$file}}, &escape($type));
 4687: 	}
 4688:     } else {
 4689: 	@{$allfiles->{$file}} = (&escape($type));
 4690:     }
 4691: }
 4692: 
 4693: sub embedded_dependency {
 4694:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4695:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4696:         if (($identifier ne '') &&
 4697:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4698:             ($pathfrom ne '')) {
 4699:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4700:             foreach my $dep (@{$related->{$identifier}}) {
 4701:                 &add_filetype($allfiles,$path.$dep,'object');
 4702:             }
 4703:         }
 4704:     }
 4705:     return;
 4706: }
 4707: 
 4708: sub bubblesheet_converter {
 4709:     my ($cdom,$fullpath,$config,$format) = @_;
 4710:     if ((&domain($cdom) ne '') &&
 4711:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4712:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4713:         my (%csvcols,%csvoptions);
 4714:         if (ref($config->{'fields'}) eq 'HASH') {  
 4715:             %csvcols = %{$config->{'fields'}};
 4716:         }
 4717:         if (ref($config->{'options'}) eq 'HASH') {
 4718:             %csvoptions = %{$config->{'options'}};
 4719:         }
 4720:         my %csvbynum = reverse(%csvcols);
 4721:         my %scantronconf = &get_scantron_config($format,$cdom);
 4722:         if (keys(%scantronconf)) {
 4723:             my %bynum = (
 4724:                           $scantronconf{CODEstart} => 'CODEstart',
 4725:                           $scantronconf{IDstart}   => 'IDstart',
 4726:                           $scantronconf{PaperID}   => 'PaperID',
 4727:                           $scantronconf{FirstName} => 'FirstName',
 4728:                           $scantronconf{LastName}  => 'LastName',
 4729:                           $scantronconf{Qstart}    => 'Qstart',
 4730:                         );
 4731:             my @ordered;
 4732:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4733:                 push(@ordered,$bynum{$item});
 4734:             }
 4735:             my %mapstart = (
 4736:                               CODEstart => 'CODE',
 4737:                               IDstart   => 'ID',
 4738:                               PaperID   => 'PaperID',
 4739:                               FirstName => 'FirstName',
 4740:                               LastName  => 'LastName',
 4741:                               Qstart    => 'FirstQuestion',
 4742:                            );
 4743:             my %maplength = (
 4744:                               CODEstart => 'CODElength',
 4745:                               IDstart   => 'IDlength',
 4746:                               PaperID   => 'PaperIDlength',
 4747:                               FirstName => 'FirstNamelength',
 4748:                               LastName  => 'LastNamelength',
 4749:             );
 4750:             if (open(my $fh,'<',$fullpath)) {
 4751:                 my $output;
 4752:                 my %lettdig = &letter_to_digits();
 4753:                 my %diglett = reverse(%lettdig);
 4754:                 my $numletts = scalar(keys(%lettdig));
 4755:                 my $num = 0;
 4756:                 while (my $line=<$fh>) {
 4757:                     $num ++;
 4758:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4759:                     $line =~ s{[\r\n]+$}{};
 4760:                     my %found;
 4761:                     my @values = split(/,/,$line,-1);
 4762:                     my ($qstart,$record);
 4763:                     for (my $i=0; $i<@values; $i++) {
 4764:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4765:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4766:                             if ($values[$i] eq '') {
 4767:                                 $values[$i] = $scantronconf{'Qoff'};
 4768:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4769:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4770:                                     $values[$i] = $lettdig{uc($values[$i])};
 4771:                                 }
 4772:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4773:                                 if ($values[$i] =~ /^[0-9]$/) {
 4774:                                     $values[$i] = $diglett{$values[$i]};
 4775:                                 }
 4776:                             } else {
 4777:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4778:                                     my $digit;
 4779:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4780:                                         $digit = $lettdig{uc($values[$i])}-1;
 4781:                                         if ($values[$i] eq 'J') {
 4782:                                             $digit += $numletts;
 4783:                                         }
 4784:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4785:                                         $digit = $values[$i]-1;
 4786:                                         if ($values[$i] eq '0') {
 4787:                                             $digit += $numletts;
 4788:                                         }
 4789:                                     }
 4790:                                     my $qval='';
 4791:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4792:                                         if ($j == $digit) {
 4793:                                             $qval .= $scantronconf{'Qon'};
 4794:                                         } else {
 4795:                                             $qval .= $scantronconf{'Qoff'};
 4796:                                         }
 4797:                                     }
 4798:                                     $values[$i] = $qval;
 4799:                                 }
 4800:                             }
 4801:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4802:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4803:                             }
 4804:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4805:                             if ($numblank > 0) {
 4806:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4807:                             }
 4808:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4809:                                 $qstart = $i;
 4810:                                 $found{$csvbynum{$i}} = $values[$i];
 4811:                             } else {
 4812:                                 $found{'FirstQuestion'} .= $values[$i];
 4813:                             }
 4814:                         } elsif (exists($csvbynum{$i})) {
 4815:                             if ($csvoptions{'rem'}) {
 4816:                                 $values[$i] =~ s/^\s+//;
 4817:                             }
 4818:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4819:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4820:                                     $values[$i] = '0'.$values[$i];
 4821:                                 }
 4822:                             }
 4823:                             $found{$csvbynum{$i}} = $values[$i];
 4824:                         }
 4825:                     }
 4826:                     foreach my $item (@ordered) {
 4827:                         my $currlength = 1+length($record);
 4828:                         my $numspaces = $scantronconf{$item} - $currlength;
 4829:                         if ($numspaces > 0) {
 4830:                             $record .= (' ' x $numspaces);
 4831:                         }
 4832:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4833:                             unless ($item eq 'Qstart') {
 4834:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4835:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4836:                                 }
 4837:                             }
 4838:                             $record .= $found{$mapstart{$item}};
 4839:                         }
 4840:                     }
 4841:                     $output .= "$record\n";
 4842:                 }
 4843:                 close($fh);
 4844:                 if ($output) {
 4845:                     if (open(my $fh,'>',$fullpath)) {
 4846:                         print $fh $output;
 4847:                         close($fh);
 4848:                     }
 4849:                 }
 4850:             }
 4851:         }
 4852:         return;
 4853:     }
 4854: }
 4855: 
 4856: sub letter_to_digits {
 4857:     my %lettdig = (
 4858:                     A => 1,
 4859:                     B => 2,
 4860:                     C => 3,
 4861:                     D => 4,
 4862:                     E => 5,
 4863:                     F => 6,
 4864:                     G => 7,
 4865:                     H => 8,
 4866:                     I => 9,
 4867:                     J => 0,
 4868:                   );
 4869:     return %lettdig;
 4870: }
 4871: 
 4872: sub get_scantron_config {
 4873:     my ($which,$cdom) = @_;
 4874:     my @lines = &get_scantronformat_file($cdom);
 4875:     my %config;
 4876:     #FIXME probably should move to XML it has already gotten a bit much now
 4877:     foreach my $line (@lines) {
 4878:         my ($name,$descrip)=split(/:/,$line);
 4879:         if ($name ne $which ) { next; }
 4880:         chomp($line);
 4881:         my @config=split(/:/,$line);
 4882:         $config{'name'}=$config[0];
 4883:         $config{'description'}=$config[1];
 4884:         $config{'CODElocation'}=$config[2];
 4885:         $config{'CODEstart'}=$config[3];
 4886:         $config{'CODElength'}=$config[4];
 4887:         $config{'IDstart'}=$config[5];
 4888:         $config{'IDlength'}=$config[6];
 4889:         $config{'Qstart'}=$config[7];
 4890:         $config{'Qlength'}=$config[8];
 4891:         $config{'Qoff'}=$config[9];
 4892:         $config{'Qon'}=$config[10];
 4893:         $config{'PaperID'}=$config[11];
 4894:         $config{'PaperIDlength'}=$config[12];
 4895:         $config{'FirstName'}=$config[13];
 4896:         $config{'FirstNamelength'}=$config[14];
 4897:         $config{'LastName'}=$config[15];
 4898:         $config{'LastNamelength'}=$config[16];
 4899:         $config{'BubblesPerRow'}=$config[17];
 4900:         last;
 4901:     }
 4902:     return %config;
 4903: }
 4904: 
 4905: sub get_scantronformat_file {
 4906:     my ($cdom) = @_;
 4907:     if ($cdom eq '') {
 4908:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4909:     }
 4910:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4911:     my $gottab = 0;
 4912:     my @lines;
 4913:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4914:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4915:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4916:             if ($formatfile ne '-1') {
 4917:                 @lines = split("\n",$formatfile,-1);
 4918:                 $gottab = 1;
 4919:             }
 4920:         }
 4921:     }
 4922:     if (!$gottab) {
 4923:         my $confname = $cdom.'-domainconfig';
 4924:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4925:         my $formatfile = &getfile($default);
 4926:         if ($formatfile ne '-1') {
 4927:             @lines = split("\n",$formatfile,-1);
 4928:             $gottab = 1;
 4929:         }
 4930:     }
 4931:     if (!$gottab) {
 4932:         my @domains = &current_machine_domains();
 4933:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4934:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4935:                 @lines = <$fh>;
 4936:                 close($fh);
 4937:             }
 4938:         } else {
 4939:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4940:                 @lines = <$fh>;
 4941:                 close($fh);
 4942:             }
 4943:         }
 4944:         chomp(@lines);
 4945:     }
 4946:     return @lines;
 4947: }
 4948: 
 4949: sub removeuploadedurl {
 4950:     my ($url)=@_;	
 4951:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4952:     return &removeuserfile($uname,$udom,$fname);
 4953: }
 4954: 
 4955: sub removeuserfile {
 4956:     my ($docuname,$docudom,$fname)=@_;
 4957:     my $home=&homeserver($docuname,$docudom);    
 4958:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4959:     if ($result eq 'ok') {	
 4960:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4961:             my $metafile = $fname.'.meta';
 4962:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4963: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4964:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4965:             my $sqlresult = 
 4966:                 &update_portfolio_table($docuname,$docudom,$file,
 4967:                                         'portfolio_metadata',$group,
 4968:                                         'delete');
 4969:         }
 4970:     }
 4971:     return $result;
 4972: }
 4973: 
 4974: sub mkdiruserfile {
 4975:     my ($docuname,$docudom,$dir)=@_;
 4976:     my $home=&homeserver($docuname,$docudom);
 4977:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4978: }
 4979: 
 4980: sub renameuserfile {
 4981:     my ($docuname,$docudom,$old,$new)=@_;
 4982:     my $home=&homeserver($docuname,$docudom);
 4983:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4984:                         &escape("$old").':'.&escape("$new"),$home);
 4985:     if ($result eq 'ok') {
 4986:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4987:             my $oldmeta = $old.'.meta';
 4988:             my $newmeta = $new.'.meta';
 4989:             my $metaresult = 
 4990:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4991: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4992:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4993:             my $sqlresult = 
 4994:                 &update_portfolio_table($docuname,$docudom,$file,
 4995:                                         'portfolio_metadata',$group,
 4996:                                         'delete');
 4997:         }
 4998:     }
 4999:     return $result;
 5000: }
 5001: 
 5002: # ------------------------------------------------------------------------- Log
 5003: 
 5004: sub log {
 5005:     my ($dom,$nam,$hom,$what)=@_;
 5006:     return critical("log:$dom:$nam:$what",$hom);
 5007: }
 5008: 
 5009: # ------------------------------------------------------------------ Course Log
 5010: #
 5011: # This routine flushes several buffers of non-mission-critical nature
 5012: #
 5013: 
 5014: sub flushcourselogs {
 5015:     &logthis('Flushing log buffers');
 5016: #
 5017: # course logs
 5018: # This is a log of all transactions in a course, which can be used
 5019: # for data mining purposes
 5020: #
 5021: # It also collects the courseid database, which lists last transaction
 5022: # times and course titles for all courseids
 5023: #
 5024:     my %courseidbuffer=();
 5025:     foreach my $crsid (keys(%courselogs)) {
 5026:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5027: 		          &escape($courselogs{$crsid}),
 5028: 		          $coursehombuf{$crsid}) eq 'ok') {
 5029: 	    delete $courselogs{$crsid};
 5030:         } else {
 5031:             &logthis('Failed to flush log buffer for '.$crsid);
 5032:             if (length($courselogs{$crsid})>40000) {
 5033:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5034:                         " exceeded maximum size, deleting.</font>");
 5035:                delete $courselogs{$crsid};
 5036:             }
 5037:         }
 5038:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5039:             'description' => $coursedescrbuf{$crsid},
 5040:             'inst_code'    => $courseinstcodebuf{$crsid},
 5041:             'type'        => $coursetypebuf{$crsid},
 5042:             'owner'       => $courseownerbuf{$crsid},
 5043:         };
 5044:     }
 5045: #
 5046: # Write course id database (reverse lookup) to homeserver of courses 
 5047: # Is used in pickcourse
 5048: #
 5049:     foreach my $crs_home (keys(%courseidbuffer)) {
 5050:         my $response = &courseidput(&host_domain($crs_home),
 5051:                                     $courseidbuffer{$crs_home},
 5052:                                     $crs_home,'timeonly');
 5053:     }
 5054: #
 5055: # File accesses
 5056: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5057: #
 5058:     foreach my $entry (keys(%accesshash)) {
 5059:         if ($entry =~ /___count$/) {
 5060:             my ($dom,$name);
 5061:             ($dom,$name,undef)=
 5062: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5063:             if (! defined($dom) || $dom eq '' || 
 5064:                 ! defined($name) || $name eq '') {
 5065:                 my $cid = $env{'request.course.id'};
 5066: #
 5067: # FIXME 11/29/2021
 5068: # Typo in rev. 1.458 (2003/12/09)??
 5069: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5070: #
 5071: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5072: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5073: # in a nohist_accesscount.db file for the user rather than the course.
 5074: #
 5075: # That said there is a lot of noise in the data being stored.
 5076: # So counts for prtspool/  and adm/ etc. are recorded.
 5077: #
 5078: # A review of which items ending '___count' are written to %accesshash should likely be 
 5079: # made before deciding whether to set these to 'course.' instead of 'request.'
 5080: #
 5081: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5082: # accesses for things which are not published resources, regardless of course, and
 5083: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5084: # anyone in the course for things which are not published resources.
 5085: #
 5086: # For an author, nohist_accesscount.db ends up having records for other items
 5087: # mixed up with the legitimate access counts for the author's published resources.
 5088: #
 5089:                 $dom  = $env{'request.'.$cid.'.domain'};
 5090:                 $name = $env{'request.'.$cid.'.num'};
 5091:             }
 5092:             my $value = $accesshash{$entry};
 5093:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5094:             my %temphash=($url => $value);
 5095:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5096:             if ($result eq 'ok') {
 5097:                 delete $accesshash{$entry};
 5098:             }
 5099:         } else {
 5100:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5101:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5102:             my %temphash=($entry => $accesshash{$entry});
 5103:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5104:                 delete $accesshash{$entry};
 5105:             }
 5106:         }
 5107:     }
 5108: #
 5109: # Roles
 5110: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5111: #
 5112:     foreach my $entry (keys(%userrolehash)) {
 5113:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5114: 	    split(/\:/,$entry);
 5115:         if (&Apache::lonnet::put('nohist_userroles',
 5116:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5117:                 $rudom,$runame) eq 'ok') {
 5118: 	    delete $userrolehash{$entry};
 5119:         }
 5120:     }
 5121: #
 5122: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5123: #
 5124:     my %domrolebuffer = ();
 5125:     foreach my $entry (keys(%domainrolehash)) {
 5126:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5127:         if ($domrolebuffer{$rudom}) {
 5128:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5129:                       '='.&escape($domainrolehash{$entry});
 5130:         } else {
 5131:             $domrolebuffer{$rudom}.=&escape($entry).
 5132:                       '='.&escape($domainrolehash{$entry});
 5133:         }
 5134:         delete $domainrolehash{$entry};
 5135:     }
 5136:     foreach my $dom (keys(%domrolebuffer)) {
 5137: 	my %servers;
 5138: 	if (defined(&domain($dom,'primary'))) {
 5139: 	    my $primary=&domain($dom,'primary');
 5140: 	    my $hostname=&hostname($primary);
 5141: 	    $servers{$primary} = $hostname;
 5142: 	} else { 
 5143: 	    %servers = &get_servers($dom,'library');
 5144: 	}
 5145: 	foreach my $tryserver (keys(%servers)) {
 5146: 	    if (&reply('domroleput:'.$dom.':'.
 5147: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5148: 		last;
 5149: 	    } else {  
 5150: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5151: 	    }
 5152:         }
 5153:     }
 5154:     $dumpcount++;
 5155: }
 5156: 
 5157: sub courselog {
 5158:     my $what=shift;
 5159:     $what=time.':'.$what;
 5160:     unless ($env{'request.course.id'}) { return ''; }
 5161:     $coursedombuf{$env{'request.course.id'}}=
 5162:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5163:     $coursenumbuf{$env{'request.course.id'}}=
 5164:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5165:     $coursehombuf{$env{'request.course.id'}}=
 5166:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5167:     $coursedescrbuf{$env{'request.course.id'}}=
 5168:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5169:     $courseinstcodebuf{$env{'request.course.id'}}=
 5170:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5171:     $courseownerbuf{$env{'request.course.id'}}=
 5172:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5173:     $coursetypebuf{$env{'request.course.id'}}=
 5174:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5175:     if (defined $courselogs{$env{'request.course.id'}}) {
 5176: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5177:     } else {
 5178: 	$courselogs{$env{'request.course.id'}}.=$what;
 5179:     }
 5180:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5181: 	&flushcourselogs();
 5182:     }
 5183: }
 5184: 
 5185: sub courseacclog {
 5186:     my $fnsymb=shift;
 5187:     unless ($env{'request.course.id'}) { return ''; }
 5188:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5189:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5190:         $what.=':POST';
 5191:         # FIXME: Probably ought to escape things....
 5192: 	foreach my $key (keys(%env)) {
 5193:             if ($key=~/^form\.(.*)/) {
 5194:                 my $formitem = $1;
 5195:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5196:                     $what.=':'.$formitem.'='.$env{$key};
 5197:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5198:                     if ($formitem eq 'proctorpassword') {
 5199:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5200:                     } else {
 5201:                         $what.=':'.$formitem.'='.$env{$key};
 5202:                     }
 5203:                 }
 5204:             }
 5205:         }
 5206:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5207:         # FIXME: We should not be depending on a form parameter that someone
 5208:         # editing lonsearchcat.pm might change in the future.
 5209:         if ($env{'form.phase'} eq 'course_search') {
 5210:             $what.= ':POST';
 5211:             # FIXME: Probably ought to escape things....
 5212:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5213:                                  'crsdiscuss') {
 5214:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5215:             }
 5216:         }
 5217:     }
 5218:     &courselog($what);
 5219: }
 5220: 
 5221: sub countacc {
 5222:     my $url=&declutter(shift);
 5223:     return if (! defined($url) || $url eq '');
 5224:     unless ($env{'request.course.id'}) { return ''; }
 5225: #
 5226: # Mark that this url was used in this course
 5227: #
 5228:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5229: #
 5230: # Increase the access count for this resource in this child process
 5231: #
 5232:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5233:     $accesshash{$key}++;
 5234: }
 5235: 
 5236: sub linklog {
 5237:     my ($from,$to)=@_;
 5238:     $from=&declutter($from);
 5239:     $to=&declutter($to);
 5240:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5241:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5242: }
 5243: 
 5244: sub statslog {
 5245:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5246:     if ($users<2) { return; }
 5247:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5248:             'course'       => $env{'request.course.id'},
 5249:             'sections'     => '"all"',
 5250:             'num_students' => $users,
 5251:             'part'         => $part,
 5252:             'symb'         => $symb,
 5253:             'mean_tries'   => $av_attempts,
 5254:             'deg_of_diff'  => $degdiff});
 5255:     foreach my $key (keys(%dynstore)) {
 5256:         $accesshash{$key}=$dynstore{$key};
 5257:     }
 5258: }
 5259:   
 5260: sub userrolelog {
 5261:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5262:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5263:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5264:        $userrolehash
 5265:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5266:                     =$tend.':'.$tstart;
 5267:     }
 5268:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5269:        $userrolehash
 5270:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5271:                     =$tend.':'.$tstart;
 5272:     }
 5273:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5274:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5275:        $domainrolehash
 5276:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5277:                     = $tend.':'.$tstart;
 5278:     }
 5279: }
 5280: 
 5281: sub courserolelog {
 5282:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5283:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5284:         my $cdom = $1;
 5285:         my $cnum = $2;
 5286:         my $sec = $3;
 5287:         my $namespace = 'rolelog';
 5288:         my %storehash = (
 5289:                            role    => $trole,
 5290:                            start   => $tstart,
 5291:                            end     => $tend,
 5292:                            selfenroll => $selfenroll,
 5293:                            context    => $context,
 5294:                         );
 5295:         if ($trole eq 'gr') {
 5296:             $namespace = 'groupslog';
 5297:             $storehash{'group'} = $sec;
 5298:         } else {
 5299:             $storehash{'section'} = $sec;
 5300:         }
 5301:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5302:                    $domain,$cnum,$cdom);
 5303:         if (($trole ne 'st') || ($sec ne '')) {
 5304:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5305:         }
 5306:     }
 5307:     return;
 5308: }
 5309: 
 5310: sub domainrolelog {
 5311:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5312:     if ($area =~ m{^/($match_domain)/$}) {
 5313:         my $cdom = $1;
 5314:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5315:         my $namespace = 'rolelog';
 5316:         my %storehash = (
 5317:                            role    => $trole,
 5318:                            start   => $tstart,
 5319:                            end     => $tend,
 5320:                            context => $context,
 5321:                         );
 5322:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5323:                    $domain,$domconfiguser,$cdom);
 5324:     }
 5325:     return;
 5326: 
 5327: }
 5328: 
 5329: sub coauthorrolelog {
 5330:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5331:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5332:         my $audom = $1;
 5333:         my $auname = $2;
 5334:         my $namespace = 'rolelog';
 5335:         my %storehash = (
 5336:                            role    => $trole,
 5337:                            start   => $tstart,
 5338:                            end     => $tend,
 5339:                            context => $context,
 5340:                         );
 5341:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5342:                    $domain,$auname,$audom);
 5343:     }
 5344:     return;
 5345: }
 5346: 
 5347: sub get_course_adv_roles {
 5348:     my ($cid,$codes) = @_;
 5349:     $cid=$env{'request.course.id'} unless (defined($cid));
 5350:     my %coursehash=&coursedescription($cid);
 5351:     my $crstype = &Apache::loncommon::course_type($cid);
 5352:     my %nothide=();
 5353:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5354:         if ($user !~ /:/) {
 5355: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5356:         } else {
 5357:             $nothide{$user}=1;
 5358:         }
 5359:     }
 5360:     my @possdoms = ($coursehash{'domain'});
 5361:     if ($coursehash{'checkforpriv'}) {
 5362:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5363:     }
 5364:     my %returnhash=();
 5365:     my %dumphash=
 5366:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5367:     my $now=time;
 5368:     my %privileged;
 5369:     foreach my $entry (keys(%dumphash)) {
 5370: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5371:         if (($tstart) && ($tstart<0)) { next; }
 5372:         if (($tend) && ($tend<$now)) { next; }
 5373:         if (($tstart) && ($now<$tstart)) { next; }
 5374:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5375: 	if ($username eq '' || $domain eq '') { next; }
 5376:         if ((&privileged($username,$domain,\@possdoms)) &&
 5377:             (!$nothide{$username.':'.$domain})) { next; }
 5378: 	if ($role eq 'cr') { next; }
 5379:         if ($codes) {
 5380:             if ($section) { $role .= ':'.$section; }
 5381:             if ($returnhash{$role}) {
 5382:                 $returnhash{$role}.=','.$username.':'.$domain;
 5383:             } else {
 5384:                 $returnhash{$role}=$username.':'.$domain;
 5385:             }
 5386:         } else {
 5387:             my $key=&plaintext($role,$crstype);
 5388:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5389:             if ($returnhash{$key}) {
 5390: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5391:             } else {
 5392:                 $returnhash{$key}=$username.':'.$domain;
 5393:             }
 5394:         }
 5395:     }
 5396:     return %returnhash;
 5397: }
 5398: 
 5399: sub get_my_roles {
 5400:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5401:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5402:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5403:     my (%dumphash,%nothide);
 5404:     if ($context eq 'userroles') {
 5405:         %dumphash = &dump('roles',$udom,$uname);
 5406:     } else {
 5407:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5408:         if ($hidepriv) {
 5409:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5410:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5411:                 if ($user !~ /:/) {
 5412:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5413:                 } else {
 5414:                     $nothide{$user} = 1;
 5415:                 }
 5416:             }
 5417:         }
 5418:     }
 5419:     my %returnhash=();
 5420:     my $now=time;
 5421:     my %privileged;
 5422:     foreach my $entry (keys(%dumphash)) {
 5423:         my ($role,$tend,$tstart);
 5424:         if ($context eq 'userroles') {
 5425:             next if ($entry =~ /^rolesdef/);
 5426: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5427:         } else {
 5428:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5429:         }
 5430:         if (($tstart) && ($tstart<0)) { next; }
 5431:         my $status = 'active';
 5432:         if (($tend) && ($tend<=$now)) {
 5433:             $status = 'previous';
 5434:         } 
 5435:         if (($tstart) && ($now<$tstart)) {
 5436:             $status = 'future';
 5437:         }
 5438:         if (ref($types) eq 'ARRAY') {
 5439:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5440:                 next;
 5441:             } 
 5442:         } else {
 5443:             if ($status ne 'active') {
 5444:                 next;
 5445:             }
 5446:         }
 5447:         my ($rolecode,$username,$domain,$section,$area);
 5448:         if ($context eq 'userroles') {
 5449:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5450:             (undef,$domain,$username,$section) = split(/\//,$area);
 5451:         } else {
 5452:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5453:         }
 5454:         if (ref($roledoms) eq 'ARRAY') {
 5455:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5456:                 next;
 5457:             }
 5458:         }
 5459:         if (ref($roles) eq 'ARRAY') {
 5460:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5461:                 if ($role =~ /^cr\//) {
 5462:                     if (!grep(/^cr$/,@{$roles})) {
 5463:                         next;
 5464:                     }
 5465:                 } elsif ($role =~ /^gr\//) {
 5466:                     if (!grep(/^gr$/,@{$roles})) {
 5467:                         next;
 5468:                     }
 5469:                 } else {
 5470:                     next;
 5471:                 }
 5472:             }
 5473:         }
 5474:         if ($hidepriv) {
 5475:             my @privroles = ('dc','su');
 5476:             if ($context eq 'userroles') {
 5477:                 next if (grep(/^\Q$role\E$/,@privroles));
 5478:             } else {
 5479:                 my $possdoms = [$domain];
 5480:                 if (ref($roledoms) eq 'ARRAY') {
 5481:                    push(@{$possdoms},@{$roledoms}); 
 5482:                 }
 5483:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5484:                     if (!$nothide{$username.':'.$domain}) {
 5485:                         next;
 5486:                     }
 5487:                 }
 5488:             }
 5489:         }
 5490:         if ($withsec) {
 5491:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5492:                 $tstart.':'.$tend;
 5493:         } else {
 5494:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5495:         }
 5496:     }
 5497:     return %returnhash;
 5498: }
 5499: 
 5500: sub get_all_adhocroles {
 5501:     my ($dom) = @_;
 5502:     my @roles_by_num = ();
 5503:     my %domdefaults = &get_domain_defaults($dom);
 5504:     my (%description,%access_in_dom,%access_info);
 5505:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5506:         my $count = 0;
 5507:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5508:         my %ordered;
 5509:         foreach my $role (sort(keys(%domcurrent))) {
 5510:             my ($order,$desc,$access_in_dom);
 5511:             if (ref($domcurrent{$role}) eq 'HASH') {
 5512:                 $order = $domcurrent{$role}{'order'};
 5513:                 $desc = $domcurrent{$role}{'desc'};
 5514:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5515:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5516:             }
 5517:             if ($order eq '') {
 5518:                 $order = $count;
 5519:             }
 5520:             $ordered{$order} = $role;
 5521:             if ($desc ne '') {
 5522:                 $description{$role} = $desc;
 5523:             } else {
 5524:                 $description{$role}= $role;
 5525:             }
 5526:             $count++;
 5527:         }
 5528:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5529:             push(@roles_by_num,$ordered{$item});
 5530:         }
 5531:     }
 5532:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5533: }
 5534: 
 5535: sub get_my_adhocroles {
 5536:     my ($cid,$checkreg) = @_;
 5537:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5538:     if ($env{'request.course.id'} eq $cid) {
 5539:         $cdom = $env{'course.'.$cid.'.domain'};
 5540:         $cnum = $env{'course.'.$cid.'.num'};
 5541:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5542:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5543:         $cdom = $1;
 5544:         $cnum = $2;
 5545:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5546:                                      $cdom,$cnum);
 5547:     }
 5548:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5549:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5550:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5551:         if ($rosterhash{$user} ne '') {
 5552:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5553:             return ([],{}) if ($type eq 'auto');
 5554:         }
 5555:     }
 5556:     if (($cdom ne '') && ($cnum ne ''))  {
 5557:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5558:             my $then=$env{'user.login.time'};
 5559:             my $update=$env{'user.update.time'};
 5560:             if (!$update) {
 5561:                 $update = $then;
 5562:             }
 5563:             my @liveroles;
 5564:             foreach my $role ('dh','da') {
 5565:                 if ($env{"user.role.$role./$cdom/"}) {
 5566:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5567:                     my $limit = $update;
 5568:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5569:                         $limit = $then;
 5570:                     }
 5571:                     my $activerole = 1;
 5572:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5573:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5574:                     if ($activerole) {
 5575:                         push(@liveroles,$role);
 5576:                     }
 5577:                 }
 5578:             }
 5579:             if (@liveroles) {
 5580:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5581:                     my ($accessref,$accessinfo,%access_in_dom);
 5582:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5583:                     if (ref($roles_by_num) eq 'ARRAY') {
 5584:                         if (@{$roles_by_num}) {
 5585:                             my %settings;
 5586:                             if ($env{'request.course.id'} eq $cid) {
 5587:                                 foreach my $envkey (keys(%env)) {
 5588:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5589:                                         $settings{$1} = $env{$envkey};
 5590:                                     }
 5591:                                 }
 5592:                             } else {
 5593:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5594:                             }
 5595:                             my %setincrs;
 5596:                             if ($settings{'internal.adhocaccess'}) {
 5597:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5598:                             }
 5599:                             my @statuses;
 5600:                             if ($env{'environment.inststatus'}) {
 5601:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5602:                             }
 5603:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5604:                             if (ref($accessref) eq 'HASH') {
 5605:                                 %access_in_dom = %{$accessref};
 5606:                             }
 5607:                             foreach my $role (@{$roles_by_num}) {
 5608:                                 my ($curraccess,@okstatus,@personnel);
 5609:                                 if ($setincrs{$role}) {
 5610:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5611:                                     if ($curraccess eq 'status') {
 5612:                                         @okstatus = split(/\&/,$rest);
 5613:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5614:                                         @personnel = split(/\&/,$rest);
 5615:                                     }
 5616:                                 } else {
 5617:                                     $curraccess = $access_in_dom{$role};
 5618:                                     if (ref($accessinfo) eq 'HASH') {
 5619:                                         if ($curraccess eq 'status') {
 5620:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5621:                                                 @okstatus = @{$accessinfo->{$role}};
 5622:                                             }
 5623:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5624:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5625:                                                 @personnel = @{$accessinfo->{$role}};
 5626:                                             }
 5627:                                         }
 5628:                                     }
 5629:                                 }
 5630:                                 if ($curraccess eq 'none') {
 5631:                                     next;
 5632:                                 } elsif ($curraccess eq 'all') {
 5633:                                     push(@possroles,$role);
 5634:                                 } elsif ($curraccess eq 'dh') {
 5635:                                     if (grep(/^dh$/,@liveroles)) {
 5636:                                         push(@possroles,$role);
 5637:                                     } else {
 5638:                                         next;
 5639:                                     }
 5640:                                 } elsif ($curraccess eq 'da') {
 5641:                                     if (grep(/^da$/,@liveroles)) {
 5642:                                         push(@possroles,$role);
 5643:                                     } else {
 5644:                                         next;
 5645:                                     }
 5646:                                 } elsif ($curraccess eq 'status') {
 5647:                                     if (@okstatus) {
 5648:                                         if (!@statuses) {
 5649:                                             if (grep(/^default$/,@okstatus)) {
 5650:                                                 push(@possroles,$role);
 5651:                                             }
 5652:                                         } else {
 5653:                                             foreach my $status (@okstatus) {
 5654:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5655:                                                     push(@possroles,$role);
 5656:                                                     last;
 5657:                                                 }
 5658:                                             }
 5659:                                         }
 5660:                                     }
 5661:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5662:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5663:                                         if ($curraccess eq 'exc') {
 5664:                                             push(@possroles,$role);
 5665:                                         }
 5666:                                     } elsif ($curraccess eq 'inc') {
 5667:                                         push(@possroles,$role);
 5668:                                     }
 5669:                                 }
 5670:                             }
 5671:                         }
 5672:                     }
 5673:                 }
 5674:             }
 5675:         }
 5676:     }
 5677:     unless (ref($description) eq 'HASH') {
 5678:         if (ref($roles_by_num) eq 'ARRAY') {
 5679:             my %desc;
 5680:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5681:             $description = \%desc;
 5682:         } else {
 5683:             $description = {};
 5684:         }
 5685:     }
 5686:     return (\@possroles,$description);
 5687: }
 5688: 
 5689: # ----------------------------------------------------- Frontpage Announcements
 5690: #
 5691: #
 5692: 
 5693: sub postannounce {
 5694:     my ($server,$text)=@_;
 5695:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5696:     unless ($text=~/\w/) { $text=''; }
 5697:     return &reply('setannounce:'.&escape($text),$server);
 5698: }
 5699: 
 5700: sub getannounce {
 5701: 
 5702:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5703: 	my $announcement='';
 5704: 	while (my $line = <$fh>) { $announcement .= $line; }
 5705: 	close($fh);
 5706: 	if ($announcement=~/\w/) { 
 5707: 	    return 
 5708:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5709:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5710: 	} else {
 5711: 	    return '';
 5712: 	}
 5713:     } else {
 5714: 	return '';
 5715:     }
 5716: }
 5717: 
 5718: # ---------------------------------------------------------- Course ID routines
 5719: # Deal with domain's nohist_courseid.db files
 5720: #
 5721: 
 5722: sub courseidput {
 5723:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5724:     return unless (ref($storehash) eq 'HASH');
 5725:     my $outcome;
 5726:     if ($caller eq 'timeonly') {
 5727:         my $cids = '';
 5728:         foreach my $item (keys(%$storehash)) {
 5729:             $cids.=&escape($item).'&';
 5730:         }
 5731:         $cids=~s/\&$//;
 5732:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5733:                           $coursehome);       
 5734:     } else {
 5735:         my $items = '';
 5736:         foreach my $item (keys(%$storehash)) {
 5737:             $items.= &escape($item).'='.
 5738:                      &freeze_escape($$storehash{$item}).'&';
 5739:         }
 5740:         $items=~s/\&$//;
 5741:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5742:                           $coursehome);
 5743:     }
 5744:     if ($outcome eq 'unknown_cmd') {
 5745:         my $what;
 5746:         foreach my $cid (keys(%$storehash)) {
 5747:             $what .= &escape($cid).'=';
 5748:             foreach my $item ('description','inst_code','owner','type') {
 5749:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5750:             }
 5751:             $what =~ s/\:$/&/;
 5752:         }
 5753:         $what =~ s/\&$//;  
 5754:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5755:     } else {
 5756:         return $outcome;
 5757:     }
 5758: }
 5759: 
 5760: sub courseiddump {
 5761:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5762:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5763:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5764:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5765:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5766:     my $as_hash = 1;
 5767:     my %returnhash;
 5768:     if (!$domfilter) { $domfilter=''; }
 5769:     my %libserv = &all_library();
 5770:     foreach my $tryserver (keys(%libserv)) {
 5771:         if ( (  $hostidflag == 1 
 5772: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5773: 	     || (!defined($hostidflag)) ) {
 5774: 
 5775: 	    if (($domfilter eq '') ||
 5776: 		(&host_domain($tryserver) eq $domfilter)) {
 5777:                 my $rep;
 5778:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5779:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5780:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5781:                                 &escape($descfilter), &escape($instcodefilter), 
 5782:                                 &escape($ownerfilter), &escape($coursefilter),
 5783:                                 &escape($typefilter), &escape($regexp_ok), 
 5784:                                 $as_hash, &escape($selfenrollonly), 
 5785:                                 &escape($catfilter), $showhidden, $caller, 
 5786:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5787:                                 &escape($createdbefore), &escape($createdafter), 
 5788:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5789:                                 $reqcrsdom,&escape($reqinstcode))));
 5790:                 } else {
 5791:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5792:                              $sincefilter.':'.&escape($descfilter).':'.
 5793:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5794:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5795:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5796:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5797:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5798:                              &escape($cc_clone).':'.$cloneonly.':'.
 5799:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5800:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5801:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5802:                 }
 5803:                      
 5804:                 my @pairs=split(/\&/,$rep);
 5805:                 foreach my $item (@pairs) {
 5806:                     my ($key,$value)=split(/\=/,$item,2);
 5807:                     $key = &unescape($key);
 5808:                     next if ($key =~ /^error: 2 /);
 5809:                     my $result = &thaw_unescape($value);
 5810:                     if (ref($result) eq 'HASH') {
 5811:                         $returnhash{$key}=$result;
 5812:                     } else {
 5813:                         my @responses = split(/:/,$value);
 5814:                         my @items = ('description','inst_code','owner','type');
 5815:                         for (my $i=0; $i<@responses; $i++) {
 5816:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5817:                         }
 5818:                     }
 5819:                 }
 5820:             }
 5821:         }
 5822:     }
 5823:     return %returnhash;
 5824: }
 5825: 
 5826: sub courselastaccess {
 5827:     my ($cdom,$cnum,$hostidref) = @_;
 5828:     my %returnhash;
 5829:     if ($cdom && $cnum) {
 5830:         my $chome = &homeserver($cnum,$cdom);
 5831:         if ($chome ne 'no_host') {
 5832:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5833:             &extract_lastaccess(\%returnhash,$rep);
 5834:         }
 5835:     } else {
 5836:         if (!$cdom) { $cdom=''; }
 5837:         my %libserv = &all_library();
 5838:         foreach my $tryserver (keys(%libserv)) {
 5839:             if (ref($hostidref) eq 'ARRAY') {
 5840:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5841:             } 
 5842:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5843:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5844:                 &extract_lastaccess(\%returnhash,$rep);
 5845:             }
 5846:         }
 5847:     }
 5848:     return %returnhash;
 5849: }
 5850: 
 5851: sub extract_lastaccess {
 5852:     my ($returnhash,$rep) = @_;
 5853:     if (ref($returnhash) eq 'HASH') {
 5854:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5855:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5856:                  $rep eq '') {
 5857:             my @pairs=split(/\&/,$rep);
 5858:             foreach my $item (@pairs) {
 5859:                 my ($key,$value)=split(/\=/,$item,2);
 5860:                 $key = &unescape($key);
 5861:                 next if ($key =~ /^error: 2 /);
 5862:                 $returnhash->{$key} = &thaw_unescape($value);
 5863:             }
 5864:         }
 5865:     }
 5866:     return;
 5867: }
 5868: 
 5869: # ---------------------------------------------------------- DC e-mail
 5870: 
 5871: sub dcmailput {
 5872:     my ($domain,$msgid,$message,$server)=@_;
 5873:     my $status = &Apache::lonnet::critical(
 5874:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5875:        &escape($message),$server);
 5876:     return $status;
 5877: }
 5878: 
 5879: sub dcmaildump {
 5880:     my ($dom,$startdate,$enddate,$senders) = @_;
 5881:     my %returnhash=();
 5882: 
 5883:     if (defined(&domain($dom,'primary'))) {
 5884:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5885:                                                          &escape($enddate).':';
 5886: 	my @esc_senders=map { &escape($_)} @$senders;
 5887: 	$cmd.=&escape(join('&',@esc_senders));
 5888: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5889:             my ($key,$value) = split(/\=/,$line,2);
 5890:             if (($key) && ($value)) {
 5891:                 $returnhash{&unescape($key)} = &unescape($value);
 5892:             }
 5893:         }
 5894:     }
 5895:     return %returnhash;
 5896: }
 5897: # ---------------------------------------------------------- Domain roles
 5898: 
 5899: sub get_domain_roles {
 5900:     my ($dom,$roles,$startdate,$enddate)=@_;
 5901:     if ((!defined($startdate)) || ($startdate eq '')) {
 5902:         $startdate = '.';
 5903:     }
 5904:     if ((!defined($enddate)) || ($enddate eq '')) {
 5905:         $enddate = '.';
 5906:     }
 5907:     my $rolelist;
 5908:     if (ref($roles) eq 'ARRAY') {
 5909:         $rolelist = join('&',@{$roles});
 5910:     }
 5911:     my %personnel = ();
 5912: 
 5913:     my %servers = &get_servers($dom,'library');
 5914:     foreach my $tryserver (keys(%servers)) {
 5915: 	%{$personnel{$tryserver}}=();
 5916: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5917: 					    &escape($startdate).':'.
 5918: 					    &escape($enddate).':'.
 5919: 					    &escape($rolelist), $tryserver))) {
 5920: 	    my ($key,$value) = split(/\=/,$line,2);
 5921: 	    if (($key) && ($value)) {
 5922: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5923: 	    }
 5924: 	}
 5925:     }
 5926:     return %personnel;
 5927: }
 5928: 
 5929: sub get_active_domroles {
 5930:     my ($dom,$roles) = @_;
 5931:     return () unless (ref($roles) eq 'ARRAY');
 5932:     my $now = time;
 5933:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5934:     my %domroles;
 5935:     foreach my $server (keys(%dompersonnel)) {
 5936:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5937:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5938:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5939:         }
 5940:     }
 5941:     return %domroles;
 5942: }
 5943: 
 5944: # ----------------------------------------------------------- Interval timing 
 5945: 
 5946: {
 5947: # Caches needed for speedup of navmaps
 5948: # We don't want to cache this for very long at all (5 seconds at most)
 5949: # 
 5950: # The user for whom we cache
 5951: my $cachedkey='';
 5952: # The cached times for this user
 5953: my %cachedtimes=();
 5954: # When this was last done
 5955: my $cachedtime='';
 5956: 
 5957: sub load_all_first_access {
 5958:     my ($uname,$udom,$ignorecache)=@_;
 5959:     if (($cachedkey eq $uname.':'.$udom) &&
 5960:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5961:         (!$ignorecache)) {
 5962:         return;
 5963:     }
 5964:     $cachedtime=time;
 5965:     $cachedkey=$uname.':'.$udom;
 5966:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5967: }
 5968: 
 5969: sub get_first_access {
 5970:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5971:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5972:     if ($argsymb) { $symb=$argsymb; }
 5973:     my ($map,$id,$res)=&decode_symb($symb);
 5974:     if ($argmap) { $map = $argmap; }
 5975:     if ($type eq 'course') {
 5976: 	$res='course';
 5977:     } elsif ($type eq 'map') {
 5978: 	$res=&symbread($map);
 5979:     } else {
 5980: 	$res=$symb;
 5981:     }
 5982:     &load_all_first_access($uname,$udom,$ignorecache);
 5983:     return $cachedtimes{"$courseid\0$res"};
 5984: }
 5985: 
 5986: sub set_first_access {
 5987:     my ($type,$interval)=@_;
 5988:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5989:     my ($map,$id,$res)=&decode_symb($symb);
 5990:     if ($type eq 'course') {
 5991: 	$res='course';
 5992:     } elsif ($type eq 'map') {
 5993: 	$res=&symbread($map);
 5994:     } else {
 5995: 	$res=$symb;
 5996:     }
 5997:     $cachedkey='';
 5998:     my $firstaccess=&get_first_access($type,$symb,$map);
 5999:     if ($firstaccess) {
 6000:         &logthis("First access time already set ($firstaccess) when attempting ".
 6001:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6002:                  "in $courseid");
 6003:         return 'already_set';
 6004:     } else {
 6005:         my $start = time;
 6006: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6007:                           $udom,$uname);
 6008:         if ($putres eq 'ok') {
 6009:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6010:                  $udom,$uname); 
 6011:             &appenv(
 6012:                      {
 6013:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6014:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6015:                      }
 6016:                   );
 6017:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6018:                 $cachedtimes{"$courseid\0$res"} = $start;
 6019:             }
 6020:         } elsif ($putres ne 'refused') {
 6021:             &logthis("Result: $putres when attempting to set first access time ".
 6022:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6023:         }
 6024:         return $putres;
 6025:     }
 6026:     return 'already_set';
 6027: }
 6028: }
 6029: 
 6030: # --------------------------------------------- Set Expire Date for Spreadsheet
 6031: 
 6032: sub expirespread {
 6033:     my ($uname,$udom,$stype,$usymb)=@_;
 6034:     my $cid=$env{'request.course.id'}; 
 6035:     if ($cid) {
 6036:        my $now=time;
 6037:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6038:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6039:                             $env{'course.'.$cid.'.num'}.
 6040: 	        	    ':nohist_expirationdates:'.
 6041:                             &escape($key).'='.$now,
 6042:                             $env{'course.'.$cid.'.home'})
 6043:     }
 6044:     return 'ok';
 6045: }
 6046: 
 6047: # ----------------------------------------------------- Devalidate Spreadsheets
 6048: 
 6049: sub devalidate {
 6050:     my ($symb,$uname,$udom)=@_;
 6051:     my $cid=$env{'request.course.id'}; 
 6052:     if ($cid) {
 6053:         # delete the stored spreadsheets for
 6054:         # - the student level sheet of this user in course's homespace
 6055:         # - the assessment level sheet for this resource 
 6056:         #   for this user in user's homespace
 6057: 	# - current conditional state info
 6058: 	my $key=$uname.':'.$udom.':';
 6059:         my $status=
 6060: 	    &del('nohist_calculatedsheets',
 6061: 		 [$key.'studentcalc:'],
 6062: 		 $env{'course.'.$cid.'.domain'},
 6063: 		 $env{'course.'.$cid.'.num'})
 6064: 		.' '.
 6065: 	    &del('nohist_calculatedsheets_'.$cid,
 6066: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6067:         unless ($status eq 'ok ok') {
 6068:            &logthis('Could not devalidate spreadsheet '.
 6069:                     $uname.' at '.$udom.' for '.
 6070: 		    $symb.': '.$status);
 6071:         }
 6072: 	&delenv('user.state.'.$cid);
 6073:     }
 6074: }
 6075: 
 6076: sub get_scalar {
 6077:     my ($string,$end) = @_;
 6078:     my $value;
 6079:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6080: 	$value = $1;
 6081:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6082: 	$value = $1;
 6083:     }
 6084:     return &unescape($value);
 6085: }
 6086: 
 6087: sub array2str {
 6088:   my (@array) = @_;
 6089:   my $result=&arrayref2str(\@array);
 6090:   $result=~s/^__ARRAY_REF__//;
 6091:   $result=~s/__END_ARRAY_REF__$//;
 6092:   return $result;
 6093: }
 6094: 
 6095: sub arrayref2str {
 6096:   my ($arrayref) = @_;
 6097:   my $result='__ARRAY_REF__';
 6098:   foreach my $elem (@$arrayref) {
 6099:     if(ref($elem) eq 'ARRAY') {
 6100:       $result.=&arrayref2str($elem).'&';
 6101:     } elsif(ref($elem) eq 'HASH') {
 6102:       $result.=&hashref2str($elem).'&';
 6103:     } elsif(ref($elem)) {
 6104:       #print("Got a ref of ".(ref($elem))." skipping.");
 6105:     } else {
 6106:       $result.=&escape($elem).'&';
 6107:     }
 6108:   }
 6109:   $result=~s/\&$//;
 6110:   $result .= '__END_ARRAY_REF__';
 6111:   return $result;
 6112: }
 6113: 
 6114: sub hash2str {
 6115:   my (%hash) = @_;
 6116:   my $result=&hashref2str(\%hash);
 6117:   $result=~s/^__HASH_REF__//;
 6118:   $result=~s/__END_HASH_REF__$//;
 6119:   return $result;
 6120: }
 6121: 
 6122: sub hashref2str {
 6123:   my ($hashref)=@_;
 6124:   my $result='__HASH_REF__';
 6125:   foreach my $key (sort(keys(%$hashref))) {
 6126:     if (ref($key) eq 'ARRAY') {
 6127:       $result.=&arrayref2str($key).'=';
 6128:     } elsif (ref($key) eq 'HASH') {
 6129:       $result.=&hashref2str($key).'=';
 6130:     } elsif (ref($key)) {
 6131:       $result.='=';
 6132:       #print("Got a ref of ".(ref($key))." skipping.");
 6133:     } else {
 6134: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6135:     }
 6136: 
 6137:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6138:       $result.=&arrayref2str($hashref->{$key}).'&';
 6139:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6140:       $result.=&hashref2str($hashref->{$key}).'&';
 6141:     } elsif(ref($hashref->{$key})) {
 6142:        $result.='&';
 6143:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6144:     } else {
 6145:       $result.=&escape($hashref->{$key}).'&';
 6146:     }
 6147:   }
 6148:   $result=~s/\&$//;
 6149:   $result .= '__END_HASH_REF__';
 6150:   return $result;
 6151: }
 6152: 
 6153: sub str2hash {
 6154:     my ($string)=@_;
 6155:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6156:     return %$hash;
 6157: }
 6158: 
 6159: sub str2hashref {
 6160:   my ($string) = @_;
 6161: 
 6162:   my %hash;
 6163: 
 6164:   if($string !~ /^__HASH_REF__/) {
 6165:       if (! ($string eq '' || !defined($string))) {
 6166: 	  $hash{'error'}='Not hash reference';
 6167:       }
 6168:       return (\%hash, $string);
 6169:   }
 6170: 
 6171:   $string =~ s/^__HASH_REF__//;
 6172: 
 6173:   while($string !~ /^__END_HASH_REF__/) {
 6174:       #key
 6175:       my $key='';
 6176:       if($string =~ /^__HASH_REF__/) {
 6177:           ($key, $string)=&str2hashref($string);
 6178:           if(defined($key->{'error'})) {
 6179:               $hash{'error'}='Bad data';
 6180:               return (\%hash, $string);
 6181:           }
 6182:       } elsif($string =~ /^__ARRAY_REF__/) {
 6183:           ($key, $string)=&str2arrayref($string);
 6184:           if($key->[0] eq 'Array reference error') {
 6185:               $hash{'error'}='Bad data';
 6186:               return (\%hash, $string);
 6187:           }
 6188:       } else {
 6189:           $string =~ s/^(.*?)=//;
 6190: 	  $key=&unescape($1);
 6191:       }
 6192:       $string =~ s/^=//;
 6193: 
 6194:       #value
 6195:       my $value='';
 6196:       if($string =~ /^__HASH_REF__/) {
 6197:           ($value, $string)=&str2hashref($string);
 6198:           if(defined($value->{'error'})) {
 6199:               $hash{'error'}='Bad data';
 6200:               return (\%hash, $string);
 6201:           }
 6202:       } elsif($string =~ /^__ARRAY_REF__/) {
 6203:           ($value, $string)=&str2arrayref($string);
 6204:           if($value->[0] eq 'Array reference error') {
 6205:               $hash{'error'}='Bad data';
 6206:               return (\%hash, $string);
 6207:           }
 6208:       } else {
 6209: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6210:       }
 6211:       $string =~ s/^&//;
 6212: 
 6213:       $hash{$key}=$value;
 6214:   }
 6215: 
 6216:   $string =~ s/^__END_HASH_REF__//;
 6217: 
 6218:   return (\%hash, $string);
 6219: }
 6220: 
 6221: sub str2array {
 6222:     my ($string)=@_;
 6223:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6224:     return @$array;
 6225: }
 6226: 
 6227: sub str2arrayref {
 6228:   my ($string) = @_;
 6229:   my @array;
 6230: 
 6231:   if($string !~ /^__ARRAY_REF__/) {
 6232:       if (! ($string eq '' || !defined($string))) {
 6233: 	  $array[0]='Array reference error';
 6234:       }
 6235:       return (\@array, $string);
 6236:   }
 6237: 
 6238:   $string =~ s/^__ARRAY_REF__//;
 6239: 
 6240:   while($string !~ /^__END_ARRAY_REF__/) {
 6241:       my $value='';
 6242:       if($string =~ /^__HASH_REF__/) {
 6243:           ($value, $string)=&str2hashref($string);
 6244:           if(defined($value->{'error'})) {
 6245:               $array[0] ='Array reference error';
 6246:               return (\@array, $string);
 6247:           }
 6248:       } elsif($string =~ /^__ARRAY_REF__/) {
 6249:           ($value, $string)=&str2arrayref($string);
 6250:           if($value->[0] eq 'Array reference error') {
 6251:               $array[0] ='Array reference error';
 6252:               return (\@array, $string);
 6253:           }
 6254:       } else {
 6255: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6256:       }
 6257:       $string =~ s/^&//;
 6258: 
 6259:       push(@array, $value);
 6260:   }
 6261: 
 6262:   $string =~ s/^__END_ARRAY_REF__//;
 6263: 
 6264:   return (\@array, $string);
 6265: }
 6266: 
 6267: # -------------------------------------------------------------------Temp Store
 6268: 
 6269: sub tmpreset {
 6270:   my ($symb,$namespace,$domain,$stuname) = @_;
 6271:   if (!$symb) {
 6272:     $symb=&symbread();
 6273:     if (!$symb) { $symb= $env{'request.url'}; }
 6274:   }
 6275:   $symb=escape($symb);
 6276: 
 6277:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6278:   $namespace=~s/\//\_/g;
 6279:   $namespace=~s/\W//g;
 6280: 
 6281:   if (!$domain) { $domain=$env{'user.domain'}; }
 6282:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6283:   if ($domain eq 'public' && $stuname eq 'public') {
 6284:       $stuname=&get_requestor_ip();
 6285:   }
 6286:   my $path=LONCAPA::tempdir();
 6287:   my %hash;
 6288:   if (tie(%hash,'GDBM_File',
 6289: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6290: 	  &GDBM_WRCREAT(),0640)) {
 6291:     foreach my $key (keys(%hash)) {
 6292:       if ($key=~ /:$symb/) {
 6293: 	delete($hash{$key});
 6294:       }
 6295:     }
 6296:   }
 6297: }
 6298: 
 6299: sub tmpstore {
 6300:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6301: 
 6302:   if (!$symb) {
 6303:     $symb=&symbread();
 6304:     if (!$symb) { $symb= $env{'request.url'}; }
 6305:   }
 6306:   $symb=escape($symb);
 6307: 
 6308:   if (!$namespace) {
 6309:     # I don't think we would ever want to store this for a course.
 6310:     # it seems this will only be used if we don't have a course.
 6311:     #$namespace=$env{'request.course.id'};
 6312:     #if (!$namespace) {
 6313:       $namespace=$env{'request.state'};
 6314:     #}
 6315:   }
 6316:   $namespace=~s/\//\_/g;
 6317:   $namespace=~s/\W//g;
 6318:   if (!$domain) { $domain=$env{'user.domain'}; }
 6319:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6320:   if ($domain eq 'public' && $stuname eq 'public') {
 6321:       $stuname=&get_requestor_ip();
 6322:   }
 6323:   my $now=time;
 6324:   my %hash;
 6325:   my $path=LONCAPA::tempdir();
 6326:   if (tie(%hash,'GDBM_File',
 6327: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6328: 	  &GDBM_WRCREAT(),0640)) {
 6329:     $hash{"version:$symb"}++;
 6330:     my $version=$hash{"version:$symb"};
 6331:     my $allkeys=''; 
 6332:     foreach my $key (keys(%$storehash)) {
 6333:       $allkeys.=$key.':';
 6334:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6335:     }
 6336:     $hash{"$version:$symb:timestamp"}=$now;
 6337:     $allkeys.='timestamp';
 6338:     $hash{"$version:keys:$symb"}=$allkeys;
 6339:     if (untie(%hash)) {
 6340:       return 'ok';
 6341:     } else {
 6342:       return "error:$!";
 6343:     }
 6344:   } else {
 6345:     return "error:$!";
 6346:   }
 6347: }
 6348: 
 6349: # -----------------------------------------------------------------Temp Restore
 6350: 
 6351: sub tmprestore {
 6352:   my ($symb,$namespace,$domain,$stuname) = @_;
 6353: 
 6354:   if (!$symb) {
 6355:     $symb=&symbread();
 6356:     if (!$symb) { $symb= $env{'request.url'}; }
 6357:   }
 6358:   $symb=escape($symb);
 6359: 
 6360:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6361: 
 6362:   if (!$domain) { $domain=$env{'user.domain'}; }
 6363:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6364:   if ($domain eq 'public' && $stuname eq 'public') {
 6365:       $stuname=&get_requestor_ip();
 6366:   }
 6367:   my %returnhash;
 6368:   $namespace=~s/\//\_/g;
 6369:   $namespace=~s/\W//g;
 6370:   my %hash;
 6371:   my $path=LONCAPA::tempdir();
 6372:   if (tie(%hash,'GDBM_File',
 6373: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6374: 	  &GDBM_READER(),0640)) {
 6375:     my $version=$hash{"version:$symb"};
 6376:     $returnhash{'version'}=$version;
 6377:     my $scope;
 6378:     for ($scope=1;$scope<=$version;$scope++) {
 6379:       my $vkeys=$hash{"$scope:keys:$symb"};
 6380:       my @keys=split(/:/,$vkeys);
 6381:       my $key;
 6382:       $returnhash{"$scope:keys"}=$vkeys;
 6383:       foreach $key (@keys) {
 6384: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6385: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6386:       }
 6387:     }
 6388:     if (!(untie(%hash))) {
 6389:       return "error:$!";
 6390:     }
 6391:   } else {
 6392:     return "error:$!";
 6393:   }
 6394:   return %returnhash;
 6395: }
 6396: 
 6397: # ----------------------------------------------------------------------- Store
 6398: 
 6399: sub store {
 6400:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6401:     my $home='';
 6402: 
 6403:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6404: 
 6405:     $symb=&symbclean($symb);
 6406:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6407: 
 6408:     if (!$domain) { $domain=$env{'user.domain'}; }
 6409:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6410: 
 6411:     &devalidate($symb,$stuname,$domain);
 6412: 
 6413:     $symb=escape($symb);
 6414:     if (!$namespace) { 
 6415:        unless ($namespace=$env{'request.course.id'}) { 
 6416:           return ''; 
 6417:        } 
 6418:     }
 6419:     if (!$home) { $home=$env{'user.home'}; }
 6420: 
 6421:     $$storehash{'ip'}=&get_requestor_ip();
 6422:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6423: 
 6424:     my $namevalue='';
 6425:     foreach my $key (keys(%$storehash)) {
 6426:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6427:     }
 6428:     $namevalue=~s/\&$//;
 6429:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6430:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6431: }
 6432: 
 6433: # -------------------------------------------------------------- Critical Store
 6434: 
 6435: sub cstore {
 6436:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6437:     my $home='';
 6438: 
 6439:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6440: 
 6441:     $symb=&symbclean($symb);
 6442:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6443: 
 6444:     if (!$domain) { $domain=$env{'user.domain'}; }
 6445:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6446: 
 6447:     &devalidate($symb,$stuname,$domain);
 6448: 
 6449:     $symb=escape($symb);
 6450:     if (!$namespace) { 
 6451:        unless ($namespace=$env{'request.course.id'}) { 
 6452:           return ''; 
 6453:        } 
 6454:     }
 6455:     if (!$home) { $home=$env{'user.home'}; }
 6456: 
 6457:     $$storehash{'ip'}=&get_requestor_ip();
 6458:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6459: 
 6460:     my $namevalue='';
 6461:     foreach my $key (keys(%$storehash)) {
 6462:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6463:     }
 6464:     $namevalue=~s/\&$//;
 6465:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6466:     return critical
 6467:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6468: }
 6469: 
 6470: # --------------------------------------------------------------------- Restore
 6471: 
 6472: sub restore {
 6473:     my ($symb,$namespace,$domain,$stuname) = @_;
 6474:     my $home='';
 6475: 
 6476:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6477: 
 6478:     if (!$symb) {
 6479:         return if ($namespace eq 'courserequests');
 6480:         unless ($symb=escape(&symbread())) { return ''; }
 6481:     } else {
 6482:         unless ($namespace eq 'courserequests') {
 6483:             $symb=&escape(&symbclean($symb));
 6484:         }
 6485:     }
 6486:     if (!$namespace) { 
 6487:        unless ($namespace=$env{'request.course.id'}) { 
 6488:           return ''; 
 6489:        } 
 6490:     }
 6491:     if (!$domain) { $domain=$env{'user.domain'}; }
 6492:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6493:     if (!$home) { $home=$env{'user.home'}; }
 6494:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6495: 
 6496:     my %returnhash=();
 6497:     foreach my $line (split(/\&/,$answer)) {
 6498: 	my ($name,$value)=split(/\=/,$line);
 6499:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6500:     }
 6501:     my $version;
 6502:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6503:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6504:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6505:        }
 6506:     }
 6507:     return %returnhash;
 6508: }
 6509: 
 6510: # ---------------------------------------------------------- Course Description
 6511: #
 6512: #  
 6513: 
 6514: sub coursedescription {
 6515:     my ($courseid,$args)=@_;
 6516:     $courseid=~s/^\///;
 6517:     $courseid=~s/\_/\//g;
 6518:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6519:     my $chome=&homeserver($cnum,$cdomain);
 6520:     my $normalid=$cdomain.'_'.$cnum;
 6521:     # need to always cache even if we get errors otherwise we keep 
 6522:     # trying and trying and trying to get the course description.
 6523:     my %envhash=();
 6524:     my %returnhash=();
 6525:     
 6526:     my $expiretime=600;
 6527:     if ($env{'request.course.id'} eq $normalid) {
 6528: 	$expiretime=120;
 6529:     }
 6530: 
 6531:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6532:     if (!$args->{'freshen_cache'}
 6533: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6534: 	foreach my $key (keys(%env)) {
 6535: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6536: 	    my ($setting) = $1;
 6537: 	    $returnhash{$setting} = $env{$key};
 6538: 	}
 6539: 	return %returnhash;
 6540:     }
 6541: 
 6542:     # get the data again
 6543: 
 6544:     if (!$args->{'one_time'}) {
 6545: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6546:     }
 6547: 
 6548:     if ($chome ne 'no_host') {
 6549:        %returnhash=&dump('environment',$cdomain,$cnum);
 6550:        if (!exists($returnhash{'con_lost'})) {
 6551: 	   my $username = $env{'user.name'}; # Defult username
 6552: 	   if(defined $args->{'user'}) {
 6553: 	       $username = $args->{'user'};
 6554: 	   }
 6555:            $returnhash{'home'}= $chome;
 6556: 	   $returnhash{'domain'} = $cdomain;
 6557: 	   $returnhash{'num'} = $cnum;
 6558:            if (!defined($returnhash{'type'})) {
 6559:                $returnhash{'type'} = 'Course';
 6560:            }
 6561:            while (my ($name,$value) = each %returnhash) {
 6562:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6563:            }
 6564:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6565:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6566: 	       $username.'_'.$cdomain.'_'.$cnum;
 6567:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6568:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6569:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6570:        }
 6571:     }
 6572:     if (!$args->{'one_time'}) {
 6573: 	&appenv(\%envhash);
 6574:     }
 6575:     return %returnhash;
 6576: }
 6577: 
 6578: sub update_released_required {
 6579:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6580:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6581:         $cid = $env{'request.course.id'};
 6582:         $cdom = $env{'course.'.$cid.'.domain'};
 6583:         $cnum = $env{'course.'.$cid.'.num'};
 6584:         $chome = $env{'course.'.$cid.'.home'};
 6585:     }
 6586:     if ($needsrelease) {
 6587:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6588:         my $needsupdate;
 6589:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6590:             $needsupdate = 1;
 6591:         } else {
 6592:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6593:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6594:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6595:                 $needsupdate = 1;
 6596:             }
 6597:         }
 6598:         if ($needsupdate) {
 6599:             my %needshash = (
 6600:                              'internal.releaserequired' => $needsrelease,
 6601:                             );
 6602:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6603:             if ($putresult eq 'ok') {
 6604:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6605:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6606:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6607:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6608:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6609:                 }
 6610:             }
 6611:         }
 6612:     }
 6613:     return;
 6614: }
 6615: 
 6616: # -------------------------------------------------See if a user is privileged
 6617: 
 6618: sub privileged {
 6619:     my ($username,$domain,$possdomains,$possroles)=@_;
 6620:     my $now = time;
 6621:     my $roles;
 6622:     if (ref($possroles) eq 'ARRAY') {
 6623:         $roles = $possroles; 
 6624:     } else {
 6625:         $roles = ['dc','su'];
 6626:     }
 6627:     if (ref($possdomains) eq 'ARRAY') {
 6628:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6629:         foreach my $dom (@{$possdomains}) {
 6630:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6631:                 (ref($privileged{$dom}) eq 'HASH')) {
 6632:                 foreach my $role (@{$roles}) {
 6633:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6634:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6635:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6636:                             return 1 unless (($end && $end < $now) ||
 6637:                                              ($start && $start > $now));
 6638:                         }
 6639:                     }
 6640:                 }
 6641:             }
 6642:         }
 6643:     } else {
 6644:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6645:         my $now = time;
 6646: 
 6647:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6648:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6649:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6650:                 return 1 unless ($tend && $tend < $now) 
 6651:                         or ($tstart && $tstart > $now);
 6652:             }
 6653:         }
 6654:     }
 6655:     return 0;
 6656: }
 6657: 
 6658: sub privileged_by_domain {
 6659:     my ($domains,$roles) = @_;
 6660:     my %privileged = ();
 6661:     my $cachetime = 60*60*24;
 6662:     my $now = time;
 6663:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6664:         return %privileged;
 6665:     }
 6666:     foreach my $dom (@{$domains}) {
 6667:         next if (ref($privileged{$dom}) eq 'HASH');
 6668:         my $needroles;
 6669:         foreach my $role (@{$roles}) {
 6670:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6671:             if (defined($cached)) {
 6672:                 if (ref($result) eq 'HASH') {
 6673:                     $privileged{$dom}{$role} = $result;
 6674:                 }
 6675:             } else {
 6676:                 $needroles = 1;
 6677:             }
 6678:         }
 6679:         if ($needroles) {
 6680:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6681:             $privileged{$dom} = {};
 6682:             foreach my $server (keys(%dompersonnel)) {
 6683:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6684:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6685:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6686:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6687:                         next if ($end && $end < $now);
 6688:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6689:                             $dompersonnel{$server}{$item};
 6690:                     }
 6691:                 }
 6692:             }
 6693:             if (ref($privileged{$dom}) eq 'HASH') {
 6694:                 foreach my $role (@{$roles}) {
 6695:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6696:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6697:                     } else {
 6698:                         my %hash = ();
 6699:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6700:                     }
 6701:                 }
 6702:             }
 6703:         }
 6704:     }
 6705:     return %privileged;
 6706: }
 6707: 
 6708: # -------------------------------------------------------- Get user privileges
 6709: 
 6710: sub rolesinit {
 6711:     my ($domain, $username) = @_;
 6712:     my %userroles = ('user.login.time' => time);
 6713:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6714: 
 6715:     # firstaccess and timerinterval are related to timed maps/resources. 
 6716:     # also, blocking can be triggered by an activating timer
 6717:     # it's saved in the user's %env.
 6718:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6719:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6720:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6721:         %timerintchk, %timerintenv);
 6722: 
 6723:     foreach my $key (keys(%firstaccess)) {
 6724:         my ($cid, $rest) = split(/\0/, $key);
 6725:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6726:     }
 6727: 
 6728:     foreach my $key (keys(%timerinterval)) {
 6729:         my ($cid,$rest) = split(/\0/,$key);
 6730:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6731:     }
 6732: 
 6733:     my %allroles=();
 6734:     my %allgroups=();
 6735: 
 6736:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6737:         my $role = $rolesdump{$area};
 6738:         $area =~ s/\_\w\w$//;
 6739: 
 6740:         my ($trole, $tend, $tstart, $group_privs);
 6741: 
 6742:         if ($role =~ /^cr/) {
 6743:         # Custom role, defined by a user 
 6744:         # e.g., user.role.cr/msu/smith/mynewrole
 6745:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6746:                 $trole = $1;
 6747:                 ($tend, $tstart) = split('_', $2);
 6748:             } else {
 6749:                 $trole = $role;
 6750:             }
 6751:         } elsif ($role =~ m|^gr/|) {
 6752:         # Role of member in a group, defined within a course/community
 6753:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6754:             ($trole, $tend, $tstart) = split(/_/, $role);
 6755:             next if $tstart eq '-1';
 6756:             ($trole, $group_privs) = split(/\//, $trole);
 6757:             $group_privs = &unescape($group_privs);
 6758:         } else {
 6759:         # Just a normal role, defined in roles.tab
 6760:             ($trole, $tend, $tstart) = split(/_/,$role);
 6761:         }
 6762: 
 6763:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6764:                  $username);
 6765:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6766: 
 6767:         # role expired or not available yet?
 6768:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6769:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6770: 
 6771:         next if $area eq '' or $trole eq '';
 6772: 
 6773:         my $spec = "$trole.$area";
 6774:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6775: 
 6776:         if ($trole =~ /^cr\//) {
 6777:         # Custom role, defined by a user
 6778:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6779:         } elsif ($trole eq 'gr') {
 6780:         # Role of a member in a group, defined within a course/community
 6781:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6782:             next;
 6783:         } else {
 6784:         # Normal role, defined in roles.tab
 6785:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6786:         }
 6787: 
 6788:         my $cid = $tdomain.'_'.$trest;
 6789:         unless ($firstaccchk{$cid}) {
 6790:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6791:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6792:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6793:                         $coursetimerstarts{$cid}{$item}; 
 6794:                 }
 6795:             }
 6796:             $firstaccchk{$cid} = 1;
 6797:         }
 6798:         unless ($timerintchk{$cid}) {
 6799:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6800:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6801:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6802:                        $coursetimerintervals{$cid}{$item};
 6803:                 }
 6804:             }
 6805:             $timerintchk{$cid} = 1;
 6806:         }
 6807:     }
 6808: 
 6809:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6810:                                                           \%allroles, \%allgroups);
 6811:     $env{'user.adv'} = $userroles{'user.adv'};
 6812:     $env{'user.rar'} = $userroles{'user.rar'};
 6813: 
 6814:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6815: }
 6816: 
 6817: sub set_arearole {
 6818:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6819:     unless ($nolog) {
 6820: # log the associated role with the area
 6821:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6822:     }
 6823:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6824: }
 6825: 
 6826: sub custom_roleprivs {
 6827:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6828:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6829:     my $homsvr = &homeserver($rauthor,$rdomain);
 6830:     if (&hostname($homsvr) ne '') {
 6831:         my ($rdummy,$roledef)=
 6832:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6833:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6834:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6835:             if (defined($syspriv)) {
 6836:                 if ($trest =~ /^$match_community$/) {
 6837:                     $syspriv =~ s/bre\&S//; 
 6838:                 }
 6839:                 $$allroles{'cm./'}.=':'.$syspriv;
 6840:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6841:             }
 6842:             if ($tdomain ne '') {
 6843:                 if (defined($dompriv)) {
 6844:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6845:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6846:                 }
 6847:                 if (($trest ne '') && (defined($coursepriv))) {
 6848:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6849:                         my $rolename = $1;
 6850:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6851:                     }
 6852:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6853:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6854:                 }
 6855:             }
 6856:         }
 6857:     }
 6858: }
 6859: 
 6860: sub course_adhocrole_privs {
 6861:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6862:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6863:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6864:         my (%currprivs,%storeprivs);
 6865:         foreach my $item (split(/:/,$coursepriv)) {
 6866:             my ($priv,$restrict) = split(/\&/,$item);
 6867:             $currprivs{$priv} = $restrict;
 6868:         }
 6869:         my (%possadd,%possremove,%full);
 6870:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6871:             my ($priv,$restrict)=split(/\&/,$item);
 6872:             $full{$priv} = $restrict;
 6873:         }
 6874:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6875:             next if ($item eq '');
 6876:             my ($rule,$rest) = split(/=/,$item);
 6877:             next unless (($rule eq 'off') || ($rule eq 'on'));
 6878:             foreach my $priv (split(/:/,$rest)) {
 6879:                 if ($priv ne '') {
 6880:                     if ($rule eq 'off') {
 6881:                         $possremove{$priv} = 1;
 6882:                     } else {
 6883:                         $possadd{$priv} = 1;
 6884:                     }
 6885:                 }
 6886:             }
 6887:         }
 6888:         foreach my $priv (sort(keys(%full))) {
 6889:             if (exists($currprivs{$priv})) {
 6890:                 unless (exists($possremove{$priv})) {
 6891:                     $storeprivs{$priv} = $currprivs{$priv};
 6892:                 }
 6893:             } elsif (exists($possadd{$priv})) {
 6894:                 $storeprivs{$priv} = $full{$priv};
 6895:             }
 6896:         }
 6897:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6898:     }
 6899:     return $coursepriv;
 6900: }
 6901: 
 6902: sub group_roleprivs {
 6903:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6904:     my $access = 1;
 6905:     my $now = time;
 6906:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6907:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6908:     if ($access) {
 6909:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6910:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6911:     }
 6912: }
 6913: 
 6914: sub standard_roleprivs {
 6915:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6916:     if (defined($pr{$trole.':s'})) {
 6917:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6918:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6919:     }
 6920:     if ($tdomain ne '') {
 6921:         if (defined($pr{$trole.':d'})) {
 6922:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6923:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6924:         }
 6925:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6926:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6927:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6928:         }
 6929:     }
 6930: }
 6931: 
 6932: sub set_userprivs {
 6933:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6934:     my $author=0;
 6935:     my $adv=0;
 6936:     my $rar=0;
 6937:     my %grouproles = ();
 6938:     if (keys(%{$allgroups}) > 0) {
 6939:         my @groupkeys; 
 6940:         foreach my $role (keys(%{$allroles})) {
 6941:             push(@groupkeys,$role);
 6942:         }
 6943:         if (ref($groups_roles) eq 'HASH') {
 6944:             foreach my $key (keys(%{$groups_roles})) {
 6945:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6946:                     push(@groupkeys,$key);
 6947:                 }
 6948:             }
 6949:         }
 6950:         if (@groupkeys > 0) {
 6951:             foreach my $role (@groupkeys) {
 6952:                 my ($trole,$area,$sec,$extendedarea);
 6953:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6954:                     $trole = $1;
 6955:                     $area = $2;
 6956:                     $sec = $3;
 6957:                     $extendedarea = $area.$sec;
 6958:                     if (exists($$allgroups{$area})) {
 6959:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6960:                             my $spec = $trole.'.'.$extendedarea;
 6961:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6962:                                                 $$allgroups{$area}{$group};
 6963:                         }
 6964:                     }
 6965:                 }
 6966:             }
 6967:         }
 6968:     }
 6969:     foreach my $group (keys(%grouproles)) {
 6970:         $$allroles{$group} = $grouproles{$group};
 6971:     }
 6972:     foreach my $role (keys(%{$allroles})) {
 6973:         my %thesepriv;
 6974:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6975:         foreach my $item (split(/:/,$$allroles{$role})) {
 6976:             if ($item ne '') {
 6977:                 my ($privilege,$restrictions)=split(/&/,$item);
 6978:                 if ($restrictions eq '') {
 6979:                     $thesepriv{$privilege}='F';
 6980:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6981:                     $thesepriv{$privilege}.=$restrictions;
 6982:                 }
 6983:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6984:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6985:             }
 6986:         }
 6987:         my $thesestr='';
 6988:         foreach my $priv (sort(keys(%thesepriv))) {
 6989: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6990: 	}
 6991:         $userroles->{'user.priv.'.$role} = $thesestr;
 6992:     }
 6993:     return ($author,$adv,$rar);
 6994: }
 6995: 
 6996: sub role_status {
 6997:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6998:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6999:         my ($one,$two) = split(m{\./},$rolekey,2);
 7000:         (undef,undef,$$role) = split(/\./,$one,3);
 7001:         unless (!defined($$role) || $$role eq '') {
 7002:             $$where = '/'.$two;
 7003:             $$trolecode=$$role.'.'.$$where;
 7004:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7005:             $$tstatus='is';
 7006:             if ($$tstart && $$tstart>$update) {
 7007:                 $$tstatus='future';
 7008:                 if ($$tstart<$now) {
 7009:                     if ($$tstart && $$tstart>$refresh) {
 7010:                         if (($$where ne '') && ($$role ne '')) {
 7011:                             my (%allroles,%allgroups,$group_privs,
 7012:                                 %groups_roles,@rolecodes);
 7013:                             my %userroles = (
 7014:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7015:                             );
 7016:                             @rolecodes = ('cm'); 
 7017:                             my $spec=$$role.'.'.$$where;
 7018:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7019:                             if ($$role =~ /^cr\//) {
 7020:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7021:                                 push(@rolecodes,'cr');
 7022:                             } elsif ($$role eq 'gr') {
 7023:                                 push(@rolecodes,$$role);
 7024:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7025:                                                     $env{'user.name'});
 7026:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7027:                                 (undef,my $group_privs) = split(/\//,$trole);
 7028:                                 $group_privs = &unescape($group_privs);
 7029:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7030:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7031:                                 &get_groups_roles($tdomain,$trest,
 7032:                                                   \%course_roles,\@rolecodes,
 7033:                                                   \%groups_roles);
 7034:                             } else {
 7035:                                 push(@rolecodes,$$role);
 7036:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7037:                             }
 7038:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7039:                                                                    \%groups_roles);
 7040:                             &appenv(\%userroles,\@rolecodes);
 7041:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7042:                         }
 7043:                     }
 7044:                     $$tstatus = 'is';
 7045:                 }
 7046:             }
 7047:             if ($$tend) {
 7048:                 if ($$tend<$update) {
 7049:                     $$tstatus='expired';
 7050:                 } elsif ($$tend<$now) {
 7051:                     $$tstatus='will_not';
 7052:                 }
 7053:             }
 7054:         }
 7055:     }
 7056: }
 7057: 
 7058: sub get_groups_roles {
 7059:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7060:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7061:                   (ref($rolecodes) eq 'ARRAY') && 
 7062:                   (ref($groups_roles) eq 'HASH')); 
 7063:     if (keys(%{$cdom_courseroles}) > 0) {
 7064:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7065:         if ($cdom ne '' && $cnum ne '') {
 7066:             foreach my $key (keys(%{$cdom_courseroles})) {
 7067:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7068:                     my $crsrole = $1;
 7069:                     my $crssec = $2;
 7070:                     if ($crsrole =~ /^cr/) {
 7071:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7072:                             push(@{$rolecodes},'cr');
 7073:                         }
 7074:                     } else {
 7075:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7076:                             push(@{$rolecodes},$crsrole);
 7077:                         }
 7078:                     }
 7079:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7080:                     if ($crssec ne '') {
 7081:                         $rolekey .= "/$crssec";
 7082:                     }
 7083:                     $rolekey .= './';
 7084:                     $groups_roles->{$rolekey} = $rolecodes;
 7085:                 }
 7086:             }
 7087:         }
 7088:     }
 7089:     return;
 7090: }
 7091: 
 7092: sub delete_env_groupprivs {
 7093:     my ($where,$courseroles,$possroles) = @_;
 7094:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7095:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7096:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7097:         %{$courseroles->{$udom}} =
 7098:             &get_my_roles('','','userroles',['active'],
 7099:                           $possroles,[$udom],1);
 7100:     }
 7101:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7102:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7103:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7104:             my $area = '/'.$cdom.'/'.$cnum;
 7105:             my $privkey = "user.priv.$crsrole.$area";
 7106:             if ($crssec ne '') {
 7107:                 $privkey .= '/'.$crssec;
 7108:             }
 7109:             $privkey .= ".$area/$group";
 7110:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7111:         }
 7112:     }
 7113:     return;
 7114: }
 7115: 
 7116: sub check_adhoc_privs {
 7117:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7118:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7119:     if ($sec) {
 7120:         $cckey .= '/'.$sec;
 7121:     } 
 7122:     my $setprivs;
 7123:     if ($env{$cckey}) {
 7124:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7125:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7126:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7127:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7128:             $setprivs = 1;
 7129:         }
 7130:     } else {
 7131:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7132:         $setprivs = 1;
 7133:     }
 7134:     return $setprivs;
 7135: }
 7136: 
 7137: sub set_adhoc_privileges {
 7138: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7139:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7140:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7141:     if ($sec ne '') {
 7142:         $area .= '/'.$sec;
 7143:     }
 7144:     my $spec = $role.'.'.$area;
 7145:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7146:                                   $env{'user.name'},1);
 7147:     my %rolehash = ();
 7148:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7149:         my $rolename = $1;
 7150:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7151:         my %domdef = &get_domain_defaults($dcdom);
 7152:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7153:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7154:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7155:             }
 7156:         }
 7157:     } else {
 7158:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7159:     }
 7160:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7161:     &appenv(\%userroles,[$role,'cm']);
 7162:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7163:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7164:             ($caller eq 'tiny')) {
 7165:         &appenv( {'request.role'        => $spec,
 7166:                   'request.role.domain' => $dcdom,
 7167:                   'request.course.sec'  => $sec,
 7168:                  }
 7169:                );
 7170:         my $tadv=0;
 7171:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7172:         &appenv({'request.role.adv'    => $tadv});
 7173:     }
 7174: }
 7175: 
 7176: # --------------------------------------------------------------- get interface
 7177: 
 7178: sub get {
 7179:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7180:    my $items='';
 7181:    foreach my $item (@$storearr) {
 7182:        $items.=&escape($item).'&';
 7183:    }
 7184:    $items=~s/\&$//;
 7185:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7186:    if (!$uname) { $uname=$env{'user.name'}; }
 7187:    my $uhome=&homeserver($uname,$udomain);
 7188: 
 7189:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7190:    my @pairs=split(/\&/,$rep);
 7191:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7192:      return @pairs;
 7193:    }
 7194:    my %returnhash=();
 7195:    my $i=0;
 7196:    foreach my $item (@$storearr) {
 7197:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7198:       $i++;
 7199:    }
 7200:    return %returnhash;
 7201: }
 7202: 
 7203: # --------------------------------------------------------------- del interface
 7204: 
 7205: sub del {
 7206:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7207:    my $items='';
 7208:    foreach my $item (@$storearr) {
 7209:        $items.=&escape($item).'&';
 7210:    }
 7211: 
 7212:    $items=~s/\&$//;
 7213:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7214:    if (!$uname) { $uname=$env{'user.name'}; }
 7215:    my $uhome=&homeserver($uname,$udomain);
 7216:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7217: }
 7218: 
 7219: # -------------------------------------------------------------- dump interface
 7220: 
 7221: sub unserialize {
 7222:     my ($rep, $escapedkeys) = @_;
 7223: 
 7224:     return {} if $rep =~ /^error/;
 7225: 
 7226:     my %returnhash=();
 7227: 	foreach my $item (split(/\&/,$rep)) {
 7228: 	    my ($key, $value) = split(/=/, $item, 2);
 7229: 	    $key = unescape($key) unless $escapedkeys;
 7230: 	    next if $key =~ /^error: 2 /;
 7231: 	    $returnhash{$key} = &thaw_unescape($value);
 7232: 	}
 7233:     #return %returnhash;
 7234:     return \%returnhash;
 7235: }        
 7236: 
 7237: # see Lond::dump_with_regexp
 7238: # if $escapedkeys hash keys won't get unescaped.
 7239: sub dump {
 7240:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7241:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7242:     if (!$uname) { $uname=$env{'user.name'}; }
 7243:     my $uhome=&homeserver($uname,$udomain);
 7244: 
 7245:     if ($regexp) {
 7246:         $regexp=&escape($regexp);
 7247:     } else {
 7248:         $regexp='.';
 7249:     }
 7250:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7251:         # user is hosted on this machine
 7252:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7253:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7254:         return %{unserialize($reply, $escapedkeys)};
 7255:     }
 7256:     my $rep;
 7257:     if ($encrypt) {
 7258:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7259:     } else {
 7260:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7261:     }
 7262:     my @pairs=split(/\&/,$rep);
 7263:     my %returnhash=();
 7264:     if (!($rep =~ /^error/ )) {
 7265: 	foreach my $item (@pairs) {
 7266: 	    my ($key,$value)=split(/=/,$item,2);
 7267:         $key = unescape($key) unless $escapedkeys;
 7268:         #$key = &unescape($key);
 7269: 	    next if ($key =~ /^error: 2 /);
 7270: 	    $returnhash{$key}=&thaw_unescape($value);
 7271: 	}
 7272:     }
 7273:     return %returnhash;
 7274: }
 7275: 
 7276: 
 7277: # --------------------------------------------------------- dumpstore interface
 7278: 
 7279: sub dumpstore {
 7280:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7281:    # same as dump but keys must be escaped. They may contain colon separated
 7282:    # lists of values that may themself contain colons (e.g. symbs).
 7283:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7284: }
 7285: 
 7286: # -------------------------------------------------------------- keys interface
 7287: 
 7288: sub getkeys {
 7289:    my ($namespace,$udomain,$uname)=@_;
 7290:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7291:    if (!$uname) { $uname=$env{'user.name'}; }
 7292:    my $uhome=&homeserver($uname,$udomain);
 7293:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7294:    my @keyarray=();
 7295:    foreach my $key (split(/\&/,$rep)) {
 7296:       next if ($key =~ /^error: 2 /);
 7297:       push(@keyarray,&unescape($key));
 7298:    }
 7299:    return @keyarray;
 7300: }
 7301: 
 7302: # --------------------------------------------------------------- currentdump
 7303: sub currentdump {
 7304:    my ($courseid,$sdom,$sname)=@_;
 7305:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7306:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7307:    $sname    = $env{'user.name'}         if (! defined($sname));
 7308:    my $uhome = &homeserver($sname,$sdom);
 7309:    my $rep;
 7310: 
 7311:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7312:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7313:                    $courseid)));
 7314:    } else {
 7315:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7316:    }
 7317: 
 7318:    return if ($rep =~ /^(error:|no_such_host)/);
 7319:    #
 7320:    my %returnhash=();
 7321:    #
 7322:    if ($rep eq 'unknown_cmd') {
 7323:        # an old lond will not know currentdump
 7324:        # Do a dump and make it look like a currentdump
 7325:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7326:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7327:        my %hash = @tmp;
 7328:        @tmp=();
 7329:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7330:    } else {
 7331:        my @pairs=split(/\&/,$rep);
 7332:        foreach my $pair (@pairs) {
 7333:            my ($key,$value)=split(/=/,$pair,2);
 7334:            my ($symb,$param) = split(/:/,$key);
 7335:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7336:                                                         &thaw_unescape($value);
 7337:        }
 7338:    }
 7339:    return %returnhash;
 7340: }
 7341: 
 7342: sub convert_dump_to_currentdump{
 7343:     my %hash = %{shift()};
 7344:     my %returnhash;
 7345:     # Code ripped from lond, essentially.  The only difference
 7346:     # here is the unescaping done by lonnet::dump().  Conceivably
 7347:     # we might run in to problems with parameter names =~ /^v\./
 7348:     while (my ($key,$value) = each(%hash)) {
 7349:         my ($v,$symb,$param) = split(/:/,$key);
 7350: 	$symb  = &unescape($symb);
 7351: 	$param = &unescape($param);
 7352:         next if ($v eq 'version' || $symb eq 'keys');
 7353:         next if (exists($returnhash{$symb}) &&
 7354:                  exists($returnhash{$symb}->{$param}) &&
 7355:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7356:         $returnhash{$symb}->{$param}=$value;
 7357:         $returnhash{$symb}->{'v.'.$param}=$v;
 7358:     }
 7359:     #
 7360:     # Remove all of the keys in the hashes which keep track of
 7361:     # the version of the parameter.
 7362:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7363:         # use a foreach because we are going to delete from the hash.
 7364:         foreach my $key (keys(%$param_hash)) {
 7365:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7366:         }
 7367:     }
 7368:     return \%returnhash;
 7369: }
 7370: 
 7371: # ------------------------------------------------------ critical inc interface
 7372: 
 7373: sub cinc {
 7374:     return &inc(@_,'critical');
 7375: }
 7376: 
 7377: # --------------------------------------------------------------- inc interface
 7378: 
 7379: sub inc {
 7380:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7381:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7382:     if (!$uname) { $uname=$env{'user.name'}; }
 7383:     my $uhome=&homeserver($uname,$udomain);
 7384:     my $items='';
 7385:     if (! ref($store)) {
 7386:         # got a single value, so use that instead
 7387:         $items = &escape($store).'=&';
 7388:     } elsif (ref($store) eq 'SCALAR') {
 7389:         $items = &escape($$store).'=&';        
 7390:     } elsif (ref($store) eq 'ARRAY') {
 7391:         $items = join('=&',map {&escape($_);} @{$store});
 7392:     } elsif (ref($store) eq 'HASH') {
 7393:         while (my($key,$value) = each(%{$store})) {
 7394:             $items.= &escape($key).'='.&escape($value).'&';
 7395:         }
 7396:     }
 7397:     $items=~s/\&$//;
 7398:     if ($critical) {
 7399: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7400:     } else {
 7401: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7402:     }
 7403: }
 7404: 
 7405: # --------------------------------------------------------------- put interface
 7406: 
 7407: sub put {
 7408:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7409:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7410:    if (!$uname) { $uname=$env{'user.name'}; }
 7411:    my $uhome=&homeserver($uname,$udomain);
 7412:    my $items='';
 7413:    foreach my $item (keys(%$storehash)) {
 7414:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7415:    }
 7416:    $items=~s/\&$//;
 7417:    if ($encrypt) {
 7418:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7419:    } else {
 7420:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7421:    }
 7422: }
 7423: 
 7424: # ------------------------------------------------------------ newput interface
 7425: 
 7426: sub newput {
 7427:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7428:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7429:    if (!$uname) { $uname=$env{'user.name'}; }
 7430:    my $uhome=&homeserver($uname,$udomain);
 7431:    my $items='';
 7432:    foreach my $key (keys(%$storehash)) {
 7433:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7434:    }
 7435:    $items=~s/\&$//;
 7436:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7437: }
 7438: 
 7439: # ---------------------------------------------------------  putstore interface
 7440: 
 7441: sub putstore {
 7442:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7443:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7444:    if (!$uname) { $uname=$env{'user.name'}; }
 7445:    my $uhome=&homeserver($uname,$udomain);
 7446:    my $items='';
 7447:    foreach my $key (keys(%$storehash)) {
 7448:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7449:    }
 7450:    $items=~s/\&$//;
 7451:    my $esc_symb=&escape($symb);
 7452:    my $esc_v=&escape($version);
 7453:    my $reply =
 7454:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7455: 	      $uhome);
 7456:    if (($tolog) && ($reply eq 'ok')) {
 7457:        my $namevalue='';
 7458:        foreach my $key (keys(%{$storehash})) {
 7459:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7460:        }
 7461:        my $ip = &get_requestor_ip();
 7462:        $namevalue .= 'ip='.&escape($ip).
 7463:                      '&host='.&escape($perlvar{'lonHostID'}).
 7464:                      '&version='.$esc_v.
 7465:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7466:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7467:    }
 7468:    if ($reply eq 'unknown_cmd') {
 7469:        # gfall back to way things use to be done
 7470:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7471: 			    $uname);
 7472:    }
 7473:    return $reply;
 7474: }
 7475: 
 7476: sub old_putstore {
 7477:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7478:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7479:     if (!$uname) { $uname=$env{'user.name'}; }
 7480:     my $uhome=&homeserver($uname,$udomain);
 7481:     my %newstorehash;
 7482:     foreach my $item (keys(%$storehash)) {
 7483: 	my $key = $version.':'.&escape($symb).':'.$item;
 7484: 	$newstorehash{$key} = $storehash->{$item};
 7485:     }
 7486:     my $items='';
 7487:     my %allitems = ();
 7488:     foreach my $item (keys(%newstorehash)) {
 7489: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7490: 	    my $key = $1.':keys:'.$2;
 7491: 	    $allitems{$key} .= $3.':';
 7492: 	}
 7493: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7494:     }
 7495:     foreach my $item (keys(%allitems)) {
 7496: 	$allitems{$item} =~ s/\:$//;
 7497: 	$items.= $item.'='.$allitems{$item}.'&';
 7498:     }
 7499:     $items=~s/\&$//;
 7500:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7501: }
 7502: 
 7503: # ------------------------------------------------------ critical put interface
 7504: 
 7505: sub cput {
 7506:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7507:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7508:    if (!$uname) { $uname=$env{'user.name'}; }
 7509:    my $uhome=&homeserver($uname,$udomain);
 7510:    my $items='';
 7511:    foreach my $item (keys(%$storehash)) {
 7512:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7513:    }
 7514:    $items=~s/\&$//;
 7515:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7516: }
 7517: 
 7518: # -------------------------------------------------------------- eget interface
 7519: 
 7520: sub eget {
 7521:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7522:    my $items='';
 7523:    foreach my $item (@$storearr) {
 7524:        $items.=&escape($item).'&';
 7525:    }
 7526:    $items=~s/\&$//;
 7527:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7528:    if (!$uname) { $uname=$env{'user.name'}; }
 7529:    my $uhome=&homeserver($uname,$udomain);
 7530:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7531:    my @pairs=split(/\&/,$rep);
 7532:    my %returnhash=();
 7533:    my $i=0;
 7534:    foreach my $item (@$storearr) {
 7535:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7536:       $i++;
 7537:    }
 7538:    return %returnhash;
 7539: }
 7540: 
 7541: # ------------------------------------------------------------ tmpput interface
 7542: sub tmpput {
 7543:     my ($storehash,$server,$context)=@_;
 7544:     my $items='';
 7545:     foreach my $item (keys(%$storehash)) {
 7546: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7547:     }
 7548:     $items=~s/\&$//;
 7549:     if (defined($context)) {
 7550:         $items .= ':'.&escape($context);
 7551:     }
 7552:     return &reply("tmpput:$items",$server);
 7553: }
 7554: 
 7555: # ------------------------------------------------------------ tmpget interface
 7556: sub tmpget {
 7557:     my ($token,$server)=@_;
 7558:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7559:     my $rep=&reply("tmpget:$token",$server);
 7560:     my %returnhash;
 7561:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7562:         return %returnhash;
 7563:     }
 7564:     foreach my $item (split(/\&/,$rep)) {
 7565: 	my ($key,$value)=split(/=/,$item);
 7566: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7567:     }
 7568:     return %returnhash;
 7569: }
 7570: 
 7571: # ------------------------------------------------------------ tmpdel interface
 7572: sub tmpdel {
 7573:     my ($token,$server)=@_;
 7574:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7575:     return &reply("tmpdel:$token",$server);
 7576: }
 7577: 
 7578: # ------------------------------------------------------------ get_timebased_id 
 7579: 
 7580: sub get_timebased_id {
 7581:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7582:         $maxtries) = @_;
 7583:     my ($newid,$error,$dellock);
 7584:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7585:         return ('','ok','invalid call to get suffix');
 7586:     }
 7587: 
 7588: # set defaults for any optional args for which values were not supplied
 7589:     if ($who eq '') {
 7590:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7591:     }
 7592:     if (!$locktries) {
 7593:         $locktries = 3;
 7594:     }
 7595:     if (!$maxtries) {
 7596:         $maxtries = 10;
 7597:     }
 7598:     
 7599:     if (($cdom eq '') || ($cnum eq '')) {
 7600:         if ($env{'request.course.id'}) {
 7601:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7602:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7603:         }
 7604:         if (($cdom eq '') || ($cnum eq '')) {
 7605:             return ('','ok','call to get suffix not in course context');
 7606:         }
 7607:     }
 7608: 
 7609: # construct locking item
 7610:     my $lockhash = {
 7611:                       $prefix."\0".'locked_'.$keyid => $who,
 7612:                    };
 7613:     my $tries = 0;
 7614: 
 7615: # attempt to get lock on nohist_$namespace file
 7616:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7617:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7618:         $tries ++;
 7619:         sleep 1;
 7620:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7621:     }
 7622: 
 7623: # attempt to get unique identifier, based on current timestamp
 7624:     if ($gotlock eq 'ok') {
 7625:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7626:         my $id = time;
 7627:         $newid = $id;
 7628:         if ($idtype eq 'addcode') {
 7629:             $newid .= &sixnum_code();
 7630:         }
 7631:         my $idtries = 0;
 7632:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7633:             if ($idtype eq 'concat') {
 7634:                 $newid = $id.$idtries;
 7635:             } elsif ($idtype eq 'addcode') {
 7636:                 $newid = $newid.&sixnum_code();
 7637:             } else {
 7638:                 $newid ++;
 7639:             }
 7640:             $idtries ++;
 7641:         }
 7642:         if (!exists($inuse{$prefix."\0".$newid})) {
 7643:             my %new_item =  (
 7644:                               $prefix."\0".$newid => $who,
 7645:                             );
 7646:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7647:                                                  $cdom,$cnum);
 7648:             if ($putresult ne 'ok') {
 7649:                 undef($newid);
 7650:                 $error = 'error saving new item: '.$putresult;
 7651:             }
 7652:         } else {
 7653:              undef($newid);
 7654:              $error = ('error: no unique suffix available for the new item ');
 7655:         }
 7656: #  remove lock
 7657:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7658:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7659:     } else {
 7660:         $error = "error: could not obtain lockfile\n";
 7661:         $dellock = 'ok';
 7662:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7663:             $dellock = 'nolock';
 7664:         }
 7665:     }
 7666:     return ($newid,$dellock,$error);
 7667: }
 7668: 
 7669: sub sixnum_code {
 7670:     my $code;
 7671:     for (0..6) {
 7672:         $code .= int( rand(9) );
 7673:     }
 7674:     return $code;
 7675: }
 7676: 
 7677: # -------------------------------------------------- portfolio access checking
 7678: 
 7679: sub portfolio_access {
 7680:     my ($requrl,$clientip) = @_;
 7681:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7682:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7683:     if ($result) {
 7684:         my %setters;
 7685:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7686:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7687:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7688:             if (($startblock && $endblock) || ($by_ip)) {
 7689:                 return 'B';
 7690:             }
 7691:         } else {
 7692:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7693:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7694:             if (($startblock && $endblock) || ($by_ip)) {
 7695:                 return 'B';
 7696:             }
 7697:         }
 7698:     }
 7699:     if ($result eq 'ok') {
 7700:        return 'F';
 7701:     } elsif ($result =~ /^[^:]+:guest_/) {
 7702:        return 'A';
 7703:     }
 7704:     return '';
 7705: }
 7706: 
 7707: sub get_portfolio_access {
 7708:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7709: 
 7710:     if (!ref($access_hash)) {
 7711: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7712: 	my %access_controls = &get_access_controls($current_perms,$group,
 7713: 						   $file_name);
 7714: 	$access_hash = $access_controls{$file_name};
 7715:     }
 7716: 
 7717:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7718:     my $now = time;
 7719:     if (ref($access_hash) eq 'HASH') {
 7720:         foreach my $key (keys(%{$access_hash})) {
 7721:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7722:             if ($start > $now) {
 7723:                 next;
 7724:             }
 7725:             if ($end && $end<$now) {
 7726:                 next;
 7727:             }
 7728:             if ($scope eq 'public') {
 7729:                 $public = $key;
 7730:                 last;
 7731:             } elsif ($scope eq 'guest') {
 7732:                 $guest = $key;
 7733:             } elsif ($scope eq 'domains') {
 7734:                 push(@domains,$key);
 7735:             } elsif ($scope eq 'users') {
 7736:                 push(@users,$key);
 7737:             } elsif ($scope eq 'course') {
 7738:                 push(@courses,$key);
 7739:             } elsif ($scope eq 'group') {
 7740:                 push(@groups,$key);
 7741:             } elsif ($scope eq 'ip') {
 7742:                 push(@ips,$key);
 7743:             }
 7744:         }
 7745:         if ($public) {
 7746:             return 'ok';
 7747:         } elsif (@ips > 0) {
 7748:             my $allowed;
 7749:             foreach my $ipkey (@ips) {
 7750:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7751:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7752:                         $allowed = 1;
 7753:                         last; 
 7754:                     }
 7755:                 }
 7756:             }
 7757:             if ($allowed) {
 7758:                 return 'ok';
 7759:             }
 7760:         }
 7761:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7762:             if ($guest) {
 7763:                 return $guest;
 7764:             }
 7765:         } else {
 7766:             if (@domains > 0) {
 7767:                 foreach my $domkey (@domains) {
 7768:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7769:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7770:                             return 'ok';
 7771:                         }
 7772:                     }
 7773:                 }
 7774:             }
 7775:             if (@users > 0) {
 7776:                 foreach my $userkey (@users) {
 7777:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7778:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7779:                             if (ref($item) eq 'HASH') {
 7780:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7781:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7782:                                     return 'ok';
 7783:                                 }
 7784:                             }
 7785:                         }
 7786:                     } 
 7787:                 }
 7788:             }
 7789:             my %roleshash;
 7790:             my @courses_and_groups = @courses;
 7791:             push(@courses_and_groups,@groups); 
 7792:             if (@courses_and_groups > 0) {
 7793:                 my (%allgroups,%allroles); 
 7794:                 my ($start,$end,$role,$sec,$group);
 7795:                 foreach my $envkey (%env) {
 7796:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7797:                         my $cid = $2.'_'.$3; 
 7798:                         if ($1 eq 'gr') {
 7799:                             $group = $4;
 7800:                             $allgroups{$cid}{$group} = $env{$envkey};
 7801:                         } else {
 7802:                             if ($4 eq '') {
 7803:                                 $sec = 'none';
 7804:                             } else {
 7805:                                 $sec = $4;
 7806:                             }
 7807:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7808:                         }
 7809:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7810:                         my $cid = $2.'_'.$3;
 7811:                         if ($4 eq '') {
 7812:                             $sec = 'none';
 7813:                         } else {
 7814:                             $sec = $4;
 7815:                         }
 7816:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7817:                     }
 7818:                 }
 7819:                 if (keys(%allroles) == 0) {
 7820:                     return;
 7821:                 }
 7822:                 foreach my $key (@courses_and_groups) {
 7823:                     my %content = %{$$access_hash{$key}};
 7824:                     my $cnum = $content{'number'};
 7825:                     my $cdom = $content{'domain'};
 7826:                     my $cid = $cdom.'_'.$cnum;
 7827:                     if (!exists($allroles{$cid})) {
 7828:                         next;
 7829:                     }    
 7830:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7831:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7832:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7833:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7834:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7835:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7836:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7837:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7838:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7839:                                         if (grep/^all$/,@sections) {
 7840:                                             return 'ok';
 7841:                                         } else {
 7842:                                             if (grep/^$sec$/,@sections) {
 7843:                                                 return 'ok';
 7844:                                             }
 7845:                                         }
 7846:                                     }
 7847:                                 }
 7848:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7849:                                     if (grep/^none$/,@groups) {
 7850:                                         return 'ok';
 7851:                                     }
 7852:                                 } else {
 7853:                                     if (grep/^all$/,@groups) {
 7854:                                         return 'ok';
 7855:                                     } 
 7856:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7857:                                         if (grep/^$group$/,@groups) {
 7858:                                             return 'ok';
 7859:                                         }
 7860:                                     }
 7861:                                 } 
 7862:                             }
 7863:                         }
 7864:                     }
 7865:                 }
 7866:             }
 7867:             if ($guest) {
 7868:                 return $guest;
 7869:             }
 7870:         }
 7871:     }
 7872:     return;
 7873: }
 7874: 
 7875: sub course_group_datechecker {
 7876:     my ($dates,$now,$status) = @_;
 7877:     my ($start,$end) = split(/\./,$dates);
 7878:     if (!$start && !$end) {
 7879:         return 'ok';
 7880:     }
 7881:     if (grep/^active$/,@{$status}) {
 7882:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7883:             return 'ok';
 7884:         }
 7885:     }
 7886:     if (grep/^previous$/,@{$status}) {
 7887:         if ($end > $now ) {
 7888:             return 'ok';
 7889:         }
 7890:     }
 7891:     if (grep/^future$/,@{$status}) {
 7892:         if ($start > $now) {
 7893:             return 'ok';
 7894:         }
 7895:     }
 7896:     return; 
 7897: }
 7898: 
 7899: sub parse_portfolio_url {
 7900:     my ($url) = @_;
 7901: 
 7902:     my ($type,$udom,$unum,$group,$file_name);
 7903:     
 7904:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7905: 	$type = 1;
 7906:         $udom = $1;
 7907:         $unum = $2;
 7908:         $file_name = $3;
 7909:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7910: 	$type = 2;
 7911:         $udom = $1;
 7912:         $unum = $2;
 7913:         $group = $3;
 7914:         $file_name = $3.'/'.$4;
 7915:     }
 7916:     if (wantarray) {
 7917: 	return ($type,$udom,$unum,$file_name,$group);
 7918:     }
 7919:     return $type;
 7920: }
 7921: 
 7922: sub is_portfolio_url {
 7923:     my ($url) = @_;
 7924:     return scalar(&parse_portfolio_url($url));
 7925: }
 7926: 
 7927: sub is_portfolio_file {
 7928:     my ($file) = @_;
 7929:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7930:         return 1;
 7931:     }
 7932:     return;
 7933: }
 7934: 
 7935: sub usertools_access {
 7936:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7937:     my ($access,%tools);
 7938:     if ($context eq '') {
 7939:         $context = 'tools';
 7940:     }
 7941:     if ($context eq 'requestcourses') {
 7942:         %tools = (
 7943:                       official   => 1,
 7944:                       unofficial => 1,
 7945:                       community  => 1,
 7946:                       textbook   => 1,
 7947:                       placement  => 1,
 7948:                       lti        => 1,
 7949:                  );
 7950:     } elsif ($context eq 'requestauthor') {
 7951:         %tools = (
 7952:                       requestauthor => 1,
 7953:                  );
 7954:     } else {
 7955:         %tools = (
 7956:                       aboutme   => 1,
 7957:                       blog      => 1,
 7958:                       webdav    => 1,
 7959:                       portfolio => 1,
 7960:                       timezone  => 1,
 7961:                  );
 7962:     }
 7963:     return if (!defined($tools{$tool}));
 7964: 
 7965:     if (($udom eq '') || ($uname eq '')) {
 7966:         $udom = $env{'user.domain'};
 7967:         $uname = $env{'user.name'};
 7968:     }
 7969: 
 7970:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7971:         if ($action ne 'reload') {
 7972:             if ($context eq 'requestcourses') {
 7973:                 return $env{'environment.canrequest.'.$tool};
 7974:             } elsif ($context eq 'requestauthor') {
 7975:                 return $env{'environment.canrequest.author'};
 7976:             } else {
 7977:                 return $env{'environment.availabletools.'.$tool};
 7978:             }
 7979:         }
 7980:     }
 7981: 
 7982:     my ($toolstatus,$inststatus,$envkey);
 7983:     if ($context eq 'requestauthor') {
 7984:         $envkey = $context; 
 7985:     } else {
 7986:         $envkey = $context.'.'.$tool;
 7987:     }
 7988: 
 7989:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7990:          ($action ne 'reload')) {
 7991:         $toolstatus = $env{'environment.'.$envkey};
 7992:         $inststatus = $env{'environment.inststatus'};
 7993:     } else {
 7994:         if (ref($userenvref) eq 'HASH') {
 7995:             $toolstatus = $userenvref->{$envkey};
 7996:             $inststatus = $userenvref->{'inststatus'};
 7997:         } else {
 7998:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7999:             $toolstatus = $userenv{$envkey};
 8000:             $inststatus = $userenv{'inststatus'};
 8001:         }
 8002:     }
 8003: 
 8004:     if ($toolstatus ne '') {
 8005:         if ($toolstatus) {
 8006:             $access = 1;
 8007:         } else {
 8008:             $access = 0;
 8009:         }
 8010:         return $access;
 8011:     }
 8012: 
 8013:     my ($is_adv,%domdef);
 8014:     if (ref($is_advref) eq 'HASH') {
 8015:         $is_adv = $is_advref->{'is_adv'};
 8016:     } else {
 8017:         $is_adv = &is_advanced_user($udom,$uname);
 8018:     }
 8019:     if (ref($domdefref) eq 'HASH') {
 8020:         %domdef = %{$domdefref};
 8021:     } else {
 8022:         %domdef = &get_domain_defaults($udom);
 8023:     }
 8024:     if (ref($domdef{$tool}) eq 'HASH') {
 8025:         if ($is_adv) {
 8026:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8027:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8028:                     $access = 1;
 8029:                 } else {
 8030:                     $access = 0;
 8031:                 }
 8032:                 return $access;
 8033:             }
 8034:         }
 8035:         if ($inststatus ne '') {
 8036:             my ($hasaccess,$hasnoaccess);
 8037:             foreach my $affiliation (split(/:/,$inststatus)) {
 8038:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8039:                     if ($domdef{$tool}{$affiliation}) {
 8040:                         $hasaccess = 1;
 8041:                     } else {
 8042:                         $hasnoaccess = 1;
 8043:                     }
 8044:                 }
 8045:             }
 8046:             if ($hasaccess || $hasnoaccess) {
 8047:                 if ($hasaccess) {
 8048:                     $access = 1;
 8049:                 } elsif ($hasnoaccess) {
 8050:                     $access = 0; 
 8051:                 }
 8052:                 return $access;
 8053:             }
 8054:         } else {
 8055:             if ($domdef{$tool}{'default'} ne '') {
 8056:                 if ($domdef{$tool}{'default'}) {
 8057:                     $access = 1;
 8058:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8059:                     $access = 0;
 8060:                 }
 8061:                 return $access;
 8062:             }
 8063:         }
 8064:     } else {
 8065:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8066:             $access = 1;
 8067:         } else {
 8068:             $access = 0;
 8069:         }
 8070:         return $access;
 8071:     }
 8072: }
 8073: 
 8074: sub is_course_owner {
 8075:     my ($cdom,$cnum,$udom,$uname) = @_;
 8076:     if (($udom eq '') || ($uname eq '')) {
 8077:         $udom = $env{'user.domain'};
 8078:         $uname = $env{'user.name'};
 8079:     }
 8080:     unless (($udom eq '') || ($uname eq '')) {
 8081:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8082:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8083:                 return 1;
 8084:             } else {
 8085:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 8086:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8087:                     return 1;
 8088:                 }
 8089:             }
 8090:         }
 8091:     }
 8092:     return;
 8093: }
 8094: 
 8095: sub is_advanced_user {
 8096:     my ($udom,$uname) = @_;
 8097:     if ($udom ne '' && $uname ne '') {
 8098:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8099:             if (wantarray) {
 8100:                 return ($env{'user.adv'},$env{'user.author'});
 8101:             } else {
 8102:                 return $env{'user.adv'};
 8103:             }
 8104:         }
 8105:     }
 8106:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8107:     my %allroles;
 8108:     my ($is_adv,$is_author);
 8109:     foreach my $role (keys(%roleshash)) {
 8110:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8111:         my $area = '/'.$tdomain.'/'.$trest;
 8112:         if ($sec ne '') {
 8113:             $area .= '/'.$sec;
 8114:         }
 8115:         if (($area ne '') && ($trole ne '')) {
 8116:             my $spec=$trole.'.'.$area;
 8117:             if ($trole =~ /^cr\//) {
 8118:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8119:             } elsif ($trole ne 'gr') {
 8120:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8121:             }
 8122:             if ($trole eq 'au') {
 8123:                 $is_author = 1;
 8124:             }
 8125:         }
 8126:     }
 8127:     foreach my $role (keys(%allroles)) {
 8128:         last if ($is_adv);
 8129:         foreach my $item (split(/:/,$allroles{$role})) {
 8130:             if ($item ne '') {
 8131:                 my ($privilege,$restrictions)=split(/&/,$item);
 8132:                 if ($privilege eq 'adv') {
 8133:                     $is_adv = 1;
 8134:                     last;
 8135:                 }
 8136:             }
 8137:         }
 8138:     }
 8139:     if (wantarray) {
 8140:         return ($is_adv,$is_author);
 8141:     }
 8142:     return $is_adv;
 8143: }
 8144: 
 8145: sub check_can_request {
 8146:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8147:     my $canreq = 0;
 8148:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8149:         $uname = $env{'user.name'};
 8150:         $udom = $env{'user.domain'};
 8151:     }
 8152:     my ($types,$typename) = &Apache::loncommon::course_types();
 8153:     my @options = ('approval','validate','autolimit');
 8154:     my $optregex = join('|',@options);
 8155:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8156:         my %willtrust;
 8157:         foreach my $type (@{$types}) {
 8158:             if (&usertools_access($uname,$udom,$type,undef,
 8159:                                   'requestcourses')) {
 8160:                 $canreq ++;
 8161:                 if (ref($request_domains) eq 'HASH') {
 8162:                     push(@{$request_domains->{$type}},$udom);
 8163:                 }
 8164:                 if ($dom eq $udom) {
 8165:                     $can_request->{$type} = 1;
 8166:                 }
 8167:             }
 8168:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8169:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8170:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8171:                 if (@curr > 0) {
 8172:                     foreach my $item (@curr) {
 8173:                         if (ref($request_domains) eq 'HASH') {
 8174:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8175:                             if ($otherdom ne '') {
 8176:                                 unless (exists($willtrust{$otherdom})) {
 8177:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8178:                                 }
 8179:                                 if ($willtrust{$otherdom}) {
 8180:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8181:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8182:                                             push(@{$request_domains->{$type}},$otherdom);
 8183:                                         }
 8184:                                     } else {
 8185:                                         push(@{$request_domains->{$type}},$otherdom);
 8186:                                     }
 8187:                                 }
 8188:                             }
 8189:                         }
 8190:                     }
 8191:                     unless ($dom eq $env{'user.domain'}) {
 8192:                         $canreq ++;
 8193:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8194:                             $can_request->{$type} = 1;
 8195:                         }
 8196:                     }
 8197:                 }
 8198:             }
 8199:         }
 8200:     }
 8201:     return $canreq;
 8202: }
 8203: 
 8204: # ---------------------------------------------- Custom access rule evaluation
 8205: 
 8206: sub customaccess {
 8207:     my ($priv,$uri)=@_;
 8208:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8209:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8210:     $udom = &LONCAPA::clean_domain($udom);
 8211:     $ucrs = &LONCAPA::clean_username($ucrs);
 8212:     my $access=0;
 8213:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8214: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8215: 	if ($type eq 'user') {
 8216: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8217: 		my ($tdom,$tuname)=split(m{/},$scope);
 8218: 		if ($tdom) {
 8219: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8220: 		}
 8221: 		if ($tuname) {
 8222: 		    if ($tuname ne $env{'user.name'}) { next; }
 8223: 		}
 8224: 		$access=($effect eq 'allow');
 8225: 		last;
 8226: 	    }
 8227: 	} else {
 8228: 	    if ($role) {
 8229: 		if ($role ne $urole) { next; }
 8230: 	    }
 8231: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8232: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8233: 		if ($tdom) {
 8234: 		    if ($tdom ne $udom) { next; }
 8235: 		}
 8236: 		if ($tcrs) {
 8237: 		    if ($tcrs ne $ucrs) { next; }
 8238: 		}
 8239: 		if ($tsec) {
 8240: 		    if ($tsec ne $usec) { next; }
 8241: 		}
 8242: 		$access=($effect eq 'allow');
 8243: 		last;
 8244: 	    }
 8245: 	    if ($realm eq '' && $role eq '') {
 8246: 		$access=($effect eq 'allow');
 8247: 	    }
 8248: 	}
 8249:     }
 8250:     return $access;
 8251: }
 8252: 
 8253: # ------------------------------------------------- Check for a user privilege
 8254: 
 8255: sub allowed {
 8256:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8257:     my $ver_orguri=$uri;
 8258:     $uri=&deversion($uri);
 8259:     my $orguri=$uri;
 8260:     $uri=&declutter($uri);
 8261: 
 8262:     if ($priv eq 'evb') {
 8263: # Evade communication block restrictions for specified role in a course or domain
 8264:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8265:             return $1;
 8266:         } else {
 8267:             return;
 8268:         }
 8269:     }
 8270: 
 8271:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8272: # Free bre access to adm and meta resources
 8273:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8274: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8275: 	&& ($priv eq 'bre')) {
 8276: 	return 'F';
 8277:     }
 8278: 
 8279: # Free bre access to user's own portfolio contents
 8280:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8281:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8282: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8283:         my %setters;
 8284:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8285:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8286:         if (($startblock && $endblock) || ($by_ip)) {
 8287:             return 'B';
 8288:         } else {
 8289:             return 'F';
 8290:         }
 8291:     }
 8292: 
 8293: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8294:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8295:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8296:         if (exists($env{'request.course.id'})) {
 8297:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8298:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8299:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8300:                 my $courseprivid=$env{'request.course.id'};
 8301:                 $courseprivid=~s/\_/\//;
 8302:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8303:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8304:                     return $1; 
 8305:                 } else {
 8306:                     if ($env{'request.course.sec'}) {
 8307:                         $courseprivid.='/'.$env{'request.course.sec'};
 8308:                     }
 8309:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8310:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8311:                         return $2;
 8312:                     }
 8313:                 }
 8314:             }
 8315:         }
 8316:     }
 8317: 
 8318: # Free bre to public access
 8319: 
 8320:     if ($priv eq 'bre') {
 8321:         my $copyright;
 8322:         unless ($uri =~ /ext\.tool/) {
 8323:             $copyright=&metadata($uri,'copyright');
 8324:         }
 8325: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8326:            return 'F'; 
 8327:         }
 8328:         if ($copyright eq 'priv') {
 8329:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8330: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8331: 		return '';
 8332:             }
 8333:         }
 8334:         if ($copyright eq 'domain') {
 8335:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8336: 	    unless (($env{'user.domain'} eq $1) ||
 8337:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8338: 		return '';
 8339:             }
 8340:         }
 8341:         if ($env{'request.role'}=~ /li\.\//) {
 8342:             # Library role, so allow browsing of resources in this domain.
 8343:             return 'F';
 8344:         }
 8345:         if ($copyright eq 'custom') {
 8346: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8347:         }
 8348:     }
 8349:     # Domain coordinator is trying to create a course
 8350:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8351:         # uri is the requested domain in this case.
 8352:         # comparison to 'request.role.domain' shows if the user has selected
 8353:         # a role of dc for the domain in question.
 8354:         return 'F' if ($uri eq $env{'request.role.domain'});
 8355:     }
 8356: 
 8357:     my $thisallowed='';
 8358:     my $statecond=0;
 8359:     my $courseprivid='';
 8360: 
 8361:     my $ownaccess;
 8362:     # Community Coordinator or Assistant Co-author browsing resource space.
 8363:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8364:         if ($uri eq '') {
 8365:             $ownaccess = 1;
 8366:         } else {
 8367:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8368:                 my $udom = $env{'user.domain'};
 8369:                 my $uname = $env{'user.name'};
 8370:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8371:                     $ownaccess = 1;
 8372:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8373:                     unless ($uri =~ m{\.\./}) {
 8374:                         $ownaccess = 1;
 8375:                     }
 8376:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8377:                     my $now = time;
 8378:                     if ($uri =~ m{^([^/]+)/?$}) {
 8379:                         my $adom = $1;
 8380:                         foreach my $key (keys(%env)) {
 8381:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8382:                                 my ($start,$end) = split(/\./,$env{$key});
 8383:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8384:                                     $ownaccess = 1;
 8385:                                     last;
 8386:                                 }
 8387:                             }
 8388:                         }
 8389:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8390:                         my $adom = $1;
 8391:                         my $aname = $2;
 8392:                         foreach my $role ('ca','aa') { 
 8393:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8394:                                 my ($start,$end) =
 8395:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8396:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8397:                                     $ownaccess = 1;
 8398:                                     last;
 8399:                                 }
 8400:                             }
 8401:                         }
 8402:                     }
 8403:                 }
 8404:             }
 8405:         }
 8406:     }
 8407: 
 8408: # Course
 8409: 
 8410:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8411:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8412:             $thisallowed.=$1;
 8413:         }
 8414:     }
 8415: 
 8416: # Domain
 8417: 
 8418:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8419:        =~/\Q$priv\E\&([^\:]*)/) {
 8420:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8421:             $thisallowed.=$1;
 8422:         }
 8423:     }
 8424: 
 8425: # User who is not author or co-author might still be able to edit
 8426: # resource of an author in the domain (e.g., if Domain Coordinator).
 8427:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8428:         (&allowed('mdc',$env{'request.course.id'}))) {
 8429:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8430:             $thisallowed.=$1;
 8431:         }
 8432:     }
 8433: 
 8434: # Course: uri itself is a course
 8435:     my $courseuri=$uri;
 8436:     $courseuri=~s/\_(\d)/\/$1/;
 8437:     $courseuri=~s/^([^\/])/\/$1/;
 8438: 
 8439:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8440:        =~/\Q$priv\E\&([^\:]*)/) {
 8441:         if ($priv eq 'mip') {
 8442:             my $rem = $1;
 8443:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8444:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8445:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8446:                 if ($cdom ne '') {
 8447:                     my %passwdconf = &get_passwdconf($cdom);
 8448:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8449:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8450:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8451:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8452:                                 unless (@inststatuses) {
 8453:                                     @inststatuses = ('default');
 8454:                                 }
 8455:                                 foreach my $status (@inststatuses) {
 8456:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8457:                                         $thisallowed.=$rem;
 8458:                                     }
 8459:                                 }
 8460:                             }
 8461:                         }
 8462:                     }
 8463:                 }
 8464:             }
 8465:         } else {
 8466:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8467:                 $thisallowed.=$1;
 8468:             }
 8469:         }
 8470:     }
 8471: 
 8472: # URI is an uploaded document for this course, default permissions don't matter
 8473: # not allowing 'edit' access (editupload) to uploaded course docs
 8474:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8475: 	$thisallowed='';
 8476:         my ($match)=&is_on_map($uri);
 8477:         if ($match) {
 8478:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8479:                   =~/\Q$priv\E\&([^\:]*)/) {
 8480:                 my $value = $1;
 8481:                 my $deeplinkblock;
 8482:                 unless ($nodeeplinkcheck) {
 8483:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8484:                 }
 8485:                 if ($deeplinkblock) {
 8486:                     $thisallowed='D';
 8487:                 } elsif ($noblockcheck) {
 8488:                     $thisallowed.=$value;
 8489:                 } else {
 8490:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8491:                     if (@blockers > 0) {
 8492:                         $thisallowed = 'B';
 8493:                     } else {
 8494:                         $thisallowed.=$value;
 8495:                     }
 8496:                 }
 8497:             }
 8498:         } else {
 8499:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8500:             if ($refuri) {
 8501:                 if ($refuri =~ m|^/adm/|) {
 8502:                     $thisallowed='F';
 8503:                 } else {
 8504:                     $refuri=&declutter($refuri);
 8505:                     my ($match) = &is_on_map($refuri);
 8506:                     if ($match) {
 8507:                         my $deeplinkblock;
 8508:                         unless ($nodeeplinkcheck) {
 8509:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8510:                         }
 8511:                         if ($deeplinkblock) {
 8512:                             $thisallowed='D';
 8513:                         } elsif ($noblockcheck) {
 8514:                             $thisallowed='F';
 8515:                         } else {
 8516:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8517:                             if (@blockers > 0) {
 8518:                                 $thisallowed = 'B';
 8519:                             } else {
 8520:                                 $thisallowed='F';
 8521:                             }
 8522:                         }
 8523:                     }
 8524:                 }
 8525:             }
 8526:         }
 8527:     }
 8528: 
 8529:     if ($priv eq 'bre'
 8530: 	&& $thisallowed ne 'F' 
 8531: 	&& $thisallowed ne '2'
 8532: 	&& &is_portfolio_url($uri)) {
 8533: 	$thisallowed = &portfolio_access($uri,$clientip);
 8534:     }
 8535: 
 8536: # Full access at system, domain or course-wide level? Exit.
 8537:     if ($thisallowed=~/F/) {
 8538: 	return 'F';
 8539:     }
 8540: 
 8541: # If this is generating or modifying users, exit with special codes
 8542: 
 8543:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8544: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8545: 	    my ($audom,$auname)=split('/',$uri);
 8546: # no author name given, so this just checks on the general right to make a co-author in this domain
 8547: 	    unless ($auname) { return $thisallowed; }
 8548: # an author name is given, so we are about to actually make a co-author for a certain account
 8549: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8550: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8551: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8552: 	}
 8553: 	return $thisallowed;
 8554:     }
 8555: #
 8556: # Gathered so far: system, domain and course wide privileges
 8557: #
 8558: # Course: See if uri or referer is an individual resource that is part of 
 8559: # the course
 8560: 
 8561:     if ($env{'request.course.id'}) {
 8562: 
 8563: # If this is modifying password (internal auth) domains must match for user and user's role.
 8564: 
 8565:         if ($priv eq 'mip') {
 8566:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8567:                 return $thisallowed;
 8568:             } else {
 8569:                 return '';
 8570:             }
 8571:         }
 8572: 
 8573:        $courseprivid=$env{'request.course.id'};
 8574:        if ($env{'request.course.sec'}) {
 8575:           $courseprivid.='/'.$env{'request.course.sec'};
 8576:        }
 8577:        $courseprivid=~s/\_/\//;
 8578:        my $checkreferer=1;
 8579:        my ($match,$cond)=&is_on_map($uri);
 8580:        if ($match) {
 8581:            $statecond=$cond;
 8582:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8583:                =~/\Q$priv\E\&([^\:]*)/) {
 8584:                my $value = $1;
 8585:                if ($priv eq 'bre') {
 8586:                    my $deeplinkblock;
 8587:                    unless ($nodeeplinkcheck) {
 8588:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8589:                    }
 8590:                    if ($deeplinkblock) {
 8591:                        $thisallowed = 'D';
 8592:                    } elsif ($noblockcheck) {
 8593:                        $thisallowed.=$value;
 8594:                    } else {
 8595:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8596:                        if (@blockers > 0) {
 8597:                            $thisallowed = 'B';
 8598:                        } else {
 8599:                            $thisallowed.=$value;
 8600:                        }
 8601:                    }
 8602:                } else {
 8603:                    $thisallowed.=$value;
 8604:                }
 8605:                $checkreferer=0;
 8606:            }
 8607:        }
 8608: 
 8609:        if ($checkreferer) {
 8610: 	  my $refuri=$env{'httpref.'.$orguri};
 8611:             unless ($refuri) {
 8612:                 foreach my $key (keys(%env)) {
 8613: 		    if ($key=~/^httpref\..*\*/) {
 8614: 			my $pattern=$key;
 8615:                         $pattern=~s/^httpref\.\/res\///;
 8616:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8617:                         $pattern=~s/\//\\\//g;
 8618:                         if ($orguri=~/$pattern/) {
 8619: 			    $refuri=$env{$key};
 8620:                         }
 8621:                     }
 8622:                 }
 8623:             }
 8624: 
 8625:          if ($refuri) { 
 8626: 	  $refuri=&declutter($refuri);
 8627:           my ($match,$cond)=&is_on_map($refuri);
 8628:             if ($match) {
 8629:               my $refstatecond=$cond;
 8630:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8631:                   =~/\Q$priv\E\&([^\:]*)/) {
 8632:                   my $value = $1;
 8633:                   if ($priv eq 'bre') {
 8634:                       my $deeplinkblock;
 8635:                       unless ($nodeeplinkcheck) {
 8636:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8637:                       }
 8638:                       if ($deeplinkblock) {
 8639:                           $thisallowed = 'D';
 8640:                       } elsif ($noblockcheck) {
 8641:                           $thisallowed.=$value;
 8642:                       } else {
 8643:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8644:                           if (@blockers > 0) {
 8645:                               $thisallowed = 'B';
 8646:                           } else {
 8647:                               $thisallowed.=$value;
 8648:                           }
 8649:                       }
 8650:                   } else {
 8651:                       $thisallowed.=$value;
 8652:                   }
 8653:                   $uri=$refuri;
 8654:                   $statecond=$refstatecond;
 8655:               }
 8656:           }
 8657:         }
 8658:        }
 8659:    }
 8660: 
 8661: #
 8662: # Gathered now: all privileges that could apply, and condition number
 8663: # 
 8664: #
 8665: # Full or no access?
 8666: #
 8667: 
 8668:     if ($thisallowed=~/F/) {
 8669: 	return 'F';
 8670:     }
 8671: 
 8672:     unless ($thisallowed) {
 8673:         return '';
 8674:     }
 8675: 
 8676: # Restrictions exist, deal with them
 8677: #
 8678: #   C:according to course preferences
 8679: #   R:according to resource settings
 8680: #   L:unless locked
 8681: #   X:according to user session state
 8682: #
 8683: 
 8684: # Possibly locked functionality, check all courses
 8685: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8686: # Locks might take effect only after 10 minutes cache expiration for other
 8687: # courses, and 2 minutes for current course, in which user has st or ta role
 8688: # which is neither expired nor a future role (unless current course).
 8689: 
 8690:     my ($needlockcheck,$now,$crsonly);
 8691:     if ($thisallowed=~/L/) {
 8692:         $now = time;
 8693:         if ($priv eq 'bre') {
 8694:             if ($uri ne '') {
 8695:                 if ($orguri =~ m{^/+res/}) {
 8696:                     if ($uri =~ m{^lib/templates/}) {
 8697:                         if ($env{'request.course.id'}) {
 8698:                             $crsonly = 1;
 8699:                             $needlockcheck = 1;
 8700:                         }
 8701:                     } else {
 8702:                         $needlockcheck = 1;
 8703:                     }
 8704:                 } elsif ($env{'request.course.id'}) {
 8705:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8706:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8707:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8708:                         $crsonly = 1;
 8709:                     }
 8710:                     $needlockcheck = 1;
 8711:                 }
 8712:             }
 8713:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8714:             $needlockcheck = 1;
 8715:         }
 8716:     }
 8717:     if ($needlockcheck) {
 8718:         foreach my $envkey (keys(%env)) {
 8719:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8720:                my $courseid=$2;
 8721:                my $roleid=$1.'.'.$2;
 8722:                $courseid=~s/^\///;
 8723:                unless ($env{'request.role'} eq $roleid) {
 8724:                    my ($start,$end) = split(/\./,$env{$envkey});
 8725:                    next unless (($now >= $start) && (!$end || $end > $now));
 8726:                }
 8727:                my $expiretime=600;
 8728:                if ($env{'request.role'} eq $roleid) {
 8729: 		  $expiretime=120;
 8730:                }
 8731: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8732:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8733:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8734: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8735:                }
 8736:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8737:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8738: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8739:                        &log($env{'user.domain'},$env{'user.name'},
 8740:                             $env{'user.home'},
 8741:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8742:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8743:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8744: 		       return '';
 8745:                    }
 8746:                }
 8747:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8748:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8749: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8750:                        &log($env{'user.domain'},$env{'user.name'},
 8751:                             $env{'user.home'},
 8752:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8753:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8754:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8755: 		       return '';
 8756:                    }
 8757:                }
 8758: 	   }
 8759:        }
 8760:     }
 8761: 
 8762: #
 8763: # Rest of the restrictions depend on selected course
 8764: #
 8765: 
 8766:     unless ($env{'request.course.id'}) {
 8767: 	if ($thisallowed eq 'A') {
 8768: 	    return 'A';
 8769:         } elsif ($thisallowed eq 'B') {
 8770:             return 'B';
 8771: 	} else {
 8772: 	    return '1';
 8773: 	}
 8774:     }
 8775: 
 8776: #
 8777: # Now user is definitely in a course
 8778: #
 8779: 
 8780: 
 8781: # Course preferences
 8782: 
 8783:    if ($thisallowed=~/C/) {
 8784:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8785:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8786:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8787: 	   =~/\Q$rolecode\E/) {
 8788: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8789: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8790: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8791: 			$env{'request.course.id'});
 8792: 	   }
 8793:            return '';
 8794:        }
 8795: 
 8796:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8797: 	   =~/\Q$unamedom\E/) {
 8798: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8799: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8800: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8801: 			$env{'request.course.id'});
 8802: 	   }
 8803:            return '';
 8804:        }
 8805:    }
 8806: 
 8807: # Resource preferences
 8808: 
 8809:    if ($thisallowed=~/R/) {
 8810:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8811:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8812: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8813: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8814: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8815: 	   }
 8816: 	   return '';
 8817:        }
 8818:    }
 8819: 
 8820: # Restricted for deeplinked session?
 8821: 
 8822:     if ($env{'request.deeplink.login'}) {
 8823:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8824:             if (!$symb) { $symb=&symbread($uri,1); }
 8825:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8826:                 return '';
 8827:             }
 8828:         }
 8829:     }
 8830: 
 8831: # Restricted by state or randomout?
 8832: 
 8833:    if ($thisallowed=~/X/) {
 8834:       if ($env{'acc.randomout'}) {
 8835: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8836:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8837:             return ''; 
 8838:          }
 8839:       }
 8840:       if (&condval($statecond)) {
 8841: 	 return '2';
 8842:       } else {
 8843:          return '';
 8844:       }
 8845:    }
 8846: 
 8847:     if ($thisallowed eq 'A') {
 8848: 	return 'A';
 8849:     } elsif ($thisallowed eq 'B') {
 8850:         return 'B';
 8851:     } elsif ($thisallowed eq 'D') {
 8852:         return 'D';
 8853:     }
 8854:    return 'F';
 8855: }
 8856: 
 8857: # ------------------------------------------- Check construction space access
 8858: 
 8859: sub constructaccess {
 8860:     my ($url,$setpriv)=@_;
 8861: 
 8862: # We do not allow editing of previous versions of files
 8863:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8864: 
 8865: # Get username and domain from URL
 8866:     my ($ownername,$ownerdomain,$ownerhome);
 8867: 
 8868:     ($ownerdomain,$ownername) =
 8869:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8870: 
 8871: # The URL does not really point to any authorspace, forget it
 8872:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8873: 
 8874: # Now we need to see if the user has access to the authorspace of
 8875: # $ownername at $ownerdomain
 8876: 
 8877:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8878: # Real author for this?
 8879:        $ownerhome = $env{'user.home'};
 8880:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8881:           return ($ownername,$ownerdomain,$ownerhome);
 8882:        }
 8883:     } else {
 8884: # Co-author for this?
 8885:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8886:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8887:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8888:             return ($ownername,$ownerdomain,$ownerhome);
 8889:         }
 8890:         if ($env{'request.course.id'}) {
 8891:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8892:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8893:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8894:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8895:                     return ($ownername,$ownerdomain,$ownerhome);
 8896:                 }
 8897:             }
 8898:         }
 8899:     }
 8900: 
 8901: # We don't have any access right now. If we are not possibly going to do anything about this,
 8902: # we might as well leave
 8903:    unless ($setpriv) { return ''; }
 8904: 
 8905: # Backdoor access?
 8906:     my $allowed=&allowed('eco',$ownerdomain);
 8907: # Nope
 8908:     unless ($allowed) { return ''; }
 8909: # Looks like we may have access, but could be locked by the owner of the construction space
 8910:     if ($allowed eq 'U') {
 8911:         my %blocked=&get('environment',['domcoord.author'],
 8912:                          $ownerdomain,$ownername);
 8913: # Is blocked by owner
 8914:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8915:     }
 8916:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8917: # Grant temporary access
 8918:         my $then=$env{'user.login.time'};
 8919:         my $update=$env{'user.update.time'};
 8920:         if (!$update) { $update = $then; }
 8921:         my $refresh=$env{'user.refresh.time'};
 8922:         if (!$refresh) { $refresh = $update; }
 8923:         my $now = time;
 8924:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8925:                            $now,'ca','constructaccess');
 8926:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8927:         return($ownername,$ownerdomain,$ownerhome);
 8928:     }
 8929: # No business here
 8930:     return '';
 8931: }
 8932: 
 8933: # ----------------------------------------------------------- Content Blocking
 8934: 
 8935: {
 8936: # Caches for faster Course Contents display where content blocking
 8937: # is in operation (i.e., interval param set) for timed quiz.
 8938: #
 8939: # User for whom data are being temporarily cached.
 8940: my $cacheduser='';
 8941: # Course for which data are being temporarily cached.
 8942: my $cachedcid='';
 8943: # Cached blockers for this user (a hash of blocking items). 
 8944: my %cachedblockers=();
 8945: # When the data were last cached.
 8946: my $cachedlast='';
 8947: 
 8948: sub load_all_blockers {
 8949:     my ($uname,$udom)=@_;
 8950:     if (($uname ne '') && ($udom ne '')) { 
 8951:         if (($cacheduser eq $uname.':'.$udom) &&
 8952:             ($cachedcid eq $env{'request.course.id'}) &&
 8953:             (abs($cachedlast-time)<5)) {
 8954:             return;
 8955:         }
 8956:     }
 8957:     $cachedlast=time;
 8958:     $cacheduser=$uname.':'.$udom;
 8959:     $cachedcid=$env{'request.course.id'};
 8960:     %cachedblockers = &get_commblock_resources();
 8961:     return;
 8962: }
 8963: 
 8964: sub get_comm_blocks {
 8965:     my ($cdom,$cnum) = @_;
 8966:     if ($cdom eq '' || $cnum eq '') {
 8967:         return unless ($env{'request.course.id'});
 8968:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8969:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8970:     }
 8971:     my %commblocks;
 8972:     my $hashid=$cdom.'_'.$cnum;
 8973:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8974:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8975:         %commblocks = %{$blocksref};
 8976:     } else {
 8977:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8978:         my $cachetime = 600;
 8979:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8980:     }
 8981:     return %commblocks;
 8982: }
 8983: 
 8984: sub get_commblock_resources {
 8985:     my ($blocks) = @_;
 8986:     my %blockers = ();
 8987:     return %blockers unless ($env{'request.course.id'});
 8988:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8989:     if ($env{'request.course.sec'}) {
 8990:         $courseurl .= '/'.$env{'request.course.sec'};
 8991:     }
 8992:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8993:     my %commblocks;
 8994:     if (ref($blocks) eq 'HASH') {
 8995:         %commblocks = %{$blocks};
 8996:     } else {
 8997:         %commblocks = &get_comm_blocks();
 8998:     }
 8999:     return %blockers unless (keys(%commblocks) > 0); 
 9000:     my $navmap = Apache::lonnavmaps::navmap->new();
 9001:     return %blockers unless (ref($navmap));
 9002:     my $now = time;
 9003:     foreach my $block (keys(%commblocks)) {
 9004:         if ($block =~ /^(\d+)____(\d+)$/) {
 9005:             my ($start,$end) = ($1,$2);
 9006:             if ($start <= $now && $end >= $now) {
 9007:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9008:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9009:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9010:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9011:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9012:                             }
 9013:                         }
 9014:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9015:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9016:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9017:                             }
 9018:                         }
 9019:                     }
 9020:                 }
 9021:             }
 9022:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9023:             my $item = $1;
 9024:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9025:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9026:                     my (@interval,$mapname);
 9027:                     my $type = 'map';
 9028:                     if ($item eq 'course') {
 9029:                         $type = 'course';
 9030:                         @interval=&EXT("resource.0.interval");
 9031:                     } else {
 9032:                         if ($item =~ /___\d+___/) {
 9033:                             $type = 'resource';
 9034:                             @interval=&EXT("resource.0.interval",$item);
 9035:                         } else {
 9036:                             $mapname = &deversion($item);
 9037:                             if (ref($navmap)) {
 9038:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9039:                                 @interval = ($timelimit,'map');
 9040:                             }
 9041:                         }
 9042:                     }
 9043:                     if ($interval[0] =~ /^(\d+)/) {
 9044:                         my $timelimit = $1; 
 9045:                         my $first_access;
 9046:                         if ($type eq 'resource') {
 9047:                             $first_access=&get_first_access($interval[1],$item);
 9048:                         } elsif ($type eq 'map') {
 9049:                             $first_access=&get_first_access($interval[1],undef,$item);
 9050:                         } else {
 9051:                             $first_access=&get_first_access($interval[1]);
 9052:                         }
 9053:                         if ($first_access) {
 9054:                             my $timesup = $first_access+$timelimit;
 9055:                             if ($timesup > $now) {
 9056:                                 my $activeblock;
 9057:                                 if ($type eq 'resource') {
 9058:                                     if (ref($navmap)) {
 9059:                                         my $res = $navmap->getBySymb($item);
 9060:                                         if ($res->answerable()) {
 9061:                                             $activeblock = 1;
 9062:                                         }
 9063:                                     }
 9064:                                 } elsif ($type eq 'map') {
 9065:                                     my $mapsymb = &symbread($mapname,1);
 9066:                                     if (($mapsymb) && (ref($navmap))) {
 9067:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9068:                                         if (ref($mapres)) {
 9069:                                             my $first = $mapres->map_start();
 9070:                                             my $finish = $mapres->map_finish();
 9071:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9072:                                             if (ref($it)) {
 9073:                                                 my $res;
 9074:                                                 while ($res = $it->next(undef,1)) {
 9075:                                                     next unless (ref($res));
 9076:                                                     my $symb = $res->symb();
 9077:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9078:                                                     @interval=&EXT("resource.0.interval",$symb);
 9079:                                                     if ($interval[1] eq 'map') {
 9080:                                                         if ($res->answerable()) {
 9081:                                                             $activeblock = 1;
 9082:                                                             last;
 9083:                                                         }
 9084:                                                     }
 9085:                                                 }
 9086:                                             }
 9087:                                         }
 9088:                                     }
 9089:                                 }
 9090:                                 if ($activeblock) {
 9091:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9092:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9093:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9094:                                          }
 9095:                                     }
 9096:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9097:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9098:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9099:                                         }
 9100:                                     }
 9101:                                 }
 9102:                             }
 9103:                         }
 9104:                     }
 9105:                 }
 9106:             }
 9107:         }
 9108:     }
 9109:     return %blockers;
 9110: }
 9111: 
 9112: sub has_comm_blocking {
 9113:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9114:     my @blockers;
 9115:     return unless ($env{'request.course.id'});
 9116:     return unless ($priv eq 'bre');
 9117:     return if ($env{'request.state'} eq 'construct');
 9118:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9119:     if ($env{'request.course.sec'}) {
 9120:         $courseurl .= '/'.$env{'request.course.sec'};
 9121:     }
 9122:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9123:     my %blockinfo;
 9124:     if (ref($blocks) eq 'HASH') {
 9125:         %blockinfo = &get_commblock_resources($blocks);
 9126:     } else {
 9127:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9128:         %blockinfo = %cachedblockers;
 9129:     }
 9130:     return unless (keys(%blockinfo) > 0);
 9131:     my (%possibles,@symbs);
 9132:     if (!$symb) {
 9133:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9134:     }
 9135:     if ($symb) {
 9136:         @symbs = ($symb);
 9137:     } elsif (keys(%possibles)) { 
 9138:         @symbs = keys(%possibles);
 9139:     }
 9140:     my $noblock;
 9141:     foreach my $symb (@symbs) {
 9142:         last if ($noblock);
 9143:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9144:         foreach my $block (keys(%blockinfo)) {
 9145:             if ($block =~ /^firstaccess____(.+)$/) {
 9146:                 my $item = $1;
 9147:                 unless ($blocked) {
 9148:                     if (($item eq $map) || ($item eq $symb)) {
 9149:                         $noblock = 1;
 9150:                         last;
 9151:                     }
 9152:                 }
 9153:             }
 9154:             if (ref($blockinfo{$block}) eq 'HASH') {
 9155:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9156:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9157:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9158:                             push(@blockers,$block);
 9159:                         }
 9160:                     }
 9161:                 }
 9162:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9163:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9164:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9165:                             push(@blockers,$block);
 9166:                         }
 9167:                     }
 9168:                 }
 9169:             }
 9170:         }
 9171:     }
 9172:     unless ($noblock) { 
 9173:         return @blockers;
 9174:     }
 9175:     return;
 9176: }
 9177: }
 9178: 
 9179: sub deeplink_check {
 9180:     my ($priv,$symb,$uri) = @_;
 9181:     return unless ($env{'request.course.id'});
 9182:     return unless ($priv eq 'bre');
 9183:     return if ($env{'request.state'} eq 'construct');
 9184:     return if ($env{'request.role.adv'});
 9185:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9186:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9187:     my (%possibles,@symbs);
 9188:     if (!$symb) {
 9189:         $symb = &symbread($uri,1,1,1,\%possibles);
 9190:     }
 9191:     if ($symb) {
 9192:         @symbs = ($symb);
 9193:     } elsif (keys(%possibles)) {
 9194:         @symbs = keys(%possibles);
 9195:     }
 9196: 
 9197:     my ($deeplink_symb,$allow);
 9198:     if ($env{'request.deeplink.login'}) {
 9199:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9200:     }
 9201:     foreach my $symb (@symbs) {
 9202:         last if ($allow);
 9203:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9204:         if ($deeplink eq '') {
 9205:             $allow = 1;
 9206:         } else {
 9207:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9208:             if ($state ne 'only') {
 9209:                 $allow = 1;
 9210:             } else {
 9211:                 my $check_deeplink_entry;
 9212:                 if ($protect ne 'none') {
 9213:                     my ($acctype,$item) = split(/:/,$protect);
 9214:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9215:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9216:                             $check_deeplink_entry = 1
 9217:                         }
 9218:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9219:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9220:                             $check_deeplink_entry = 1;
 9221:                         }
 9222:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9223:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9224:                             $check_deeplink_entry = 1;
 9225:                         }
 9226:                     }
 9227:                 }
 9228:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9229:                     if ($scope eq 'res') {
 9230:                         if ($symb eq $deeplink_symb) {
 9231:                             $allow = 1;
 9232:                         }
 9233:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9234:                         my ($map_from_symb,$map_from_login);
 9235:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9236:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9237:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9238:                         } else {
 9239:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9240:                         }
 9241:                         if (($map_from_symb) && ($map_from_login)) {
 9242:                             if ($map_from_symb eq $map_from_login) {
 9243:                                 $allow = 1;
 9244:                             } elsif ($scope eq 'rec') {
 9245:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9246:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9247:                                     $allow = 1;
 9248:                                 }
 9249:                             }
 9250:                         }
 9251:                     }
 9252:                 }
 9253:             }
 9254:         }
 9255:     }
 9256:     return if ($allow);
 9257:     return 1;
 9258: }
 9259: 
 9260: # -------------------------------- Deversion and split uri into path an filename   
 9261: 
 9262: #
 9263: #   Removes the version from a URI and
 9264: #   splits it in to its filename and path to the filename.
 9265: #   Seems like File::Basename could have done this more clearly.
 9266: #   Parameters:
 9267: #      $uri   - input URI
 9268: #   Returns:
 9269: #     Two element list consisting of 
 9270: #     $pathname  - the URI up to and excluding the trailing /
 9271: #     $filename  - The part of the URI following the last /
 9272: #  NOTE:
 9273: #    Another realization of this is simply:
 9274: #    use File::Basename;
 9275: #    ...
 9276: #    $uri = shift;
 9277: #    $filename = basename($uri);
 9278: #    $path     = dirname($uri);
 9279: #    return ($filename, $path);
 9280: #
 9281: #     The implementation below is probably faster however.
 9282: #
 9283: sub split_uri_for_cond {
 9284:     my $uri=&deversion(&declutter(shift));
 9285:     my @uriparts=split(/\//,$uri);
 9286:     my $filename=pop(@uriparts);
 9287:     my $pathname=join('/',@uriparts);
 9288:     return ($pathname,$filename);
 9289: }
 9290: # --------------------------------------------------- Is a resource on the map?
 9291: 
 9292: sub is_on_map {
 9293:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9294:     #Trying to find the conditional for the file
 9295:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9296: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9297:     if ($match) {
 9298: 	return (1,$1);
 9299:     } else {
 9300: 	return (0,0);
 9301:     }
 9302: }
 9303: 
 9304: # --------------------------------------------------------- Get symb from alias
 9305: 
 9306: sub get_symb_from_alias {
 9307:     my $symb=shift;
 9308:     my ($map,$resid,$url)=&decode_symb($symb);
 9309: # Already is a symb
 9310:     if ($url) { return $symb; }
 9311: # Must be an alias
 9312:     my $aliassymb='';
 9313:     my %bighash;
 9314:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9315:                             &GDBM_READER(),0640)) {
 9316:         my $rid=$bighash{'mapalias_'.$symb};
 9317: 	if ($rid) {
 9318: 	    my ($mapid,$resid)=split(/\./,$rid);
 9319: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9320: 				    $resid,$bighash{'src_'.$rid});
 9321: 	}
 9322:         untie %bighash;
 9323:     }
 9324:     return $aliassymb;
 9325: }
 9326: 
 9327: # ----------------------------------------------------------------- Define Role
 9328: 
 9329: sub definerole {
 9330:   if (allowed('mcr','/')) {
 9331:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9332:     foreach my $role (split(':',$sysrole)) {
 9333: 	my ($crole,$cqual)=split(/\&/,$role);
 9334:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9335:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9336: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9337:                return "refused:s:$crole&$cqual"; 
 9338:             }
 9339:         }
 9340:     }
 9341:     foreach my $role (split(':',$domrole)) {
 9342: 	my ($crole,$cqual)=split(/\&/,$role);
 9343:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9344:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9345: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9346:                return "refused:d:$crole&$cqual"; 
 9347:             }
 9348:         }
 9349:     }
 9350:     foreach my $role (split(':',$courole)) {
 9351: 	my ($crole,$cqual)=split(/\&/,$role);
 9352:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9353:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9354: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9355:                return "refused:c:$crole&$cqual"; 
 9356:             }
 9357:         }
 9358:     }
 9359:     my $uhome;
 9360:     if (($uname ne '') && ($udom ne '')) {
 9361:         $uhome = &homeserver($uname,$udom);
 9362:         return $uhome if ($uhome eq 'no_host');
 9363:     } else {
 9364:         $uname = $env{'user.name'};
 9365:         $udom = $env{'user.domain'};
 9366:         $uhome = $env{'user.home'};
 9367:     }
 9368:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9369:                 "$udom:$uname:rolesdef_$rolename=".
 9370:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9371:     return reply($command,$uhome);
 9372:   } else {
 9373:     return 'refused';
 9374:   }
 9375: }
 9376: 
 9377: # ---------------- Make a metadata query against the network of library servers
 9378: 
 9379: sub metadata_query {
 9380:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9381:     my %rhash;
 9382:     my %libserv = &all_library();
 9383:     my @server_list = (defined($server_array) ? @$server_array
 9384:                                               : keys(%libserv) );
 9385:     for my $server (@server_list) {
 9386:         my $domains = ''; 
 9387:         if (ref($domains_hash) eq 'HASH') {
 9388:             $domains = $domains_hash->{$server}; 
 9389:         }
 9390: 	unless ($custom or $customshow) {
 9391: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9392: 	    $rhash{$server}=$reply;
 9393: 	}
 9394: 	else {
 9395: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9396: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9397: 			     $server);
 9398: 	    $rhash{$server}=$reply;
 9399: 	}
 9400:     }
 9401:     return \%rhash;
 9402: }
 9403: 
 9404: # ----------------------------------------- Send log queries and wait for reply
 9405: 
 9406: sub log_query {
 9407:     my ($uname,$udom,$query,%filters)=@_;
 9408:     my $uhome=&homeserver($uname,$udom);
 9409:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9410:     my $uhost=&hostname($uhome);
 9411:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9412:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9413:                        $uhome);
 9414:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9415:     return get_query_reply($queryid);
 9416: }
 9417: 
 9418: # -------------------------- Update MySQL table for portfolio file
 9419: 
 9420: sub update_portfolio_table {
 9421:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9422:     if ($group ne '') {
 9423:         $file_name =~s /^\Q$group\E//;
 9424:     }
 9425:     my $homeserver = &homeserver($uname,$udom);
 9426:     my $queryid=
 9427:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9428:                ':'.&escape($file_name).':'.$action,$homeserver);
 9429:     my $reply = &get_query_reply($queryid);
 9430:     return $reply;
 9431: }
 9432: 
 9433: # -------------------------- Update MySQL allusers table
 9434: 
 9435: sub update_allusers_table {
 9436:     my ($uname,$udom,$names) = @_;
 9437:     my $homeserver = &homeserver($uname,$udom);
 9438:     my $queryid=
 9439:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9440:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9441:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9442:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9443:                'generation='.&escape($names->{'generation'}).'%%'.
 9444:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9445:                'id='.&escape($names->{'id'}),$homeserver);
 9446:     return;
 9447: }
 9448: 
 9449: # ------- Request retrieval of institutional classlists for course(s)
 9450: 
 9451: sub fetch_enrollment_query {
 9452:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9453:     my ($homeserver,$sleep,$loopmax);
 9454:     my $maxtries = 1;
 9455:     if ($context eq 'automated') {
 9456:         $homeserver = $perlvar{'lonHostID'};
 9457:         $sleep = 2;
 9458:         $loopmax = 100;
 9459:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9460:     } else {
 9461:         $homeserver = &homeserver($cnum,$dom);
 9462:     }
 9463:     my $host=&hostname($homeserver);
 9464:     my $cmd = '';
 9465:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9466:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9467:     }
 9468:     $cmd =~ s/%%$//;
 9469:     $cmd = &escape($cmd);
 9470:     my $query = 'fetchenrollment';
 9471:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9472:     unless ($queryid=~/^\Q$host\E\_/) { 
 9473:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9474:         return 'error: '.$queryid;
 9475:     }
 9476:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9477:     my $tries = 1;
 9478:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9479:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9480:         $tries ++;
 9481:     }
 9482:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9483:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9484:     } else {
 9485:         my @responses = split(/:/,$reply);
 9486:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9487:             foreach my $line (@responses) {
 9488:                 my ($key,$value) = split(/=/,$line,2);
 9489:                 $$replyref{$key} = $value;
 9490:             }
 9491:         } else {
 9492:             my $pathname = LONCAPA::tempdir();
 9493:             foreach my $line (@responses) {
 9494:                 my ($key,$value) = split(/=/,$line);
 9495:                 $$replyref{$key} = $value;
 9496:                 if ($value > 0) {
 9497:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9498:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9499:                         my $destname = $pathname.'/'.$filename;
 9500:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9501:                         if ($xml_classlist =~ /^error/) {
 9502:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9503:                         } else {
 9504:                             if ( open(FILE,">",$destname) ) {
 9505:                                 print FILE &unescape($xml_classlist);
 9506:                                 close(FILE);
 9507:                             } else {
 9508:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9509:                             }
 9510:                         }
 9511:                     }
 9512:                 }
 9513:             }
 9514:         }
 9515:         return 'ok';
 9516:     }
 9517:     return 'error';
 9518: }
 9519: 
 9520: sub get_query_reply {
 9521:     my ($queryid,$sleep,$loopmax) = @_;
 9522:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9523:         $sleep = 0.2;
 9524:     }
 9525:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9526:         $loopmax = 100;
 9527:     }
 9528:     my $replyfile=LONCAPA::tempdir().$queryid;
 9529:     my $reply='';
 9530:     for (1..$loopmax) {
 9531: 	sleep($sleep);
 9532:         if (-e $replyfile.'.end') {
 9533: 	    if (open(my $fh,"<",$replyfile)) {
 9534: 		$reply = join('',<$fh>);
 9535: 		close($fh);
 9536: 	   } else { return 'error: reply_file_error'; }
 9537:            return &unescape($reply);
 9538: 	}
 9539:     }
 9540:     return 'timeout:'.$queryid;
 9541: }
 9542: 
 9543: sub courselog_query {
 9544: #
 9545: # possible filters:
 9546: # url: url or symb
 9547: # username
 9548: # domain
 9549: # action: view, submit, grade
 9550: # start: timestamp
 9551: # end: timestamp
 9552: #
 9553:     my (%filters)=@_;
 9554:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9555:     if ($filters{'url'}) {
 9556: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9557:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9558:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9559:     }
 9560:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9561:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9562:     return &log_query($cname,$cdom,'courselog',%filters);
 9563: }
 9564: 
 9565: sub userlog_query {
 9566: #
 9567: # possible filters:
 9568: # action: log check role
 9569: # start: timestamp
 9570: # end: timestamp
 9571: #
 9572:     my ($uname,$udom,%filters)=@_;
 9573:     return &log_query($uname,$udom,'userlog',%filters);
 9574: }
 9575: 
 9576: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9577: 
 9578: sub auto_run {
 9579:     my ($cnum,$cdom) = @_;
 9580:     my $response = 0;
 9581:     my $settings;
 9582:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9583:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9584:         $settings = $domconfig{'autoenroll'};
 9585:         if ($settings->{'run'} eq '1') {
 9586:             $response = 1;
 9587:         }
 9588:     } else {
 9589:         my $homeserver;
 9590:         if (&is_course($cdom,$cnum)) {
 9591:             $homeserver = &homeserver($cnum,$cdom);
 9592:         } else {
 9593:             $homeserver = &domain($cdom,'primary');
 9594:         }
 9595:         if ($homeserver ne 'no_host') {
 9596:             $response = &reply('autorun:'.$cdom,$homeserver);
 9597:         }
 9598:     }
 9599:     return $response;
 9600: }
 9601: 
 9602: sub auto_get_sections {
 9603:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9604:     my $homeserver;
 9605:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9606:         $homeserver = &homeserver($cnum,$cdom);
 9607:     }
 9608:     if (!defined($homeserver)) { 
 9609:         if ($cdom =~ /^$match_domain$/) {
 9610:             $homeserver = &domain($cdom,'primary');
 9611:         }
 9612:     }
 9613:     my @secs;
 9614:     if (defined($homeserver)) {
 9615:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9616:         unless ($response eq 'refused') {
 9617:             @secs = split(/:/,$response);
 9618:         }
 9619:     }
 9620:     return @secs;
 9621: }
 9622: 
 9623: sub auto_new_course {
 9624:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9625:     my $homeserver = &homeserver($cnum,$cdom);
 9626:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9627:     return $response;
 9628: }
 9629: 
 9630: sub auto_validate_courseID {
 9631:     my ($cnum,$cdom,$inst_course_id) = @_;
 9632:     my $homeserver = &homeserver($cnum,$cdom);
 9633:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9634:     return $response;
 9635: }
 9636: 
 9637: sub auto_validate_instcode {
 9638:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9639:     my ($homeserver,$response);
 9640:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9641:         $homeserver = &homeserver($cnum,$cdom);
 9642:     }
 9643:     if (!defined($homeserver)) {
 9644:         if ($cdom =~ /^$match_domain$/) {
 9645:             $homeserver = &domain($cdom,'primary');
 9646:         }
 9647:     }
 9648:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9649:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9650:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9651:     return ($outcome,$description,$defaultcredits);
 9652: }
 9653: 
 9654: sub auto_validate_inst_crosslist {
 9655:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9656:     my ($homeserver,$response);
 9657:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9658:         $homeserver = &homeserver($cnum,$cdom);
 9659:     }
 9660:     if (!defined($homeserver)) {
 9661:         if ($cdom =~ /^$match_domain$/) {
 9662:             $homeserver = &domain($cdom,'primary');
 9663:         }
 9664:     }
 9665:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9666:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9667:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9668:                          &escape($coowner),$homeserver);
 9669:     }
 9670:     return $response;
 9671: }
 9672: 
 9673: sub auto_create_password {
 9674:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9675:     my ($homeserver,$response);
 9676:     my $create_passwd = 0;
 9677:     my $authchk = '';
 9678:     if ($udom =~ /^$match_domain$/) {
 9679:         $homeserver = &domain($udom,'primary');
 9680:     }
 9681:     if ($homeserver eq '') {
 9682:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9683:             $homeserver = &homeserver($cnum,$cdom);
 9684:         }
 9685:     }
 9686:     if ($homeserver eq '') {
 9687:         $authchk = 'nodomain';
 9688:     } else {
 9689:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9690:         if ($response eq 'refused') {
 9691:             $authchk = 'refused';
 9692:         } else {
 9693:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9694:         }
 9695:     }
 9696:     return ($authparam,$create_passwd,$authchk);
 9697: }
 9698: 
 9699: sub auto_photo_permission {
 9700:     my ($cnum,$cdom,$students) = @_;
 9701:     my $homeserver = &homeserver($cnum,$cdom);
 9702:     my ($outcome,$perm_reqd,$conditions) = 
 9703: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9704:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9705: 	return (undef,undef);
 9706:     }
 9707:     return ($outcome,$perm_reqd,$conditions);
 9708: }
 9709: 
 9710: sub auto_checkphotos {
 9711:     my ($uname,$udom,$pid) = @_;
 9712:     my $homeserver = &homeserver($uname,$udom);
 9713:     my ($result,$resulttype);
 9714:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9715: 				   &escape($uname).':'.&escape($pid),
 9716: 				   $homeserver));
 9717:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9718: 	return (undef,undef);
 9719:     }
 9720:     if ($outcome) {
 9721:         ($result,$resulttype) = split(/:/,$outcome);
 9722:     } 
 9723:     return ($result,$resulttype);
 9724: }
 9725: 
 9726: sub auto_photochoice {
 9727:     my ($cnum,$cdom) = @_;
 9728:     my $homeserver = &homeserver($cnum,$cdom);
 9729:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9730: 						       &escape($cdom),
 9731: 						       $homeserver)));
 9732:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9733: 	return (undef,undef);
 9734:     }
 9735:     return ($update,$comment);
 9736: }
 9737: 
 9738: sub auto_photoupdate {
 9739:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9740:     my $homeserver = &homeserver($cnum,$dom);
 9741:     my $host=&hostname($homeserver);
 9742:     my $cmd = '';
 9743:     my $maxtries = 1;
 9744:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9745:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9746:     }
 9747:     $cmd =~ s/%%$//;
 9748:     $cmd = &escape($cmd);
 9749:     my $query = 'institutionalphotos';
 9750:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9751:     unless ($queryid=~/^\Q$host\E\_/) {
 9752:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9753:         return 'error: '.$queryid;
 9754:     }
 9755:     my $reply = &get_query_reply($queryid);
 9756:     my $tries = 1;
 9757:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9758:         $reply = &get_query_reply($queryid);
 9759:         $tries ++;
 9760:     }
 9761:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9762:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9763:     } else {
 9764:         my @responses = split(/:/,$reply);
 9765:         my $outcome = shift(@responses); 
 9766:         foreach my $item (@responses) {
 9767:             my ($key,$value) = split(/=/,$item);
 9768:             $$photo{$key} = $value;
 9769:         }
 9770:         return $outcome;
 9771:     }
 9772:     return 'error';
 9773: }
 9774: 
 9775: sub auto_instcode_format {
 9776:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9777: 	$cat_order) = @_;
 9778:     my $courses = '';
 9779:     my @homeservers;
 9780:     if ($caller eq 'global') {
 9781: 	my %servers = &get_servers($codedom,'library');
 9782: 	foreach my $tryserver (keys(%servers)) {
 9783: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9784: 		push(@homeservers,$tryserver);
 9785: 	    }
 9786:         }
 9787:     } elsif ($caller eq 'requests') {
 9788:         if ($codedom =~ /^$match_domain$/) {
 9789:             my $chome = &domain($codedom,'primary');
 9790:             unless ($chome eq 'no_host') {
 9791:                 push(@homeservers,$chome);
 9792:             }
 9793:         }
 9794:     } else {
 9795:         push(@homeservers,&homeserver($caller,$codedom));
 9796:     }
 9797:     foreach my $code (keys(%{$instcodes})) {
 9798:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9799:     }
 9800:     chop($courses);
 9801:     my $ok_response = 0;
 9802:     my $response;
 9803:     while (@homeservers > 0 && $ok_response == 0) {
 9804:         my $server = shift(@homeservers); 
 9805:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9806:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9807:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9808: 		split(/:/,$response);
 9809:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9810:             push(@{$codetitles},&str2array($codetitles_str));
 9811:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9812:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9813:             $ok_response = 1;
 9814:         }
 9815:     }
 9816:     if ($ok_response) {
 9817:         return 'ok';
 9818:     } else {
 9819:         return $response;
 9820:     }
 9821: }
 9822: 
 9823: sub auto_instcode_defaults {
 9824:     my ($domain,$returnhash,$code_order) = @_;
 9825:     my @homeservers;
 9826: 
 9827:     my %servers = &get_servers($domain,'library');
 9828:     foreach my $tryserver (keys(%servers)) {
 9829: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9830: 	    push(@homeservers,$tryserver);
 9831: 	}
 9832:     }
 9833: 
 9834:     my $response;
 9835:     foreach my $server (@homeservers) {
 9836:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9837:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9838: 	
 9839: 	foreach my $pair (split(/\&/,$response)) {
 9840: 	    my ($name,$value)=split(/\=/,$pair);
 9841: 	    if ($name eq 'code_order') {
 9842: 		@{$code_order} = split(/\&/,&unescape($value));
 9843: 	    } else {
 9844: 		$returnhash->{&unescape($name)}=&unescape($value);
 9845: 	    }
 9846: 	}
 9847: 	return 'ok';
 9848:     }
 9849: 
 9850:     return $response;
 9851: }
 9852: 
 9853: sub auto_possible_instcodes {
 9854:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9855:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9856:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9857:         return;
 9858:     }
 9859:     my (@homeservers,$uhome);
 9860:     if (defined(&domain($domain,'primary'))) {
 9861:         $uhome=&domain($domain,'primary');
 9862:         push(@homeservers,&domain($domain,'primary'));
 9863:     } else {
 9864:         my %servers = &get_servers($domain,'library');
 9865:         foreach my $tryserver (keys(%servers)) {
 9866:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9867:                 push(@homeservers,$tryserver);
 9868:             }
 9869:         }
 9870:     }
 9871:     my $response;
 9872:     foreach my $server (@homeservers) {
 9873:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9874:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9875:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9876:             split(':',$response);
 9877:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9878:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9879:         foreach my $item (split('&',$cat_title)) {   
 9880:             my ($name,$value)=split('=',$item);
 9881:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9882:         }
 9883:         foreach my $item (split('&',$cat_order)) {
 9884:             my ($name,$value)=split('=',$item);
 9885:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9886:         }
 9887:         return 'ok';
 9888:     }
 9889:     return $response;
 9890: }
 9891: 
 9892: sub auto_courserequest_checks {
 9893:     my ($dom) = @_;
 9894:     my ($homeserver,%validations);
 9895:     if ($dom =~ /^$match_domain$/) {
 9896:         $homeserver = &domain($dom,'primary');
 9897:     }
 9898:     unless ($homeserver eq 'no_host') {
 9899:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9900:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9901:             my @items = split(/&/,$response);
 9902:             foreach my $item (@items) {
 9903:                 my ($key,$value) = split('=',$item);
 9904:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9905:             }
 9906:         }
 9907:     }
 9908:     return %validations; 
 9909: }
 9910: 
 9911: sub auto_courserequest_validation {
 9912:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9913:     my ($homeserver,$response);
 9914:     if ($dom =~ /^$match_domain$/) {
 9915:         $homeserver = &domain($dom,'primary');
 9916:     }
 9917:     unless ($homeserver eq 'no_host') {
 9918:         my $customdata;
 9919:         if (ref($custominfo) eq 'HASH') {
 9920:             $customdata = &freeze_escape($custominfo);
 9921:         }
 9922:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9923:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9924:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9925:                                     $customdata,$homeserver));
 9926:     }
 9927:     return $response;
 9928: }
 9929: 
 9930: sub auto_validate_class_sec {
 9931:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9932:     my $homeserver = &homeserver($cnum,$cdom);
 9933:     my $ownerlist;
 9934:     if (ref($owners) eq 'ARRAY') {
 9935:         $ownerlist = join(',',@{$owners});
 9936:     } else {
 9937:         $ownerlist = $owners;
 9938:     }
 9939:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9940:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9941:     return $response;
 9942: }
 9943: 
 9944: sub auto_instsec_reformat {
 9945:     my ($cdom,$action,$instsecref) = @_;
 9946:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
 9947:     my @homeservers;
 9948:     if (defined(&domain($cdom,'primary'))) {
 9949:         push(@homeservers,&domain($cdom,'primary'));
 9950:     } else {
 9951:         my %servers = &get_servers($cdom,'library');
 9952:         foreach my $tryserver (keys(%servers)) {
 9953:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9954:                 push(@homeservers,$tryserver);
 9955:             }
 9956:         }
 9957:     }
 9958:     my $response;
 9959:     my %reformatted = %{$instsecref};
 9960:     foreach my $server (@homeservers) {
 9961:         if (ref($instsecref) eq 'HASH') {
 9962:             my $info = &freeze_escape($instsecref);
 9963:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
 9964:                                 $action.':'.$info,$server);
 9965:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
 9966:             my @items = split(/&/,$response);
 9967:             foreach my $item (@items) {
 9968:                 my ($key,$value) = split(/=/,$item);
 9969:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
 9970:             }
 9971:         }
 9972:     }
 9973:     return %reformatted;
 9974: }
 9975: 
 9976: sub auto_validate_instclasses {
 9977:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9978:     my ($homeserver,%validations);
 9979:     $homeserver = &homeserver($cnum,$cdom);
 9980:     unless ($homeserver eq 'no_host') {
 9981:         my $ownerlist;
 9982:         if (ref($owners) eq 'ARRAY') {
 9983:             $ownerlist = join(',',@{$owners});
 9984:         } else {
 9985:             $ownerlist = $owners;
 9986:         }
 9987:         if (ref($classesref) eq 'HASH') {
 9988:             my $classes = &freeze_escape($classesref);
 9989:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9990:                                 ':'.$cdom.':'.$classes,$homeserver);
 9991:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9992:                 my @items = split(/&/,$response);
 9993:                 foreach my $item (@items) {
 9994:                     my ($key,$value) = split('=',$item);
 9995:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9996:                 }
 9997:             }
 9998:         }
 9999:     }
10000:     return %validations;
10001: }
10002: 
10003: sub auto_crsreq_update {
10004:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10005:         $code,$accessstart,$accessend,$inbound) = @_;
10006:     my ($homeserver,%crsreqresponse);
10007:     if ($cdom =~ /^$match_domain$/) {
10008:         $homeserver = &domain($cdom,'primary');
10009:     }
10010:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10011:         my $info;
10012:         if (ref($inbound) eq 'HASH') {
10013:             $info = &freeze_escape($inbound);
10014:         }
10015:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10016:                             ':'.&escape($action).':'.&escape($ownername).':'.
10017:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10018:                             &escape($title).':'.&escape($code).':'.
10019:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10020:                             $homeserver);
10021:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10022:             my @items = split(/&/,$response);
10023:             foreach my $item (@items) {
10024:                 my ($key,$value) = split('=',$item);
10025:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10026:             }
10027:         }
10028:     }
10029:     return \%crsreqresponse;
10030: }
10031: 
10032: sub auto_export_grades {
10033:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10034:     my ($homeserver,%exportresponse);
10035:     if ($cdom =~ /^$match_domain$/) {
10036:         $homeserver = &domain($cdom,'primary');
10037:     }
10038:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10039:         my $info;
10040:         if (ref($inforef) eq 'HASH') {
10041:             $info = &freeze_escape($inforef);
10042:         }
10043:         if (ref($gradesref) eq 'HASH') {
10044:             my $grades = &freeze_escape($gradesref);
10045:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10046:                                 $info.':'.$grades,$homeserver);
10047:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10048:                 my @items = split(/&/,$response);
10049:                 foreach my $item (@items) {
10050:                     my ($key,$value) = split('=',$item);
10051:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10052:                 }
10053:             }
10054:         }
10055:     }
10056:     return \%exportresponse;
10057: }
10058: 
10059: sub check_instcode_cloning {
10060:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10061:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10062:         return;
10063:     }
10064:     my $canclone;
10065:     if (@{$code_order} > 0) {
10066:         my $instcoderegexp ='^';
10067:         my @clonecodes = split(/\&/,$cloner);
10068:         foreach my $item (@{$code_order}) {
10069:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10070:                 foreach my $pair (@clonecodes) {
10071:                     my ($key,$val) = split(/\=/,$pair,2);
10072:                     $val = &unescape($val);
10073:                     if ($key eq $item) {
10074:                         $instcoderegexp .= '('.$val.')';
10075:                         last;
10076:                     }
10077:                 }
10078:             } else {
10079:                 $instcoderegexp .= $codedefaults->{$item};
10080:             }
10081:         }
10082:         $instcoderegexp .= '$';
10083:         my (@from,@to);
10084:         eval {
10085:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10086:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10087:         };
10088:         if ((@from > 0) && (@to > 0)) {
10089:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10090:             if (!@diffs) {
10091:                 $canclone = 1;
10092:             }
10093:         }
10094:     }
10095:     return $canclone;
10096: }
10097: 
10098: sub default_instcode_cloning {
10099:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10100:     my (%codedefaults,@code_order,$canclone);
10101:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10102:         %codedefaults = %{$codedefaultsref};
10103:         @code_order = @{$codeorderref};
10104:     } elsif ($clonedom) {
10105:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10106:     }
10107:     if (($domdefclone) && (@code_order)) {
10108:         my @clonecodes = split(/\+/,$domdefclone);
10109:         my $instcoderegexp ='^';
10110:         foreach my $item (@code_order) {
10111:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10112:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10113:             } else {
10114:                 $instcoderegexp .= $codedefaults{$item};
10115:             }
10116:         }
10117:         $instcoderegexp .= '$';
10118:         my (@from,@to);
10119:         eval {
10120:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10121:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10122:         };
10123:         if ((@from > 0) && (@to > 0)) {
10124:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10125:             if (!@diffs) {
10126:                 $canclone = 1;
10127:             }
10128:         }
10129:     }
10130:     return $canclone;
10131: }
10132: 
10133: # ------------------------------------------------------- Course Group routines
10134: 
10135: sub get_coursegroups {
10136:     my ($cdom,$cnum,$group,$namespace) = @_;
10137:     return(&dump($namespace,$cdom,$cnum,$group));
10138: }
10139: 
10140: sub modify_coursegroup {
10141:     my ($cdom,$cnum,$groupsettings) = @_;
10142:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10143: }
10144: 
10145: sub toggle_coursegroup_status {
10146:     my ($cdom,$cnum,$group,$action) = @_;
10147:     my ($from_namespace,$to_namespace);
10148:     if ($action eq 'delete') {
10149:         $from_namespace = 'coursegroups';
10150:         $to_namespace = 'deleted_groups';
10151:     } else {
10152:         $from_namespace = 'deleted_groups';
10153:         $to_namespace = 'coursegroups';
10154:     }
10155:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10156:     if (my $tmp = &error(%curr_group)) {
10157:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10158:         return ('read error',$tmp);
10159:     } else {
10160:         my %savedsettings = %curr_group; 
10161:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10162:         my $deloutcome;
10163:         if ($result eq 'ok') {
10164:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10165:         } else {
10166:             return ('write error',$result);
10167:         }
10168:         if ($deloutcome eq 'ok') {
10169:             return 'ok';
10170:         } else {
10171:             return ('delete error',$deloutcome);
10172:         }
10173:     }
10174: }
10175: 
10176: sub modify_group_roles {
10177:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10178:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10179:     my $role = 'gr/'.&escape($userprivs);
10180:     my ($uname,$udom) = split(/:/,$user);
10181:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10182:     if ($result eq 'ok') {
10183:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10184:     }
10185:     return $result;
10186: }
10187: 
10188: sub modify_coursegroup_membership {
10189:     my ($cdom,$cnum,$membership) = @_;
10190:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10191:     return $result;
10192: }
10193: 
10194: sub get_active_groups {
10195:     my ($udom,$uname,$cdom,$cnum) = @_;
10196:     my $now = time;
10197:     my %groups = ();
10198:     foreach my $key (keys(%env)) {
10199:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10200:             my ($start,$end) = split(/\./,$env{$key});
10201:             if (($end!=0) && ($end<$now)) { next; }
10202:             if (($start!=0) && ($start>$now)) { next; }
10203:             if ($1 eq $cdom && $2 eq $cnum) {
10204:                 $groups{$3} = $env{$key} ;
10205:             }
10206:         }
10207:     }
10208:     return %groups;
10209: }
10210: 
10211: sub get_group_membership {
10212:     my ($cdom,$cnum,$group) = @_;
10213:     return(&dump('groupmembership',$cdom,$cnum,$group));
10214: }
10215: 
10216: sub get_users_groups {
10217:     my ($udom,$uname,$courseid) = @_;
10218:     my @usersgroups;
10219:     my $cachetime=1800;
10220: 
10221:     my $hashid="$udom:$uname:$courseid";
10222:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10223:     if (defined($cached)) {
10224:         @usersgroups = split(/:/,$grouplist);
10225:     } else {  
10226:         $grouplist = '';
10227:         my $courseurl = &courseid_to_courseurl($courseid);
10228:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10229:         my $access_end = $env{'course.'.$courseid.
10230:                               '.default_enrollment_end_date'};
10231:         my $now = time;
10232:         foreach my $key (keys(%roleshash)) {
10233:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10234:                 my $group = $1;
10235:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10236:                     my $start = $2;
10237:                     my $end = $1;
10238:                     if ($start == -1) { next; } # deleted from group
10239:                     if (($start!=0) && ($start>$now)) { next; }
10240:                     if (($end!=0) && ($end<$now)) {
10241:                         if ($access_end && $access_end < $now) {
10242:                             if ($access_end - $end < 86400) {
10243:                                 push(@usersgroups,$group);
10244:                             }
10245:                         }
10246:                         next;
10247:                     }
10248:                     push(@usersgroups,$group);
10249:                 }
10250:             }
10251:         }
10252:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10253:         $grouplist = join(':',@usersgroups);
10254:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10255:     }
10256:     return @usersgroups;
10257: }
10258: 
10259: sub devalidate_getgroups_cache {
10260:     my ($udom,$uname,$cdom,$cnum)=@_;
10261:     my $courseid = $cdom.'_'.$cnum;
10262: 
10263:     my $hashid="$udom:$uname:$courseid";
10264:     &devalidate_cache_new('getgroups',$hashid);
10265: }
10266: 
10267: # ------------------------------------------------------------------ Plain Text
10268: 
10269: sub plaintext {
10270:     my ($short,$type,$cid,$forcedefault) = @_;
10271:     if ($short =~ m{^cr/}) {
10272: 	return (split('/',$short))[-1];
10273:     }
10274:     if (!defined($cid)) {
10275:         $cid = $env{'request.course.id'};
10276:     }
10277:     my %rolenames = (
10278:                       Course    => 'std',
10279:                       Community => 'alt1',
10280:                       Placement => 'std',
10281:                     );
10282:     if ($cid ne '') {
10283:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10284:             unless ($forcedefault) {
10285:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10286:                 &Apache::lonlocal::mt_escape(\$roletext);
10287:                 return &Apache::lonlocal::mt($roletext);
10288:             }
10289:         }
10290:     }
10291:     if ((defined($type)) && (defined($rolenames{$type})) &&
10292:         (defined($rolenames{$type})) && 
10293:         (defined($prp{$short}{$rolenames{$type}}))) {
10294:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10295:     } elsif ($cid ne '') {
10296:         my $crstype = $env{'course.'.$cid.'.type'};
10297:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10298:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10299:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10300:         }
10301:     }
10302:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10303: }
10304: 
10305: # ----------------------------------------------------------------- Assign Role
10306: 
10307: sub assignrole {
10308:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10309:         $context)=@_;
10310:     my $mrole;
10311:     if ($role =~ /^cr\//) {
10312:         my $cwosec=$url;
10313:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10314: 	unless (&allowed('ccr',$cwosec)) {
10315:            my $refused = 1;
10316:            if ($context eq 'requestcourses') {
10317:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10318:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10319:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10320:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10321:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10322:                            if ($crsenv{'internal.courseowner'} eq
10323:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10324:                                $refused = '';
10325:                            }
10326:                        }
10327:                    }
10328:                }
10329:            }
10330:            if ($refused) {
10331:                &logthis('Refused custom assignrole: '.
10332:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10333:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10334:                return 'refused';
10335:            }
10336:         }
10337:         $mrole='cr';
10338:     } elsif ($role =~ /^gr\//) {
10339:         my $cwogrp=$url;
10340:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10341:         unless (&allowed('mdg',$cwogrp)) {
10342:             &logthis('Refused group assignrole: '.
10343:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10344:                     $env{'user.name'}.' at '.$env{'user.domain'});
10345:             return 'refused';
10346:         }
10347:         $mrole='gr';
10348:     } else {
10349:         my $cwosec=$url;
10350:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10351:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10352:             my $refused;
10353:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10354:                 if (!(&allowed('c'.$role,$url))) {
10355:                     $refused = 1;
10356:                 }
10357:             } else {
10358:                 $refused = 1;
10359:             }
10360:             if ($refused) {
10361:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10362:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10363:                     my %crsenv;
10364:                     if ($role eq 'cc' || $role eq 'co') {
10365:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10366:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10367:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10368:                                 if ($crsenv{'internal.courseowner'} eq 
10369:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10370:                                     $refused = '';
10371:                                 }
10372:                             }
10373:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10374:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10375:                                 if ($crsenv{'internal.courseowner'} eq 
10376:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10377:                                     $refused = '';
10378:                                 }
10379:                             }
10380:                         }
10381:                     }
10382:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10383:                     if ($role eq 'st') {
10384:                         $refused = '';
10385:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10386:                         $refused = '';
10387:                     }
10388:                 } elsif ($context eq 'requestcourses') {
10389:                     my @possroles = ('st','ta','ep','in','cc','co');
10390:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10391:                         my $wrongcc;
10392:                         if ($cnum =~ /^$match_community$/) {
10393:                             $wrongcc = 1 if ($role eq 'cc');
10394:                         } else {
10395:                             $wrongcc = 1 if ($role eq 'co');
10396:                         }
10397:                         unless ($wrongcc) {
10398:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10399:                             if ($crsenv{'internal.courseowner'} eq 
10400:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10401:                                 $refused = '';
10402:                             }
10403:                         }
10404:                     }
10405:                 } elsif ($context eq 'requestauthor') {
10406:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10407:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10408:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10409:                             $refused = '';
10410:                         } else {
10411:                             my %domdefaults = &get_domain_defaults($udom);
10412:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10413:                                 my $checkbystatus;
10414:                                 if ($env{'user.adv'}) { 
10415:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10416:                                     if ($disposition eq 'automatic') {
10417:                                         $refused = '';
10418:                                     } elsif ($disposition eq '') {
10419:                                         $checkbystatus = 1;
10420:                                     } 
10421:                                 } else {
10422:                                     $checkbystatus = 1;
10423:                                 }
10424:                                 if ($checkbystatus) {
10425:                                     if ($env{'environment.inststatus'}) {
10426:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10427:                                         foreach my $type (@inststatuses) {
10428:                                             if (($type ne '') &&
10429:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10430:                                                 $refused = '';
10431:                                             }
10432:                                         }
10433:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10434:                                         $refused = '';
10435:                                     }
10436:                                 }
10437:                             }
10438:                         }
10439:                     }
10440:                 }
10441:                 if ($refused) {
10442:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10443:                              ' '.$role.' '.$end.' '.$start.' by '.
10444: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10445:                     return 'refused';
10446:                 }
10447:             }
10448:         } elsif ($role eq 'au') {
10449:             if ($url ne '/'.$udom.'/') {
10450:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10451:                          ' to assign author role for '.$uname.':'.$udom.
10452:                          ' in domain: '.$url.' refused (wrong domain).');
10453:                 return 'refused';
10454:             }
10455:         }
10456:         $mrole=$role;
10457:     }
10458:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10459:                 "$udom:$uname:$url".'_'."$mrole=$role";
10460:     if ($end) { $command.='_'.$end; }
10461:     if ($start) {
10462: 	if ($end) { 
10463:            $command.='_'.$start; 
10464:         } else {
10465:            $command.='_0_'.$start;
10466:         }
10467:     }
10468:     my $origstart = $start;
10469:     my $origend = $end;
10470:     my $delflag;
10471: # actually delete
10472:     if ($deleteflag) {
10473: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10474: # modify command to delete the role
10475:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10476:                 "$udom:$uname:$url".'_'."$mrole";
10477: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10478: # set start and finish to negative values for userrolelog
10479:            $start=-1;
10480:            $end=-1;
10481:            $delflag = 1;
10482:         }
10483:     }
10484: # send command
10485:     my $answer=&reply($command,&homeserver($uname,$udom));
10486: # log new user role if status is ok
10487:     if ($answer eq 'ok') {
10488: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10489:         if (($role eq 'cc') || ($role eq 'in') ||
10490:             ($role eq 'ep') || ($role eq 'ad') ||
10491:             ($role eq 'ta') || ($role eq 'st') ||
10492:             ($role=~/^cr/) || ($role eq 'gr') ||
10493:             ($role eq 'co')) {
10494: # for course roles, perform group memberships changes triggered by role change.
10495:             unless ($role =~ /^gr/) {
10496:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10497:                                                  $origstart,$selfenroll,$context);
10498:             }
10499:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10500:                            $selfenroll,$context);
10501:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10502:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10503:                  ($role eq 'da')) {
10504:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10505:                            $context);
10506:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10507:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10508:                              $context); 
10509:         }
10510:         if ($role eq 'cc') {
10511:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10512:         }
10513:     }
10514:     return $answer;
10515: }
10516: 
10517: sub autoupdate_coowners {
10518:     my ($url,$end,$start,$uname,$udom) = @_;
10519:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10520:     if (($cdom ne '') && ($cnum ne '')) {
10521:         my $now = time;
10522:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10523:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10524:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10525:             my $instcode = $coursehash{'internal.coursecode'};
10526:             my $xlists = $coursehash{'internal.crosslistings'};
10527:             if ($instcode ne '') {
10528:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10529:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10530:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10531:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10532:                         unless ($result eq 'valid') {
10533:                             if ($xlists ne '') {
10534:                                 foreach my $xlist (split(',',$xlists)) {
10535:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10536:                                     $result =
10537:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10538:                                                                       $inst_crosslist,$uname.':'.$udom);
10539:                                     last if ($result eq 'valid');
10540:                                 }
10541:                             }
10542:                         }
10543:                         if ($result eq 'valid') {
10544:                             if ($coursehash{'internal.co-owners'}) {
10545:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10546:                                     push(@newcoowners,$coowner);
10547:                                 }
10548:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10549:                                     push(@newcoowners,$uname.':'.$udom);
10550:                                 }
10551:                                 @newcoowners = sort(@newcoowners);
10552:                             } else {
10553:                                 push(@newcoowners,$uname.':'.$udom);
10554:                             }
10555:                         } elsif ($coursehash{'internal.co-owners'}) {
10556:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10557:                                 unless ($coowner eq $uname.':'.$udom) {
10558:                                     push(@newcoowners,$coowner);
10559:                                 }
10560:                             }
10561:                             unless (@newcoowners > 0) {
10562:                                 $delcoowners = 1;
10563:                                 $coowners = '';
10564:                             }
10565:                         }
10566:                         if (@newcoowners || $delcoowners) {
10567:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10568:                                             $delcoowners,@newcoowners);
10569:                         }
10570:                     }
10571:                 }
10572:             }
10573:         }
10574:     }
10575: }
10576: 
10577: sub store_coowners {
10578:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10579:     my $cid = $cdom.'_'.$cnum;
10580:     my ($coowners,$delresult,$putresult);
10581:     if (@newcoowners) {
10582:         $coowners = join(',',@newcoowners);
10583:         my %coownershash = (
10584:                             'internal.co-owners' => $coowners,
10585:                            );
10586:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10587:         if ($putresult eq 'ok') {
10588:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10589:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10590:             }
10591:         }
10592:     }
10593:     if ($delcoowners) {
10594:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10595:         if ($delresult eq 'ok') {
10596:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10597:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10598:             }
10599:         }
10600:     }
10601:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10602:         my %crsinfo =
10603:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10604:         if (ref($crsinfo{$cid}) eq 'HASH') {
10605:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10606:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10607:         }
10608:     }
10609: }
10610: 
10611: # -------------------------------------------------- Modify user authentication
10612: # Overrides without validation
10613: 
10614: sub modifyuserauth {
10615:     my ($udom,$uname,$umode,$upass)=@_;
10616:     my $uhome=&homeserver($uname,$udom);
10617:     my $allowed;
10618:     if (&allowed('mau',$udom)) {
10619:         $allowed = 1;
10620:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10621:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10622:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10623:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10624:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10625:         if (($cdom ne '') && ($cnum ne '')) {
10626:             my $is_owner = &is_course_owner($cdom,$cnum);
10627:             if ($is_owner) {
10628:                 $allowed = 1;
10629:             }
10630:         }
10631:     }
10632:     unless ($allowed) { return 'refused'; }
10633:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10634:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10635:              ' in domain '.$env{'request.role.domain'});  
10636:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10637: 		     &escape($upass),$uhome);
10638:     my $ip = &get_requestor_ip();
10639:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10640:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10641:          '(Remote '.$ip.'): '.$reply);
10642:     &log($udom,,$uname,$uhome,
10643:         'Authentication changed by '.$env{'user.domain'}.', '.
10644:                                      $env{'user.name'}.', '.$umode.
10645:          '(Remote '.$ip.'): '.$reply);
10646:     unless ($reply eq 'ok') {
10647:         &logthis('Authentication mode error: '.$reply);
10648: 	return 'error: '.$reply;
10649:     }   
10650:     return 'ok';
10651: }
10652: 
10653: # --------------------------------------------------------------- Modify a user
10654: 
10655: sub modifyuser {
10656:     my ($udom,    $uname, $uid,
10657:         $umode,   $upass, $first,
10658:         $middle,  $last,  $gene,
10659:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10660:     $udom= &LONCAPA::clean_domain($udom);
10661:     $uname=&LONCAPA::clean_username($uname);
10662:     my $showcandelete = 'none';
10663:     if (ref($candelete) eq 'ARRAY') {
10664:         if (@{$candelete} > 0) {
10665:             $showcandelete = join(', ',@{$candelete});
10666:         }
10667:     }
10668:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10669:              $umode.', '.$first.', '.$middle.', '.
10670: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10671:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10672:                                      ' desiredhome not specified'). 
10673:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10674:              ' in domain '.$env{'request.role.domain'});
10675:     my $uhome=&homeserver($uname,$udom,'true');
10676:     my $newuser;
10677:     if ($uhome eq 'no_host') {
10678:         $newuser = 1;
10679:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10680:                 ($umode eq 'lti')) {
10681:             return 'error: more information needed to create new user';
10682:         }
10683:     }
10684: # ----------------------------------------------------------------- Create User
10685:     if (($uhome eq 'no_host') && 
10686: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10687:         my $unhome='';
10688:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10689:             $unhome = $desiredhome;
10690: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10691: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10692:         } else { # load balancing routine for determining $unhome
10693:             my $loadm=10000000;
10694: 	    my %servers = &get_servers($udom,'library');
10695: 	    foreach my $tryserver (keys(%servers)) {
10696: 		my $answer=reply('load',$tryserver);
10697: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10698: 		    $loadm=$answer;
10699: 		    $unhome=$tryserver;
10700: 		}
10701: 	    }
10702:         }
10703:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10704: 	    return 'error: unable to find a home server for '.$uname.
10705:                    ' in domain '.$udom;
10706:         }
10707:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10708:                          &escape($upass),$unhome);
10709: 	unless ($reply eq 'ok') {
10710:             return 'error: '.$reply;
10711:         }   
10712:         $uhome=&homeserver($uname,$udom,'true');
10713:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10714: 	    return 'error: unable verify users home machine.';
10715:         }
10716:     }   # End of creation of new user
10717: # ---------------------------------------------------------------------- Add ID
10718:     if ($uid) {
10719:        $uid=~tr/A-Z/a-z/;
10720:        my %uidhash=&idrget($udom,$uname);
10721:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10722:          && (!$forceid)) {
10723: 	  unless ($uid eq $uidhash{$uname}) {
10724: 	      return 'error: user id "'.$uid.'" does not match '.
10725:                   'current user id "'.$uidhash{$uname}.'".';
10726:           }
10727:        } else {
10728: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10729:        }
10730:     }
10731: # -------------------------------------------------------------- Add names, etc
10732:     my @tmp=&get('environment',
10733: 		   ['firstname','middlename','lastname','generation','id',
10734:                     'permanentemail','inststatus'],
10735: 		   $udom,$uname);
10736:     my (%names,%oldnames);
10737:     if ($tmp[0] =~ m/^error:.*/) { 
10738:         %names=(); 
10739:     } else {
10740:         %names = @tmp;
10741:         %oldnames = %names;
10742:     }
10743: #
10744: # If name, email and/or uid are blank (e.g., because an uploaded file
10745: # of users did not contain them), do not overwrite existing values
10746: # unless field is in $candelete array ref.  
10747: #
10748: 
10749:     my @fields = ('firstname','middlename','lastname','generation',
10750:                   'permanentemail','id');
10751:     my %newvalues;
10752:     if (ref($candelete) eq 'ARRAY') {
10753:         foreach my $field (@fields) {
10754:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10755:                 if ($field eq 'firstname') {
10756:                     $names{$field} = $first;
10757:                 } elsif ($field eq 'middlename') {
10758:                     $names{$field} = $middle;
10759:                 } elsif ($field eq 'lastname') {
10760:                     $names{$field} = $last;
10761:                 } elsif ($field eq 'generation') { 
10762:                     $names{$field} = $gene;
10763:                 } elsif ($field eq 'permanentemail') {
10764:                     $names{$field} = $email;
10765:                 } elsif ($field eq 'id') {
10766:                     $names{$field}  = $uid;
10767:                 }
10768:             }
10769:         }
10770:     }
10771:     if ($first)  { $names{'firstname'}  = $first; }
10772:     if (defined($middle)) { $names{'middlename'} = $middle; }
10773:     if ($last)   { $names{'lastname'}   = $last; }
10774:     if (defined($gene))   { $names{'generation'} = $gene; }
10775:     if ($email) {
10776:        $email=~s/[^\w\@\.\-\,]//gs;
10777:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10778:     }
10779:     if ($uid) { $names{'id'}  = $uid; }
10780:     if (defined($inststatus)) {
10781:         $names{'inststatus'} = '';
10782:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10783:         if (ref($usertypes) eq 'HASH') {
10784:             my @okstatuses; 
10785:             foreach my $item (split(/:/,$inststatus)) {
10786:                 if (defined($usertypes->{$item})) {
10787:                     push(@okstatuses,$item);  
10788:                 }
10789:             }
10790:             if (@okstatuses) {
10791:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10792:             }
10793:         }
10794:     }
10795:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10796:                  $umode.', '.$first.', '.$middle.', '.
10797:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10798:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10799:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10800:     } else {
10801:         $logmsg .= ' during self creation';
10802:     }
10803:     my $changed;
10804:     if ($newuser) {
10805:         $changed = 1;
10806:     } else {
10807:         foreach my $field (@fields) {
10808:             if ($names{$field} ne $oldnames{$field}) {
10809:                 $changed = 1;
10810:                 last;
10811:             }
10812:         }
10813:     }
10814:     unless ($changed) {
10815:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10816:         &logthis($logmsg);
10817:         return 'ok';
10818:     }
10819:     my $reply = &put('environment', \%names, $udom,$uname);
10820:     if ($reply ne 'ok') { 
10821:         return 'error: '.$reply;
10822:     }
10823:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10824:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10825:     }
10826:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10827:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10828:     $logmsg = 'Success modifying user '.$logmsg;
10829:     &logthis($logmsg);
10830:     return 'ok';
10831: }
10832: 
10833: # -------------------------------------------------------------- Modify student
10834: 
10835: sub modifystudent {
10836:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10837:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10838:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10839:     if (!$cid) {
10840: 	unless ($cid=$env{'request.course.id'}) {
10841: 	    return 'not_in_class';
10842: 	}
10843:     }
10844: # --------------------------------------------------------------- Make the user
10845:     my $reply=&modifyuser
10846: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10847:          $desiredhome,$email,$inststatus);
10848:     unless ($reply eq 'ok') { return $reply; }
10849:     # This will cause &modify_student_enrollment to get the uid from the
10850:     # student's environment
10851:     $uid = undef if (!$forceid);
10852:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10853:                                         $gene,$usec,$end,$start,$type,$locktype,
10854:                                         $cid,$selfenroll,$context,$credits,$instsec);
10855:     return $reply;
10856: }
10857: 
10858: sub modify_student_enrollment {
10859:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10860:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10861:     my ($cdom,$cnum,$chome);
10862:     if (!$cid) {
10863: 	unless ($cid=$env{'request.course.id'}) {
10864: 	    return 'not_in_class';
10865: 	}
10866: 	$cdom=$env{'course.'.$cid.'.domain'};
10867: 	$cnum=$env{'course.'.$cid.'.num'};
10868:     } else {
10869: 	($cdom,$cnum)=split(/_/,$cid);
10870:     }
10871:     $chome=$env{'course.'.$cid.'.home'};
10872:     if (!$chome) {
10873: 	$chome=&homeserver($cnum,$cdom);
10874:     }
10875:     if (!$chome) { return 'unknown_course'; }
10876:     # Make sure the user exists
10877:     my $uhome=&homeserver($uname,$udom);
10878:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10879: 	return 'error: no such user';
10880:     }
10881:     # Get student data if we were not given enough information
10882:     if (!defined($first)  || $first  eq '' || 
10883:         !defined($last)   || $last   eq '' || 
10884:         !defined($uid)    || $uid    eq '' || 
10885:         !defined($middle) || $middle eq '' || 
10886:         !defined($gene)   || $gene   eq '') {
10887:         # They did not supply us with enough data to enroll the student, so
10888:         # we need to pick up more information.
10889:         my %tmp = &get('environment',
10890:                        ['firstname','middlename','lastname', 'generation','id']
10891:                        ,$udom,$uname);
10892: 
10893:         #foreach my $key (keys(%tmp)) {
10894:         #    &logthis("key $key = ".$tmp{$key});
10895:         #}
10896:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10897:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10898:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10899:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10900:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10901:     }
10902:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10903:     my $user = "$uname:$udom";
10904:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10905:     my $reply=cput('classlist',
10906: 		   {$user => 
10907: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10908: 		   $cdom,$cnum);
10909:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10910:         &devalidate_getsection_cache($udom,$uname,$cid);
10911:     } else { 
10912: 	return 'error: '.$reply;
10913:     }
10914:     # Add student role to user
10915:     my $uurl='/'.$cid;
10916:     $uurl=~s/\_/\//g;
10917:     if ($usec) {
10918: 	$uurl.='/'.$usec;
10919:     }
10920:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10921:                              $selfenroll,$context);
10922:     if ($result ne 'ok') {
10923:         if ($old_entry{$user} ne '') {
10924:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10925:         } else {
10926:             $reply = &del('classlist',[$user],$cdom,$cnum);
10927:         }
10928:     }
10929:     return $result; 
10930: }
10931: 
10932: sub format_name {
10933:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10934:     my $name;
10935:     if ($first ne 'lastname') {
10936: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10937:     } else {
10938: 	if ($lastname=~/\S/) {
10939: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10940: 	    $name=~s/\s+,/,/;
10941: 	} else {
10942: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10943: 	}
10944:     }
10945:     $name=~s/^\s+//;
10946:     $name=~s/\s+$//;
10947:     $name=~s/\s+/ /g;
10948:     return $name;
10949: }
10950: 
10951: # ------------------------------------------------- Write to course preferences
10952: 
10953: sub writecoursepref {
10954:     my ($courseid,%prefs)=@_;
10955:     $courseid=~s/^\///;
10956:     $courseid=~s/\_/\//g;
10957:     my ($cdomain,$cnum)=split(/\//,$courseid);
10958:     my $chome=homeserver($cnum,$cdomain);
10959:     if (($chome eq '') || ($chome eq 'no_host')) { 
10960: 	return 'error: no such course';
10961:     }
10962:     my $cstring='';
10963:     foreach my $pref (keys(%prefs)) {
10964: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10965:     }
10966:     $cstring=~s/\&$//;
10967:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10968: }
10969: 
10970: # ---------------------------------------------------------- Make/modify course
10971: 
10972: sub createcourse {
10973:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10974:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10975:     $url=&declutter($url);
10976:     my $cid='';
10977:     if ($context eq 'requestcourses') {
10978:         my $can_create = 0;
10979:         my ($ownername,$ownerdom) = split(':',$course_owner);
10980:         if ($udom eq $ownerdom) {
10981:             my $reload;
10982:             if (($callercontext eq 'auto') &&
10983:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10984:                 $reload = 'reload';
10985:             }
10986:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10987:                                   $context)) {
10988:                 $can_create = 1;
10989:             }
10990:         } else {
10991:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10992:                                            $category);
10993:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10994:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10995:                 if (@curr > 0) {
10996:                     my @options = qw(approval validate autolimit);
10997:                     my $optregex = join('|',@options);
10998:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10999:                         $can_create = 1;
11000:                     }
11001:                 }
11002:             }
11003:         }
11004:         if ($can_create) {
11005:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11006:                 unless (&allowed('ccc',$udom)) {
11007:                     return 'refused'; 
11008:                 }
11009:             }
11010:         } else {
11011:             return 'refused';
11012:         }
11013:     } elsif (!&allowed('ccc',$udom)) {
11014:         return 'refused';
11015:     }
11016: # --------------------------------------------------------------- Get Unique ID
11017:     my $uname;
11018:     if ($cnum =~ /^$match_courseid$/) {
11019:         my $chome=&homeserver($cnum,$udom,'true');
11020:         if (($chome eq '') || ($chome eq 'no_host')) {
11021:             $uname = $cnum;
11022:         } else {
11023:             $uname = &generate_coursenum($udom,$crstype);
11024:         }
11025:     } else {
11026:         $uname = &generate_coursenum($udom,$crstype);
11027:     }
11028:     return $uname if ($uname =~ /^error/);
11029: # -------------------------------------------------- Check supplied server name
11030:     if (!defined($course_server)) {
11031:         if (defined(&domain($udom,'primary'))) {
11032:             $course_server = &domain($udom,'primary');
11033:         } else {
11034:             $course_server = $env{'user.home'}; 
11035:         }
11036:     }
11037:     my %host_servers =
11038:         &Apache::lonnet::get_servers($udom,'library');
11039:     unless ($host_servers{$course_server}) {
11040:         return 'error: invalid home server for course: '.$course_server;
11041:     }
11042: # ------------------------------------------------------------- Make the course
11043:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11044:                       $course_server);
11045:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11046:     my $uhome=&homeserver($uname,$udom,'true');
11047:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11048: 	return 'error: no such course';
11049:     }
11050: # ----------------------------------------------------------------- Course made
11051: # log existence
11052:     my $now = time;
11053:     my $newcourse = {
11054:                     $udom.'_'.$uname => {
11055:                                      description => $description,
11056:                                      inst_code   => $inst_code,
11057:                                      owner       => $course_owner,
11058:                                      type        => $crstype,
11059:                                      creator     => $env{'user.name'}.':'.
11060:                                                     $env{'user.domain'},
11061:                                      created     => $now,
11062:                                      context     => $context,
11063:                                                 },
11064:                     };
11065:     &courseidput($udom,$newcourse,$uhome,'notime');
11066: # set toplevel url
11067:     my $topurl=$url;
11068:     unless ($nonstandard) {
11069: # ------------------------------------------ For standard courses, make top url
11070:         my $mapurl=&clutter($url);
11071:         if ($mapurl eq '/res/') { $mapurl=''; }
11072:         $env{'form.initmap'}=(<<ENDINITMAP);
11073: <map>
11074: <resource id="1" type="start"></resource>
11075: <resource id="2" src="$mapurl"></resource>
11076: <resource id="3" type="finish"></resource>
11077: <link index="1" from="1" to="2"></link>
11078: <link index="2" from="2" to="3"></link>
11079: </map>
11080: ENDINITMAP
11081:         $topurl=&declutter(
11082:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11083:                           );
11084:     }
11085: # ----------------------------------------------------------- Write preferences
11086:     &writecoursepref($udom.'_'.$uname,
11087:                      ('description'              => $description,
11088:                       'url'                      => $topurl,
11089:                       'internal.creator'         => $env{'user.name'}.':'.
11090:                                                     $env{'user.domain'},
11091:                       'internal.created'         => $now,
11092:                       'internal.creationcontext' => $context)
11093:                     );
11094:     return '/'.$udom.'/'.$uname;
11095: }
11096: 
11097: # ------------------------------------------------------------------- Create ID
11098: sub generate_coursenum {
11099:     my ($udom,$crstype) = @_;
11100:     my $domdesc = &domain($udom);
11101:     return 'error: invalid domain' if ($domdesc eq '');
11102:     my $first;
11103:     if ($crstype eq 'Community') {
11104:         $first = '0';
11105:     } else {
11106:         $first = int(1+rand(9)); 
11107:     } 
11108:     my $uname=$first.
11109:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11110:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11111:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11112: # ----------------------------------------------- Make sure that does not exist
11113:     my $uhome=&homeserver($uname,$udom,'true');
11114:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11115:         if ($crstype eq 'Community') {
11116:             $first = '0';
11117:         } else {
11118:             $first = int(1+rand(9));
11119:         }
11120:         $uname=$first.
11121:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11122:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11123:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11124:         $uhome=&homeserver($uname,$udom,'true');
11125:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11126:             return 'error: unable to generate unique course-ID';
11127:         }
11128:     }
11129:     return $uname;
11130: }
11131: 
11132: sub is_course {
11133:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11134:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11135: 
11136:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11137:     my $uhome=&homeserver($cnum,$cdom);
11138:     my $iscourse;
11139:     if (grep { $_ eq $uhome } current_machine_ids()) {
11140:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11141:     } else {
11142:         my $hashid = $cdom.':'.$cnum;
11143:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11144:         unless (defined($cached)) {
11145:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11146:                                         $cnum,undef,undef,'.');
11147:             $iscourse = 0;
11148:             if (exists($courses{$cdom.'_'.$cnum})) {
11149:                 $iscourse = 1;
11150:             }
11151:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11152:         }
11153:     }
11154:     return unless ($iscourse);
11155:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11156: }
11157: 
11158: sub store_userdata {
11159:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11160:     my $result;
11161:     if ($datakey ne '') {
11162:         if (ref($storehash) eq 'HASH') {
11163:             if ($udom eq '' || $uname eq '') {
11164:                 $udom = $env{'user.domain'};
11165:                 $uname = $env{'user.name'};
11166:             }
11167:             my $uhome=&homeserver($uname,$udom);
11168:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11169:                 $result = 'error: no_host';
11170:             } else {
11171:                 $storehash->{'ip'} = &get_requestor_ip();
11172:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11173: 
11174:                 my $namevalue='';
11175:                 foreach my $key (keys(%{$storehash})) {
11176:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11177:                 }
11178:                 $namevalue=~s/\&$//;
11179:                 unless ($namespace eq 'courserequests') {
11180:                     $datakey = &escape($datakey);
11181:                 }
11182:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11183:                                   $namevalue,$uhome);
11184:             }
11185:         } else {
11186:             $result = 'error: data to store was not a hash reference'; 
11187:         }
11188:     } else {
11189:         $result= 'error: invalid requestkey'; 
11190:     }
11191:     return $result;
11192: }
11193: 
11194: # ---------------------------------------------------------- Assign Custom Role
11195: 
11196: sub assigncustomrole {
11197:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11198:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11199:                        $end,$start,$deleteflag,$selfenroll,$context);
11200: }
11201: 
11202: # ----------------------------------------------------------------- Revoke Role
11203: 
11204: sub revokerole {
11205:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11206:     my $now=time;
11207:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11208: }
11209: 
11210: # ---------------------------------------------------------- Revoke Custom Role
11211: 
11212: sub revokecustomrole {
11213:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11214:     my $now=time;
11215:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11216:            $deleteflag,$selfenroll,$context);
11217: }
11218: 
11219: # ------------------------------------------------------------ Disk usage
11220: sub diskusage {
11221:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11222:     $directorypath =~ s/\/$//;
11223:     my $listing=&reply('du2:'.&escape($directorypath).':'
11224:                        .&escape($getpropath).':'.&escape($uname).':'
11225:                        .&escape($udom),homeserver($uname,$udom));
11226:     if ($listing eq 'unknown_cmd') {
11227:         if ($getpropath) {
11228:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11229:         }
11230:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11231:     }
11232:     return $listing;
11233: }
11234: 
11235: sub is_locked {
11236:     my ($file_name, $domain, $user, $which) = @_;
11237:     my @check;
11238:     my $is_locked;
11239:     push (@check,$file_name);
11240:     my %locked = &get('file_permissions',\@check,
11241: 		      $env{'user.domain'},$env{'user.name'});
11242:     my ($tmp)=keys(%locked);
11243:     if ($tmp=~/^error:/) { undef(%locked); }
11244:     
11245:     if (ref($locked{$file_name}) eq 'ARRAY') {
11246:         $is_locked = 'false';
11247:         foreach my $entry (@{$locked{$file_name}}) {
11248:            if (ref($entry) eq 'ARRAY') {
11249:                $is_locked = 'true';
11250:                if (ref($which) eq 'ARRAY') {
11251:                    push(@{$which},$entry);
11252:                } else {
11253:                    last;
11254:                }
11255:            }
11256:        }
11257:     } else {
11258:         $is_locked = 'false';
11259:     }
11260:     return $is_locked;
11261: }
11262: 
11263: sub declutter_portfile {
11264:     my ($file) = @_;
11265:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11266:     return $file;
11267: }
11268: 
11269: # ------------------------------------------------------------- Mark as Read Only
11270: 
11271: sub mark_as_readonly {
11272:     my ($domain,$user,$files,$what) = @_;
11273:     my %current_permissions = &dump('file_permissions',$domain,$user);
11274:     my ($tmp)=keys(%current_permissions);
11275:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11276:     foreach my $file (@{$files}) {
11277: 	$file = &declutter_portfile($file);
11278:         push(@{$current_permissions{$file}},$what);
11279:     }
11280:     &put('file_permissions',\%current_permissions,$domain,$user);
11281:     return;
11282: }
11283: 
11284: # ------------------------------------------------------------Save Selected Files
11285: 
11286: sub save_selected_files {
11287:     my ($user, $path, @files) = @_;
11288:     my $filename = $user."savedfiles";
11289:     my @other_files = &files_not_in_path($user, $path);
11290:     open (OUT,'>',LONCAPA::tempdir().$filename);
11291:     foreach my $file (@files) {
11292:         print (OUT $env{'form.currentpath'}.$file."\n");
11293:     }
11294:     foreach my $file (@other_files) {
11295:         print (OUT $file."\n");
11296:     }
11297:     close (OUT);
11298:     return 'ok';
11299: }
11300: 
11301: sub clear_selected_files {
11302:     my ($user) = @_;
11303:     my $filename = $user."savedfiles";
11304:     open (OUT,'>',LONCAPA::tempdir().$filename);
11305:     print (OUT undef);
11306:     close (OUT);
11307:     return ("ok");    
11308: }
11309: 
11310: sub files_in_path {
11311:     my ($user, $path) = @_;
11312:     my $filename = $user."savedfiles";
11313:     my %return_files;
11314:     open (IN,'<',LONCAPA::tempdir().$filename);
11315:     while (my $line_in = <IN>) {
11316:         chomp ($line_in);
11317:         my @paths_and_file = split (m!/!, $line_in);
11318:         my $file_part = pop (@paths_and_file);
11319:         my $path_part = join ('/', @paths_and_file);
11320:         $path_part.='/';
11321:         my $path_and_file = $path_part.$file_part;
11322:         if ($path_part eq $path) {
11323:             $return_files{$file_part}= 'selected';
11324:         }
11325:     }
11326:     close (IN);
11327:     return (\%return_files);
11328: }
11329: 
11330: # called in portfolio select mode, to show files selected NOT in current directory
11331: sub files_not_in_path {
11332:     my ($user, $path) = @_;
11333:     my $filename = $user."savedfiles";
11334:     my @return_files;
11335:     my $path_part;
11336:     open(IN, '<',LONCAPA::tempdir().$filename);
11337:     while (my $line = <IN>) {
11338:         #ok, I know it's clunky, but I want it to work
11339:         my @paths_and_file = split(m|/|, $line);
11340:         my $file_part = pop(@paths_and_file);
11341:         chomp($file_part);
11342:         my $path_part = join('/', @paths_and_file);
11343:         $path_part .= '/';
11344:         my $path_and_file = $path_part.$file_part;
11345:         if ($path_part ne $path) {
11346:             push(@return_files, ($path_and_file));
11347:         }
11348:     }
11349:     close(OUT);
11350:     return (@return_files);
11351: }
11352: 
11353: #------------------------------Submitted/Handedback Portfolio Files Versioning
11354:  
11355: sub portfiles_versioning {
11356:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11357:     my $portfolio_root = '/userfiles/portfolio';
11358:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11359:     foreach my $file (@{$portfiles}) {
11360:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11361:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11362:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11363:         my $getpropath = 1;
11364:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11365:                                              $stu_name,$getpropath);
11366:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11367:         my $new_answer = 
11368:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11369:         if ($new_answer ne 'problem getting file') {
11370:             push(@{$versioned_portfiles}, $directory.$new_answer);
11371:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11372:                               [$symb,$env{'request.course.id'},'graded']);
11373:         }
11374:     }
11375: }
11376: 
11377: sub get_next_version {
11378:     my ($answer_name, $answer_ext, $dir_list) = @_;
11379:     my $version;
11380:     if (ref($dir_list) eq 'ARRAY') {
11381:         foreach my $row (@{$dir_list}) {
11382:             my ($file) = split(/\&/,$row,2);
11383:             my ($file_name,$file_version,$file_ext) =
11384:                 &file_name_version_ext($file);
11385:             if (($file_name eq $answer_name) &&
11386:                 ($file_ext eq $answer_ext)) {
11387:                      # gets here if filename and extension match,
11388:                      # regardless of version
11389:                 if ($file_version ne '') {
11390:                     # a versioned file is found  so save it for later
11391:                     if ($file_version > $version) {
11392:                         $version = $file_version;
11393:                     }
11394:                 }
11395:             }
11396:         }
11397:     }
11398:     $version ++;
11399:     return($version);
11400: }
11401: 
11402: sub version_selected_portfile {
11403:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11404:     my ($answer_name,$answer_ver,$answer_ext) =
11405:         &file_name_version_ext($file_name);
11406:     my $new_answer;
11407:     $env{'form.copy'} =
11408:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11409:     if($env{'form.copy'} eq '-1') {
11410:         $new_answer = 'problem getting file';
11411:     } else {
11412:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11413:         my $copy_result = 
11414:             &finishuserfileupload($stu_name,$domain,'copy',
11415:                                   '/portfolio'.$directory.$new_answer);
11416:     }
11417:     undef($env{'form.copy'});
11418:     return ($new_answer);
11419: }
11420: 
11421: sub file_name_version_ext {
11422:     my ($file)=@_;
11423:     my @file_parts = split(/\./, $file);
11424:     my ($name,$version,$ext);
11425:     if (@file_parts > 1) {
11426:         $ext=pop(@file_parts);
11427:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11428:             $version=pop(@file_parts);
11429:         }
11430:         $name=join('.',@file_parts);
11431:     } else {
11432:         $name=join('.',@file_parts);
11433:     }
11434:     return($name,$version,$ext);
11435: }
11436: 
11437: #----------------------------------------------Get portfolio file permissions
11438: 
11439: sub get_portfile_permissions {
11440:     my ($domain,$user) = @_;
11441:     my %current_permissions = &dump('file_permissions',$domain,$user);
11442:     my ($tmp)=keys(%current_permissions);
11443:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11444:     return \%current_permissions;
11445: }
11446: 
11447: #---------------------------------------------Get portfolio file access controls
11448: 
11449: sub get_access_controls {
11450:     my ($current_permissions,$group,$file) = @_;
11451:     my %access;
11452:     my $real_file = $file;
11453:     $file =~ s/\.meta$//;
11454:     if (defined($file)) {
11455:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11456:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11457:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11458:             }
11459:         }
11460:     } else {
11461:         foreach my $key (keys(%{$current_permissions})) {
11462:             if ($key =~ /\0accesscontrol$/) {
11463:                 if (defined($group)) {
11464:                     if ($key !~ m-^\Q$group\E/-) {
11465:                         next;
11466:                     }
11467:                 }
11468:                 my ($fullpath) = split(/\0/,$key);
11469:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11470:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11471:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11472:                     }
11473:                 }
11474:             }
11475:         }
11476:     }
11477:     return %access;
11478: }
11479: 
11480: sub modify_access_controls {
11481:     my ($file_name,$changes,$domain,$user)=@_;
11482:     my ($outcome,$deloutcome);
11483:     my %store_permissions;
11484:     my %new_values;
11485:     my %new_control;
11486:     my %translation;
11487:     my @deletions = ();
11488:     my $now = time;
11489:     if (exists($$changes{'activate'})) {
11490:         if (ref($$changes{'activate'}) eq 'HASH') {
11491:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11492:             my $numnew = scalar(@newitems);
11493:             for (my $i=0; $i<$numnew; $i++) {
11494:                 my $newkey = $newitems[$i];
11495:                 my $newid = &Apache::loncommon::get_cgi_id();
11496:                 if ($newkey =~ /^\d+:/) { 
11497:                     $newkey =~ s/^(\d+)/$newid/;
11498:                     $translation{$1} = $newid;
11499:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11500:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11501:                     $translation{$1} = $newid;
11502:                 }
11503:                 $new_values{$file_name."\0".$newkey} = 
11504:                                           $$changes{'activate'}{$newitems[$i]};
11505:                 $new_control{$newkey} = $now;
11506:             }
11507:         }
11508:     }
11509:     my %todelete;
11510:     my %changed_items;
11511:     foreach my $action ('delete','update') {
11512:         if (exists($$changes{$action})) {
11513:             if (ref($$changes{$action}) eq 'HASH') {
11514:                 foreach my $key (keys(%{$$changes{$action}})) {
11515:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11516:                     if ($action eq 'delete') { 
11517:                         $todelete{$itemnum} = 1;
11518:                     } else {
11519:                         $changed_items{$itemnum} = $key;
11520:                     }
11521:                 }
11522:             }
11523:         }
11524:     }
11525:     # get lock on access controls for file.
11526:     my $lockhash = {
11527:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11528:                                                        ':'.$env{'user.domain'},
11529:                    }; 
11530:     my $tries = 0;
11531:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11532:    
11533:     while (($gotlock ne 'ok') && $tries < 10) {
11534:         $tries ++;
11535:         sleep(0.1);
11536:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11537:     }
11538:     if ($gotlock eq 'ok') {
11539:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11540:         my ($tmp)=keys(%curr_permissions);
11541:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11542:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11543:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11544:             if (ref($curr_controls) eq 'HASH') {
11545:                 foreach my $control_item (keys(%{$curr_controls})) {
11546:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11547:                     if (defined($todelete{$itemnum})) {
11548:                         push(@deletions,$file_name."\0".$control_item);
11549:                     } else {
11550:                         if (defined($changed_items{$itemnum})) {
11551:                             $new_control{$changed_items{$itemnum}} = $now;
11552:                             push(@deletions,$file_name."\0".$control_item);
11553:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11554:                         } else {
11555:                             $new_control{$control_item} = $$curr_controls{$control_item};
11556:                         }
11557:                     }
11558:                 }
11559:             }
11560:         }
11561:         my ($group);
11562:         if (&is_course($domain,$user)) {
11563:             ($group,my $file) = split(/\//,$file_name,2);
11564:         }
11565:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11566:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11567:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11568:         #  remove lock
11569:         my @del_lock = ($file_name."\0".'locked_access_records');
11570:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11571:         my $sqlresult =
11572:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11573:                                     $group);
11574:     } else {
11575:         $outcome = "error: could not obtain lockfile\n";  
11576:     }
11577:     return ($outcome,$deloutcome,\%new_values,\%translation);
11578: }
11579: 
11580: sub make_public_indefinitely {
11581:     my (@requrl) = @_;
11582:     return &automated_portfile_access('public',\@requrl);
11583: }
11584: 
11585: sub automated_portfile_access {
11586:     my ($accesstype,$addsref,$delsref,$info) = @_;
11587:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11588:         return 'invalid';
11589:     }
11590:     my %urls;
11591:     if (ref($addsref) eq 'ARRAY') {
11592:         foreach my $requrl (@{$addsref}) {
11593:             if (&is_portfolio_url($requrl)) {
11594:                 unless (exists($urls{$requrl})) {
11595:                     $urls{$requrl} = 'add';
11596:                 }
11597:             }
11598:         }
11599:     }
11600:     if (ref($delsref) eq 'ARRAY') {
11601:         foreach my $requrl (@{$delsref}) { 
11602:             if (&is_portfolio_url($requrl)) {
11603:                 unless (exists($urls{$requrl})) {
11604:                     $urls{$requrl} = 'delete'; 
11605:                 }
11606:             }
11607:         }
11608:     }
11609:     unless (keys(%urls)) {
11610:         return 'invalid';
11611:     }
11612:     my $ip;
11613:     if ($accesstype eq 'ip') {
11614:         if (ref($info) eq 'HASH') {
11615:             if ($info->{'ip'} ne '') {
11616:                 $ip = $info->{'ip'};
11617:             }
11618:         }
11619:         if ($ip eq '') {
11620:             return 'invalid';
11621:         }
11622:     }
11623:     my $errors;
11624:     my $now = time;
11625:     my %current_perms;
11626:     foreach my $requrl (sort(keys(%urls))) {
11627:         my $action;
11628:         if ($urls{$requrl} eq 'add') {
11629:             $action = 'activate';
11630:         } else {
11631:             $action = 'none';
11632:         }
11633:         my $aclnum = 0;
11634:         my (undef,$udom,$unum,$file_name,$group) =
11635:             &parse_portfolio_url($requrl);
11636:         unless (exists($current_perms{$unum.':'.$udom})) {
11637:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11638:         }
11639:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11640:                                                    $group,$file_name);
11641:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11642:             my ($num,$scope,$end,$start) = 
11643:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11644:             if ($scope eq $accesstype) {
11645:                 if (($start <= $now) && ($end == 0)) {
11646:                     if ($accesstype eq 'ip') {
11647:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11648:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11649:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11650:                                     if ($urls{$requrl} eq 'add') {
11651:                                         $action = 'none';
11652:                                         last;
11653:                                     } else {
11654:                                         $action = 'delete';
11655:                                         $aclnum = $num;
11656:                                         last;
11657:                                     }
11658:                                 }
11659:                             }
11660:                         }
11661:                     } elsif ($accesstype eq 'public') {
11662:                         if ($urls{$requrl} eq 'add') {
11663:                             $action = 'none';
11664:                             last;
11665:                         } else {
11666:                             $action = 'delete';
11667:                             $aclnum = $num;
11668:                             last;
11669:                         }
11670:                     }
11671:                 } elsif ($accesstype eq 'public') {
11672:                     $action = 'update';
11673:                     $aclnum = $num;
11674:                     last;
11675:                 }
11676:             }
11677:         }
11678:         if ($action eq 'none') {
11679:             next;
11680:         } else {
11681:             my %changes;
11682:             my $newend = 0;
11683:             my $newstart = $now;
11684:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11685:             $changes{$action}{$newkey} = {
11686:                 type => $accesstype,
11687:                 time => {
11688:                     start => $newstart,
11689:                     end   => $newend,
11690:                 },
11691:             };
11692:             if ($accesstype eq 'ip') {
11693:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11694:             }
11695:             my ($outcome,$deloutcome,$new_values,$translation) =
11696:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11697:             unless ($outcome eq 'ok') {
11698:                 $errors .= $outcome.' ';
11699:             }
11700:         }
11701:     }
11702:     if ($errors) {
11703:         $errors =~ s/\s$//;
11704:         return $errors;
11705:     } else {
11706:         return 'ok';
11707:     }
11708: }
11709: 
11710: #------------------------------------------------------Get Marked as Read Only
11711: 
11712: sub get_marked_as_readonly {
11713:     my ($domain,$user,$what,$group) = @_;
11714:     my $current_permissions = &get_portfile_permissions($domain,$user);
11715:     my @readonly_files;
11716:     my $cmp1=$what;
11717:     if (ref($what)) { $cmp1=join('',@{$what}) };
11718:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11719:         if (defined($group)) {
11720:             if ($file_name !~ m-^\Q$group\E/-) {
11721:                 next;
11722:             }
11723:         }
11724:         if (ref($value) eq "ARRAY"){
11725:             foreach my $stored_what (@{$value}) {
11726:                 my $cmp2=$stored_what;
11727:                 if (ref($stored_what) eq 'ARRAY') {
11728:                     $cmp2=join('',@{$stored_what});
11729:                 }
11730:                 if ($cmp1 eq $cmp2) {
11731:                     push(@readonly_files, $file_name);
11732:                     last;
11733:                 } elsif (!defined($what)) {
11734:                     push(@readonly_files, $file_name);
11735:                     last;
11736:                 }
11737:             }
11738:         }
11739:     }
11740:     return @readonly_files;
11741: }
11742: #-----------------------------------------------------------Get Marked as Read Only Hash
11743: 
11744: sub get_marked_as_readonly_hash {
11745:     my ($current_permissions,$group,$what) = @_;
11746:     my %readonly_files;
11747:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11748:         if (defined($group)) {
11749:             if ($file_name !~ m-^\Q$group\E/-) {
11750:                 next;
11751:             }
11752:         }
11753:         if (ref($value) eq "ARRAY"){
11754:             foreach my $stored_what (@{$value}) {
11755:                 if (ref($stored_what) eq 'ARRAY') {
11756:                     foreach my $lock_descriptor(@{$stored_what}) {
11757:                         if ($lock_descriptor eq 'graded') {
11758:                             $readonly_files{$file_name} = 'graded';
11759:                         } elsif ($lock_descriptor eq 'handback') {
11760:                             $readonly_files{$file_name} = 'handback';
11761:                         } else {
11762:                             if (!exists($readonly_files{$file_name})) {
11763:                                 $readonly_files{$file_name} = 'locked';
11764:                             }
11765:                         }
11766:                     }
11767:                 } 
11768:             }
11769:         } 
11770:     }
11771:     return %readonly_files;
11772: }
11773: # ------------------------------------------------------------ Unmark as Read Only
11774: 
11775: sub unmark_as_readonly {
11776:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11777:     # for portfolio submissions, $what contains [$symb,$crsid] 
11778:     my ($domain,$user,$what,$file_name,$group) = @_;
11779:     $file_name = &declutter_portfile($file_name);
11780:     my $symb_crs = $what;
11781:     if (ref($what)) { $symb_crs=join('',@$what); }
11782:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11783:     my ($tmp)=keys(%current_permissions);
11784:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11785:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11786:     foreach my $file (@readonly_files) {
11787: 	my $clean_file = &declutter_portfile($file);
11788: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11789: 	my $current_locks = $current_permissions{$file};
11790:         my @new_locks;
11791:         my @del_keys;
11792:         if (ref($current_locks) eq "ARRAY"){
11793:             foreach my $locker (@{$current_locks}) {
11794:                 my $compare=$locker;
11795:                 if (ref($locker) eq 'ARRAY') {
11796:                     $compare=join('',@{$locker});
11797:                     if ($compare ne $symb_crs) {
11798:                         push(@new_locks, $locker);
11799:                     }
11800:                 }
11801:             }
11802:             if (scalar(@new_locks) > 0) {
11803:                 $current_permissions{$file} = \@new_locks;
11804:             } else {
11805:                 push(@del_keys, $file);
11806:                 &del('file_permissions',\@del_keys, $domain, $user);
11807:                 delete($current_permissions{$file});
11808:             }
11809:         }
11810:     }
11811:     &put('file_permissions',\%current_permissions,$domain,$user);
11812:     return;
11813: }
11814: 
11815: # ------------------------------------------------------------ Directory lister
11816: 
11817: sub dirlist {
11818:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11819:     $uri=~s/^\///;
11820:     $uri=~s/\/$//;
11821:     my ($udom, $uname);
11822:     if ($getuserdir) {
11823:         $udom = $userdomain;
11824:         $uname = $username;
11825:     } else {
11826:         (undef,$udom,$uname)=split(/\//,$uri);
11827:         if(defined($userdomain)) {
11828:             $udom = $userdomain;
11829:         }
11830:         if(defined($username)) {
11831:             $uname = $username;
11832:         }
11833:     }
11834:     my ($dirRoot,$listing,@listing_results);
11835: 
11836:     $dirRoot = $perlvar{'lonDocRoot'};
11837:     if (defined($getpropath)) {
11838:         $dirRoot = &propath($udom,$uname);
11839:         $dirRoot =~ s/\/$//;
11840:     } elsif (defined($getuserdir)) {
11841:         my $subdir=$uname.'__';
11842:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11843:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11844:                    ."/$udom/$subdir/$uname";
11845:     } elsif (defined($alternateRoot)) {
11846:         $dirRoot = $alternateRoot;
11847:     }
11848: 
11849:     if($udom) {
11850:         if($uname) {
11851:             my $uhome = &homeserver($uname,$udom);
11852:             if ($uhome eq 'no_host') {
11853:                 return ([],'no_host');
11854:             }
11855:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11856:                               .$getuserdir.':'.&escape($dirRoot)
11857:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11858:             if ($listing eq 'unknown_cmd') {
11859:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11860:             } else {
11861:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11862:             }
11863:             if ($listing eq 'unknown_cmd') {
11864:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11865:                 @listing_results = split(/:/,$listing);
11866:             } else {
11867:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11868:             }
11869:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11870:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11871:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11872:                 return ([],$listing);
11873:             } else {
11874:                 return (\@listing_results);
11875:             }
11876:         } elsif(!$alternateRoot) {
11877:             my (%allusers,%listerror);
11878: 	    my %servers = &get_servers($udom,'library');
11879:  	    foreach my $tryserver (keys(%servers)) {
11880:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11881:                                   &escape($udom),$tryserver);
11882:                 if ($listing eq 'unknown_cmd') {
11883: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11884: 				      $udom, $tryserver);
11885:                 } else {
11886:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11887:                 }
11888: 		if ($listing eq 'unknown_cmd') {
11889: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11890: 				      $udom, $tryserver);
11891: 		    @listing_results = split(/:/,$listing);
11892: 		} else {
11893: 		    @listing_results =
11894: 			map { &unescape($_); } split(/:/,$listing);
11895: 		}
11896:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11897:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11898:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11899:                     $listerror{$tryserver} = $listing;
11900:                 } else {
11901: 		    foreach my $line (@listing_results) {
11902: 			my ($entry) = split(/&/,$line,2);
11903: 			$allusers{$entry} = 1;
11904: 		    }
11905: 		}
11906:             }
11907:             my @alluserslist=();
11908:             foreach my $user (sort(keys(%allusers))) {
11909:                 push(@alluserslist,$user.'&user');
11910:             }
11911: 
11912:             if (!%listerror) {
11913:                 # no errors
11914:                 return (\@alluserslist);
11915:             } elsif (scalar(keys(%servers)) == 1) {
11916:                 # one library server, one error 
11917:                 my ($key) = keys(%listerror);
11918:                 return (\@alluserslist, $listerror{$key});
11919:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11920:                 # con_lost indicates that we might miss data from at least one
11921:                 # library server
11922:                 return (\@alluserslist, 'con_lost');
11923:             } else {
11924:                 # multiple library servers and no con_lost -> data should be
11925:                 # complete. 
11926:                 return (\@alluserslist);
11927:             }
11928: 
11929:         } else {
11930:             return ([],'missing username');
11931:         }
11932:     } elsif(!defined($getpropath)) {
11933:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11934:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11935:         return (\@all_domains);
11936:     } else {
11937:         return ([],'missing domain');
11938:     }
11939: }
11940: 
11941: # --------------------------------------------- GetFileTimestamp
11942: # This function utilizes dirlist and returns the date stamp for
11943: # when it was last modified.  It will also return an error of -1
11944: # if an error occurs
11945: 
11946: sub GetFileTimestamp {
11947:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11948:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11949:     $studentName   = &LONCAPA::clean_username($studentName);
11950:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11951:                                     undef,$getuserdir);
11952:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11953:         return -1;
11954:     }
11955:     if (ref($fileref) eq 'ARRAY') {
11956:         my @stats = split('&',$fileref->[0]);
11957:         # @stats contains first the filename, then the stat output
11958:         return $stats[10]; # so this is 10 instead of 9.
11959:     } else {
11960:         return -1;
11961:     }
11962: }
11963: 
11964: sub stat_file {
11965:     my ($uri) = @_;
11966:     $uri = &clutter_with_no_wrapper($uri);
11967: 
11968:     my ($udom,$uname,$file);
11969:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11970: 	($udom,$uname,$file) =
11971: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11972: 	$file = 'userfiles/'.$file;
11973:     }
11974:     if ($uri =~ m-^/res/-) {
11975: 	($udom,$uname) = 
11976: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11977: 	$file = $uri;
11978:     }
11979: 
11980:     if (!$udom || !$uname || !$file) {
11981: 	# unable to handle the uri
11982: 	return ();
11983:     }
11984:     my $getpropath;
11985:     if ($file =~ /^userfiles\//) {
11986:         $getpropath = 1;
11987:     }
11988:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11989:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11990:         return ();
11991:     } else {
11992:         if (ref($listref) eq 'ARRAY') {
11993:             my @stats = split('&',$listref->[0]);
11994: 	    shift(@stats); #filename is first
11995: 	    return @stats;
11996:         }
11997:     }
11998:     return ();
11999: }
12000: 
12001: # --------------------------------------------------------- recursedirs
12002: # Recursive function to traverse either a specific user's Authoring Space
12003: # or corresponding Published Resource Space, and populate the hash ref:
12004: # $dirhashref with URLs of all directories, and if $filehashref hash
12005: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12006: # or .rights files in resource space, and .meta, .save, .log, and .bak
12007: # files in Authoring Space.
12008: #
12009: # Inputs:
12010: #
12011: # $is_home - true if current server is home server for user's space
12012: # $context - either: priv, or res respectively for Authoring or Resource Space.
12013: # $docroot - Document root (i.e., /home/httpd/html
12014: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12015: # $relpath - Current path (relative to top level).
12016: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12017: # $filehashref - reference to hash to populate with URLs of files (Optional)
12018: #
12019: # Returns: nothing
12020: #
12021: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12022: #
12023: # Currently used by interface/londocs.pm to create linked select boxes for
12024: # directory and filename to import a Course "Author" resource into a course, and
12025: # also to create linked select boxes for Authoring Space and Directory to choose
12026: # save location for creation of a new "standard" problem from the Course Editor.
12027: #
12028: 
12029: sub recursedirs {
12030:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12031:     return unless (ref($dirhashref) eq 'HASH');
12032:     my $currpath = $docroot.$toppath;
12033:     if ($relpath) {
12034:         $currpath .= "/$relpath";
12035:     }
12036:     my $savefile;
12037:     if (ref($filehashref)) {
12038:         $savefile = 1;
12039:     }
12040:     if ($is_home) {
12041:         if (opendir(my $dirh,$currpath)) {
12042:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12043:                 next if ($item eq '');
12044:                 if (-d "$currpath/$item") {
12045:                     my $newpath;
12046:                     if ($relpath) {
12047:                         $newpath = "$relpath/$item";
12048:                     } else {
12049:                         $newpath = $item;
12050:                     }
12051:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12052:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12053:                 } elsif ($savefile) {
12054:                     if ($context eq 'priv') {
12055:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12056:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12057:                         }
12058:                     } else {
12059:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
12060:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12061:                         }
12062:                     }
12063:                 }
12064:             }
12065:             closedir($dirh);
12066:         }
12067:     } else {
12068:         my ($dirlistref,$listerror) =
12069:             &dirlist($toppath.$relpath);
12070:         my @dir_lines;
12071:         my $dirptr=16384;
12072:         if (ref($dirlistref) eq 'ARRAY') {
12073:             foreach my $dir_line (sort
12074:                               {
12075:                                   my ($afile)=split('&',$a,2);
12076:                                   my ($bfile)=split('&',$b,2);
12077:                                   return (lc($afile) cmp lc($bfile));
12078:                               } (@{$dirlistref})) {
12079:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12080:                     split(/\&/,$dir_line,16);
12081:                 $item =~ s/\s+$//;
12082:                 next if (($item =~ /^\.\.?$/) || ($obs));
12083:                 if ($dirptr&$testdir) {
12084:                     my $newpath;
12085:                     if ($relpath) {
12086:                         $newpath = "$relpath/$item";
12087:                     } else {
12088:                         $relpath = '/';
12089:                         $newpath = $item;
12090:                     }
12091:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12092:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12093:                 } elsif ($savefile) {
12094:                     if ($context eq 'priv') {
12095:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12096:                             $filehashref->{$relpath}{$item} = 1;
12097:                         }
12098:                     } else {
12099:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
12100:                             $filehashref->{$relpath}{$item} = 1;
12101:                         }
12102:                     }
12103:                 }
12104:             }
12105:         }
12106:     }
12107:     return;
12108: }
12109: 
12110: # -------------------------------------------------------- Value of a Condition
12111: 
12112: # gets the value of a specific preevaluated condition
12113: #    stored in the string  $env{user.state.<cid>}
12114: # or looks up a condition reference in the bighash and if if hasn't
12115: # already been evaluated recurses into docondval to get the value of
12116: # the condition, then memoizing it to 
12117: #   $env{user.state.<cid>.<condition>}
12118: sub directcondval {
12119:     my $number=shift;
12120:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12121: 	&Apache::lonuserstate::evalstate();
12122:     }
12123:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12124: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12125:     } elsif ($number =~ /^_/) {
12126: 	my $sub_condition;
12127: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12128: 		&GDBM_READER(),0640)) {
12129: 	    $sub_condition=$bighash{'conditions'.$number};
12130: 	    untie(%bighash);
12131: 	}
12132: 	my $value = &docondval($sub_condition);
12133: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12134: 	return $value;
12135:     }
12136:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12137:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12138:     } else {
12139:        return 2;
12140:     }
12141: }
12142: 
12143: # get the collection of conditions for this resource
12144: sub condval {
12145:     my $condidx=shift;
12146:     my $allpathcond='';
12147:     foreach my $cond (split(/\|/,$condidx)) {
12148: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12149: 	    $allpathcond.=
12150: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12151: 	}
12152:     }
12153:     $allpathcond=~s/\|$//;
12154:     return &docondval($allpathcond);
12155: }
12156: 
12157: #evaluates an expression of conditions
12158: sub docondval {
12159:     my ($allpathcond) = @_;
12160:     my $result=0;
12161:     if ($env{'request.course.id'}
12162: 	&& defined($allpathcond)) {
12163: 	my $operand='|';
12164: 	my @stack;
12165: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12166: 	    if ($chunk eq '(') {
12167: 		push @stack,($operand,$result);
12168: 	    } elsif ($chunk eq ')') {
12169: 		my $before=pop @stack;
12170: 		if (pop @stack eq '&') {
12171: 		    $result=$result>$before?$before:$result;
12172: 		} else {
12173: 		    $result=$result>$before?$result:$before;
12174: 		}
12175: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12176: 		$operand=$chunk;
12177: 	    } else {
12178: 		my $new=directcondval($chunk);
12179: 		if ($operand eq '&') {
12180: 		    $result=$result>$new?$new:$result;
12181: 		} else {
12182: 		    $result=$result>$new?$result:$new;
12183: 		}
12184: 	    }
12185: 	}
12186:     }
12187:     return $result;
12188: }
12189: 
12190: # ---------------------------------------------------- Devalidate courseresdata
12191: 
12192: sub devalidatecourseresdata {
12193:     my ($coursenum,$coursedomain)=@_;
12194:     my $hashid=$coursenum.':'.$coursedomain;
12195:     &devalidate_cache_new('courseres',$hashid);
12196: }
12197: 
12198: 
12199: # --------------------------------------------------- Course Resourcedata Query
12200: #
12201: #  Parameters:
12202: #      $coursenum    - Number of the course.
12203: #      $coursedomain - Domain at which the course was created.
12204: #  Returns:
12205: #     A hash of the course parameters along (I think) with timestamps
12206: #     and version info.
12207: 
12208: sub get_courseresdata {
12209:     my ($coursenum,$coursedomain)=@_;
12210:     my $coursehom=&homeserver($coursenum,$coursedomain);
12211:     my $hashid=$coursenum.':'.$coursedomain;
12212:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12213:     my %dumpreply;
12214:     unless (defined($cached)) {
12215: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12216: 	$result=\%dumpreply;
12217: 	my ($tmp) = keys(%dumpreply);
12218: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12219: 	    &do_cache_new('courseres',$hashid,$result,600);
12220: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12221: 	    return $tmp;
12222: 	} elsif ($tmp =~ /^(error)/) {
12223: 	    $result=undef;
12224: 	    &do_cache_new('courseres',$hashid,$result,600);
12225: 	}
12226:     }
12227:     return $result;
12228: }
12229: 
12230: sub devalidateuserresdata {
12231:     my ($uname,$udom)=@_;
12232:     my $hashid="$udom:$uname";
12233:     &devalidate_cache_new('userres',$hashid);
12234: }
12235: 
12236: sub get_userresdata {
12237:     my ($uname,$udom)=@_;
12238:     #most student don\'t have any data set, check if there is some data
12239:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12240: 
12241:     my $hashid="$udom:$uname";
12242:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12243:     if (!defined($cached)) {
12244: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12245: 	$result=\%resourcedata;
12246: 	&do_cache_new('userres',$hashid,$result,600);
12247:     }
12248:     my ($tmp)=keys(%$result);
12249:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12250: 	return $result;
12251:     }
12252:     #error 2 occurs when the .db doesn't exist
12253:     if ($tmp!~/error: 2 /) {
12254:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12255: 	    &logthis("<font color=\"blue\">WARNING:".
12256: 		     " Trying to get resource data for ".
12257: 		     $uname." at ".$udom.": ".
12258: 		     $tmp."</font>");
12259:         }
12260:     } elsif ($tmp=~/error: 2 /) {
12261: 	#&EXT_cache_set($udom,$uname);
12262: 	&do_cache_new('userres',$hashid,undef,600);
12263: 	undef($tmp); # not really an error so don't send it back
12264:     }
12265:     return $tmp;
12266: }
12267: #----------------------------------------------- resdata - return resource data
12268: #  Purpose:
12269: #    Return resource data for either users or for a course.
12270: #  Parameters:
12271: #     $name      - Course/user name.
12272: #     $domain    - Name of the domain the user/course is registered on.
12273: #     $type      - Type of thing $name is (must be 'course' or 'user')
12274: #     $mapp      - decluttered URL of enclosing map  
12275: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12276: #     $recurseup - Ref to array of map URLs, starting with map containing
12277: #                  $mapp up through hierarchy of nested maps to top level map.  
12278: #     $courseid  - CourseID (first part of param identifier).
12279: #     $modifier  - Middle part of param identifier.
12280: #     $what      - Last part of param identifier.
12281: #     @which     - Array of names of resources desired.
12282: #  Returns:
12283: #     The value of the first reasource in @which that is found in the
12284: #     resource hash.
12285: #  Exceptional Conditions:
12286: #     If the $type passed in is not valid (not the string 'course' or 
12287: #     'user', an undefined  reference is returned.
12288: #     If none of the resources are found, an undef is returned
12289: sub resdata {
12290:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12291:         $modifier,$what,@which)=@_;
12292:     my $result;
12293:     if ($type eq 'course') {
12294: 	$result=&get_courseresdata($name,$domain);
12295:     } elsif ($type eq 'user') {
12296: 	$result=&get_userresdata($name,$domain);
12297:     }
12298:     if (!ref($result)) { return $result; }    
12299:     foreach my $item (@which) {
12300:         if ($item->[1] eq 'course') {
12301:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12302:                 unless ($$recursed) {
12303:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12304:                     $$recursed = 1;
12305:                 }
12306:                 foreach my $item (@${recurseup}) {
12307:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12308:                     last if (defined($result->{$norecursechk}));
12309:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12310:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12311:                 }
12312:             }
12313:         }
12314:         if (defined($result->{$item->[0]})) {
12315: 	    return [$result->{$item->[0]},$item->[1]];
12316: 	}
12317:     }
12318:     return undef;
12319: }
12320: 
12321: sub get_domain_lti {
12322:     my ($cdom,$context) = @_;
12323:     my ($name,$cachename,%lti);
12324:     if ($context eq 'consumer') {
12325:         $name = 'ltitools';
12326:     } elsif ($context eq 'provider') {
12327:         $name = 'lti';
12328:     } elsif ($context eq 'linkprot') {
12329:         $name = 'ltisec';
12330:     } else {
12331:         return %lti;
12332:     }
12333: 
12334:     if ($context eq 'linkprot') {
12335:         $cachename = $context;
12336:     } else {
12337:         $cachename = $name;
12338:     }
12339:     
12340:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12341:     if (defined($cached)) {
12342:         if (ref($result) eq 'HASH') {
12343:             %lti = %{$result};
12344:         }
12345:     } else {
12346:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12347:         if (ref($domconfig{$name}) eq 'HASH') {
12348:             if ($context eq 'linkprot') {
12349:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12350:                     %lti = %{$domconfig{$name}{'linkprot'}};
12351:                 }
12352:             } else {
12353:                 %lti = %{$domconfig{$name}};
12354:             }
12355:             if (($context eq 'consumer') && (keys(%lti))) {
12356:                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12357:                 if (ref($encdomconfig{$name}) eq 'HASH') {
12358:                     foreach my $id (keys(%lti)) {
12359:                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12360:                             foreach my $item ('key','secret') {
12361:                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12362:                             }
12363:                         }
12364:                     }
12365:                 }
12366:             }
12367:         }
12368:         my $cachetime = 24*60*60;
12369:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12370:     }
12371:     return %lti;
12372: }
12373: 
12374: sub get_course_lti {
12375:     my ($cnum,$cdom) = @_;
12376:     my $hashid=$cdom.'_'.$cnum;
12377:     my %courselti;
12378:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
12379:     if (defined($cached)) {
12380:         if (ref($result) eq 'HASH') {
12381:             %courselti = %{$result};
12382:         }
12383:     } else {
12384:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12385:         my $cachetime = 24*60*60;
12386:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12387:     }
12388:     return %courselti;
12389: }
12390: 
12391: sub courselti_itemid {
12392:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12393:     my ($chome,$itemid);
12394:     $chome = &homeserver($cnum,$cdom);
12395:     return if ($chome eq 'no_host');
12396:     if (ref($params) eq 'HASH') {
12397:         my $items = &freeze_escape($params);
12398:         my $rep;
12399:         if (grep { $_ eq $chome } current_machine_ids()) {
12400:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12401:         } else {
12402:             my $escurl = &escape($url);
12403:             my $escmethod = &escape($method);
12404:             my $items = &freeze_escape($params);
12405:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12406:         }
12407:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12408:                 ($rep eq 'unknown_cmd')) {
12409:             $itemid = $rep;
12410:         }
12411:     }
12412:     return $itemid;
12413: }
12414: 
12415: sub domainlti_itemid {
12416:     my ($cdom,$url,$method,$params,$context) = @_;
12417:     my ($primary_id,$itemid);
12418:     $primary_id = &domain($cdom,'primary');
12419:     return if ($primary_id eq '');
12420:     if (ref($params) eq 'HASH') {
12421:         my $items = &freeze_escape($params);
12422:         my $rep;
12423:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12424:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12425:         } else {
12426:             my $cnum = '';
12427:             my $escurl = &escape($url);
12428:             my $escmethod = &escape($method);
12429:             my $items = &freeze_escape($params);
12430:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12431:         }
12432:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12433:                 ($rep eq 'unknown_cmd')) {
12434:             $itemid = $rep;
12435:         }
12436:     }
12437:     return $itemid;
12438: }
12439: 
12440: sub get_numsuppfiles {
12441:     my ($cnum,$cdom,$ignorecache)=@_;
12442:     my $hashid=$cnum.':'.$cdom;
12443:     my ($suppcount,$cached);
12444:     unless ($ignorecache) {
12445:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12446:     }
12447:     unless (defined($cached)) {
12448:         my $chome=&homeserver($cnum,$cdom);
12449:         unless ($chome eq 'no_host') {
12450:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12451:             my $suppmap = 'supplemental.sequence';
12452:             ($suppcount,$supptools,$errors) =
12453:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12454:                                                          $supptools,$errors);
12455:         }
12456:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12457:     }
12458:     return $suppcount;
12459: }
12460: 
12461: #
12462: # EXT resource caching routines
12463: #
12464: 
12465: {
12466: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12467: #
12468: # The course for which we cache
12469: my $cachedmapkey='';
12470: # The cached recursive maps for this course
12471: my %cachedmaps=();
12472: # When this was last done
12473: my $cachedmaptime='';
12474: 
12475: sub clear_EXT_cache_status {
12476:     &delenv('cache.EXT.');
12477: }
12478: 
12479: sub EXT_cache_status {
12480:     my ($target_domain,$target_user) = @_;
12481:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12482:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12483:         # We know already the user has no data
12484:         return 1;
12485:     } else {
12486:         return 0;
12487:     }
12488: }
12489: 
12490: sub EXT_cache_set {
12491:     my ($target_domain,$target_user) = @_;
12492:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12493:     #&appenv({$cachename => time});
12494: }
12495: 
12496: # --------------------------------------------------------- Value of a Variable
12497: sub EXT {
12498: 
12499:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12500:     unless ($varname) { return ''; }
12501:     #get real user name/domain, courseid and symb
12502:     my $courseid;
12503:     my $publicuser;
12504:     if ($symbparm) {
12505: 	$symbparm=&get_symb_from_alias($symbparm);
12506:     }
12507:     if (!($uname && $udom)) {
12508:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12509:       if (!$symbparm) {	$symbparm=$cursymb; }
12510:     } else {
12511: 	$courseid=$env{'request.course.id'};
12512:     }
12513:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12514:     my $rest;
12515:     if (defined($therest[0])) {
12516:        $rest=join('.',@therest);
12517:     } else {
12518:        $rest='';
12519:     }
12520: 
12521:     my $qualifierrest=$qualifier;
12522:     if ($rest) { $qualifierrest.='.'.$rest; }
12523:     my $spacequalifierrest=$space;
12524:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12525:     if ($realm eq 'user') {
12526: # --------------------------------------------------------------- user.resource
12527: 	if ($space eq 'resource') {
12528: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12529: 		  || defined($Apache::lonhomework::parsing_a_task))
12530: 		 &&
12531: 		 ($symbparm eq &symbread()) ) {
12532: 		# if we are in the middle of processing the resource the
12533: 		# get the value we are planning on committing
12534:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12535:                     return $Apache::lonhomework::results{$qualifierrest};
12536:                 } else {
12537:                     return $Apache::lonhomework::history{$qualifierrest};
12538:                 }
12539: 	    } else {
12540: 		my %restored;
12541: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12542: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12543: 		} else {
12544: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12545: 		}
12546: 		return $restored{$qualifierrest};
12547: 	    }
12548: # ----------------------------------------------------------------- user.access
12549:         } elsif ($space eq 'access') {
12550: 	    # FIXME - not supporting calls for a specific user
12551:             return &allowed($qualifier,$rest);
12552: # ------------------------------------------ user.preferences, user.environment
12553:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12554: 	    if (($uname eq $env{'user.name'}) &&
12555: 		($udom eq $env{'user.domain'})) {
12556: 		return $env{join('.',('environment',$qualifierrest))};
12557: 	    } else {
12558: 		my %returnhash;
12559: 		if (!$publicuser) {
12560: 		    %returnhash=&userenvironment($udom,$uname,
12561: 						 $qualifierrest);
12562: 		}
12563: 		return $returnhash{$qualifierrest};
12564: 	    }
12565: # ----------------------------------------------------------------- user.course
12566:         } elsif ($space eq 'course') {
12567: 	    # FIXME - not supporting calls for a specific user
12568:             return $env{join('.',('request.course',$qualifier))};
12569: # ------------------------------------------------------------------- user.role
12570:         } elsif ($space eq 'role') {
12571: 	    # FIXME - not supporting calls for a specific user
12572:             my ($role,$where)=split(/\./,$env{'request.role'});
12573:             if ($qualifier eq 'value') {
12574: 		return $role;
12575:             } elsif ($qualifier eq 'extent') {
12576:                 return $where;
12577:             }
12578: # ----------------------------------------------------------------- user.domain
12579:         } elsif ($space eq 'domain') {
12580:             return $udom;
12581: # ------------------------------------------------------------------- user.name
12582:         } elsif ($space eq 'name') {
12583:             return $uname;
12584: # ---------------------------------------------------- Any other user namespace
12585:         } else {
12586: 	    my %reply;
12587: 	    if (!$publicuser) {
12588: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12589: 	    }
12590: 	    return $reply{$qualifierrest};
12591:         }
12592:     } elsif ($realm eq 'query') {
12593: # ---------------------------------------------- pull stuff out of query string
12594:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12595: 						[$spacequalifierrest]);
12596: 	return $env{'form.'.$spacequalifierrest}; 
12597:    } elsif ($realm eq 'request') {
12598: # ------------------------------------------------------------- request.browser
12599:         if ($space eq 'browser') {
12600:             return $env{'browser.'.$qualifier};
12601: # ------------------------------------------------------------ request.filename
12602:         } else {
12603:             return $env{'request.'.$spacequalifierrest};
12604:         }
12605:     } elsif ($realm eq 'course') {
12606: # ---------------------------------------------------------- course.description
12607:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12608:     } elsif ($realm eq 'resource') {
12609: 
12610: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12611: 	    if (!$symbparm) { $symbparm=&symbread(); }
12612: 	}
12613: 
12614:         if ($qualifier eq '') {
12615: 	    if ($space eq 'title') {
12616: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12617: 	        return &gettitle($symbparm);
12618: 	    }
12619: 	
12620: 	    if ($space eq 'map') {
12621: 	        my ($map) = &decode_symb($symbparm);
12622: 	        return &symbread($map);
12623: 	    }
12624:             if ($space eq 'maptitle') {
12625:                 my ($map) = &decode_symb($symbparm);
12626:                 return &gettitle($map);
12627:             }
12628: 	    if ($space eq 'filename') {
12629: 	        if ($symbparm) {
12630: 		    return &clutter((&decode_symb($symbparm))[2]);
12631: 	        }
12632: 	        return &hreflocation('',$env{'request.filename'});
12633: 	    }
12634: 
12635:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12636:                 if ($space eq 'visibleparts') {
12637:                     my $navmap = Apache::lonnavmaps::navmap->new();
12638:                     my $item;
12639:                     if (ref($navmap)) {
12640:                         my $res = $navmap->getBySymb($symbparm);
12641:                         my $parts = $res->parts();
12642:                         if (ref($parts) eq 'ARRAY') {
12643:                             $item = join(',',@{$parts});
12644:                         }
12645:                         undef($navmap);
12646:                     }
12647:                     return $item;
12648:                 }
12649:             }
12650:         }
12651: 
12652: 	my ($section, $group, @groups, @recurseup, $recursed);
12653:         if (ref($recurseupref) eq 'ARRAY') {
12654:             @recurseup = @{$recurseupref};
12655:             $recursed = 1;
12656:         }
12657: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12658:         if (($courseid eq '') && ($cid)) {
12659:             $courseid = $cid;
12660:         }
12661: 	if (($symbparm && $courseid) && 
12662: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12663: 
12664: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12665: 
12666: # ----------------------------------------------------- Cascading lookup scheme
12667: 	    my $symbp=$symbparm;
12668: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12669: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12670:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12671: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12672: 	    if (($env{'user.name'} eq $uname) &&
12673: 		($env{'user.domain'} eq $udom)) {
12674: 		$section=$env{'request.course.sec'};
12675:                 @groups = split(/:/,$env{'request.course.groups'});  
12676:                 @groups=&sort_course_groups($courseid,@groups); 
12677: 	    } else {
12678: 		if (! defined($usection)) {
12679: 		    $section=&getsection($udom,$uname,$courseid);
12680: 		} else {
12681: 		    $section = $usection;
12682: 		}
12683:                 @groups = &get_users_groups($udom,$uname,$courseid);
12684: 	    }
12685: 
12686: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12687: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12688:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12689: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12690: 
12691: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12692: 	    my $courselevelr=$courseid.'.'.$symbparm;
12693:             $courseleveli=$courseid.'.'.$recurseparm;
12694: 	    $courselevelm=$courseid.'.'.$mapparm;
12695: 
12696: # ----------------------------------------------------------- first, check user
12697: 
12698: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12699:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12700: 				       ([$courselevelr,'resource'],
12701: 					[$courselevelm,'map'     ],
12702:                                         [$courseleveli,'map'     ],
12703: 					[$courselevel, 'course'  ]));
12704: 	    if (defined($userreply)) { return &get_reply($userreply); }
12705: 
12706: # ------------------------------------------------ second, check some of course
12707:             my $coursereply;
12708:             if (@groups > 0) {
12709:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12710:                                        $recurseparm,$mapparm,$spacequalifierrest,
12711:                                        $mapp,\$recursed,\@recurseup);
12712:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12713:             }
12714: 
12715: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12716: 				  $env{'course.'.$courseid.'.domain'},
12717: 				  'course',$mapp,\$recursed,\@recurseup,
12718:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12719: 				  ([$seclevelr,   'resource'],
12720: 				   [$seclevelm,   'map'     ],
12721:                                    [$secleveli,   'map'     ],
12722: 				   [$seclevel,    'course'  ],
12723: 				   [$courselevelr,'resource']));
12724: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12725: 
12726: # ------------------------------------------------------ third, check map parms
12727: 	    my %parmhash=();
12728: 	    my $thisparm='';
12729: 	    if (tie(%parmhash,'GDBM_File',
12730: 		    $env{'request.course.fn'}.'_parms.db',
12731: 		    &GDBM_READER(),0640)) {
12732: 		$thisparm=$parmhash{$symbparm};
12733: 		untie(%parmhash);
12734: 	    }
12735: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12736: 	}
12737: # ------------------------------------------ fourth, look in resource metadata
12738:  
12739:         my $what = $spacequalifierrest;
12740: 	$what=~s/\./\_/;
12741: 	my $filename;
12742: 	if (!$symbparm) { $symbparm=&symbread(); }
12743: 	if ($symbparm) {
12744: 	    $filename=(&decode_symb($symbparm))[2];
12745: 	} else {
12746: 	    $filename=$env{'request.filename'};
12747: 	}
12748:         my $toolsymb;
12749:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12750:             $toolsymb = $symbparm;
12751:         }
12752: 	my $metadata=&metadata($filename,$what,$toolsymb);
12753: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12754: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12755: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12756: 
12757: # ----------------------------------------------- fifth, look in rest of course
12758: 	if ($symbparm && defined($courseid) && 
12759: 	    $courseid eq $env{'request.course.id'}) {
12760: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12761: 				     $env{'course.'.$courseid.'.domain'},
12762: 				     'course',$mapp,\$recursed,\@recurseup,
12763:                                      $courseid,'.',$spacequalifierrest,
12764: 				     ([$courselevelm,'map'   ],
12765:                                       [$courseleveli,'map'   ],
12766: 				      [$courselevel, 'course']));
12767: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12768: 	}
12769: # ------------------------------------------------------------------ Cascade up
12770: 	unless ($space eq '0') {
12771: 	    my @parts=split(/_/,$space);
12772: 	    my $id=pop(@parts);
12773: 	    my $part=join('_',@parts);
12774: 	    if ($part eq '') { $part='0'; }
12775: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12776: 				 $symbparm,$udom,$uname,$section,1);
12777: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12778: 	}
12779: 	if ($recurse) { return undef; }
12780: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12781: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12782: # ---------------------------------------------------- Any other user namespace
12783:     } elsif ($realm eq 'environment') {
12784: # ----------------------------------------------------------------- environment
12785: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12786: 	    return $env{'environment.'.$spacequalifierrest};
12787: 	} else {
12788: 	    if ($uname eq 'anonymous' && $udom eq '') {
12789: 		return '';
12790: 	    }
12791: 	    my %returnhash=&userenvironment($udom,$uname,
12792: 					    $spacequalifierrest);
12793: 	    return $returnhash{$spacequalifierrest};
12794: 	}
12795:     } elsif ($realm eq 'system') {
12796: # ----------------------------------------------------------------- system.time
12797: 	if ($space eq 'time') {
12798: 	    return time;
12799:         }
12800:     } elsif ($realm eq 'server') {
12801: # ----------------------------------------------------------------- system.time
12802: 	if ($space eq 'name') {
12803: 	    return $ENV{'SERVER_NAME'};
12804:         }
12805:     } elsif ($realm eq 'client') {
12806:         if ($space eq 'remote_addr') {
12807:             return &get_requestor_ip();
12808:         }
12809:     }
12810:     return '';
12811: }
12812: 
12813: sub get_reply {
12814:     my ($reply_value) = @_;
12815:     if (ref($reply_value) eq 'ARRAY') {
12816:         if (wantarray) {
12817: 	    return @$reply_value;
12818:         }
12819:         return $reply_value->[0];
12820:     } else {
12821:         return $reply_value;
12822:     }
12823: }
12824: 
12825: sub check_group_parms {
12826:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12827:         $recursed,$recurseupref) = @_;
12828:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12829:                   [$what,'course']);
12830:     my $coursereply;
12831:     foreach my $group (@{$groups}) {
12832:         my @groupitems = ();
12833:         foreach my $level (@levels) {
12834:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12835:              push(@groupitems,[$item,$level->[1]]);
12836:         }
12837:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12838:                                    $env{'course.'.$courseid.'.domain'},
12839:                                    'course',$mapp,$recursed,$recurseupref,
12840:                                    $courseid,'.['.$group.'].',$what,
12841:                                    @groupitems);
12842:         last if (defined($coursereply));
12843:     }
12844:     return $coursereply;
12845: }
12846: 
12847: sub get_map_hierarchy {
12848:     my ($mapname,$courseid) = @_;
12849:     my @recurseup = ();
12850:     if ($mapname) {
12851:         if (($cachedmapkey eq $courseid) &&
12852:             (abs($cachedmaptime-time)<5)) {
12853:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12854:                 return @{$cachedmaps{$mapname}};
12855:             }
12856:         }
12857:         my $navmap = Apache::lonnavmaps::navmap->new();
12858:         if (ref($navmap)) {
12859:             @recurseup = $navmap->recurseup_maps($mapname);
12860:             undef($navmap);
12861:             $cachedmaps{$mapname} = \@recurseup;
12862:             $cachedmaptime=time;
12863:             $cachedmapkey=$courseid;
12864:         }
12865:     }
12866:     return @recurseup;
12867: }
12868: 
12869: }
12870: 
12871: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12872:     my ($courseid,@groups) = @_;
12873:     @groups = sort(@groups);
12874:     return @groups;
12875: }
12876: 
12877: sub packages_tab_default {
12878:     my ($uri,$varname,$toolsymb)=@_;
12879:     my (undef,$part,$name)=split(/\./,$varname);
12880: 
12881:     my (@extension,@specifics,$do_default);
12882:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12883: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12884: 	if ($pack_type eq 'default') {
12885: 	    $do_default=1;
12886: 	} elsif ($pack_type eq 'extension') {
12887: 	    push(@extension,[$package,$pack_type,$pack_part]);
12888: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12889: 	    # only look at packages defaults for packages that this id is
12890: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12891: 	}
12892:     }
12893:     # first look for a package that matches the requested part id
12894:     foreach my $package (@specifics) {
12895: 	my (undef,$pack_type,$pack_part)=@{$package};
12896: 	next if ($pack_part ne $part);
12897: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12898: 	    return $packagetab{"$pack_type&$name&default"};
12899: 	}
12900:     }
12901:     # look for any possible matching non extension_ package
12902:     foreach my $package (@specifics) {
12903: 	my (undef,$pack_type,$pack_part)=@{$package};
12904: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12905: 	    return $packagetab{"$pack_type&$name&default"};
12906: 	}
12907: 	if ($pack_type eq 'part') { $pack_part='0'; }
12908: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12909: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12910: 	}
12911:     }
12912:     # look for any posible extension_ match
12913:     foreach my $package (@extension) {
12914: 	my ($package,$pack_type)=@{$package};
12915: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12916: 	    return $packagetab{"$pack_type&$name&default"};
12917: 	}
12918: 	if (defined($packagetab{$package."&$name&default"})) {
12919: 	    return $packagetab{$package."&$name&default"};
12920: 	}
12921:     }
12922:     # look for a global default setting
12923:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12924: 	return $packagetab{"default&$name&default"};
12925:     }
12926:     return undef;
12927: }
12928: 
12929: sub add_prefix_and_part {
12930:     my ($prefix,$part)=@_;
12931:     my $keyroot;
12932:     if (defined($prefix) && $prefix !~ /^__/) {
12933: 	# prefix that has a part already
12934: 	$keyroot=$prefix;
12935:     } elsif (defined($prefix)) {
12936: 	# prefix that is missing a part
12937: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12938:     } else {
12939: 	# no prefix at all
12940: 	if (defined($part)) { $keyroot='_'.$part; }
12941:     }
12942:     return $keyroot;
12943: }
12944: 
12945: # ---------------------------------------------------------------- Get metadata
12946: 
12947: my %metaentry;
12948: my %importedpartids;
12949: my %importedrespids;
12950: sub metadata {
12951:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12952:     $uri=&declutter($uri);
12953:     # if it is a non metadata possible uri return quickly
12954:     if (($uri eq '') || 
12955: 	(($uri =~ m|^/*adm/|) && 
12956: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12957:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12958: 	return undef;
12959:     }
12960:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12961: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12962: 	return undef;
12963:     }
12964:     my $filename=$uri;
12965:     $uri=~s/\.meta$//;
12966: #
12967: # Is the metadata already cached?
12968: # Look at timestamp of caching
12969: # Everything is cached by the main uri, libraries are never directly cached
12970: #
12971:     if (!defined($liburi)) {
12972: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12973: 	if (defined($cached)) { return $result->{':'.$what}; }
12974:     }
12975: 
12976: #
12977: # If the uri is for an external tool the file from
12978: # which metadata should be retrieved depends on whether
12979: # the tool had been configured to be gradable (set in the Course
12980: # Editor or Resource Editor).
12981: #
12982: # If a valid symb has been included as the third arg in the call
12983: # to &metadata() that can be used to retrieve the value of
12984: # parameter_0_gradable set for the resource, and included in the
12985: # uploaded map containing the tool. The value is retrieved via
12986: # &EXT(), if a valid symb is available.  Otherwise the value of
12987: # gradable in the exttool_$marker.db file for the tool instance
12988: # is retrieved via &get().
12989: #
12990: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12991: # hiddenresource and encrypturl (during course initialization)
12992: # the map-level parameter for resource.0.gradable included in the 
12993: # uploaded map containing the tool will not yet have been stored
12994: # in the user_course_parms.db file for the user's session, so in 
12995: # this case fall back to retrieving gradable status from the
12996: # exttool_$marker.db file.
12997: #
12998: # In order to avoid an infinite loop, &metadata() will return
12999: # before a call to &EXT(), if the uri is for an external tool
13000: # and the $what for which metadata is being requested is
13001: # parameter_0_gradable or 0_gradable.
13002: #
13003: 
13004:     if ($uri =~ /ext\.tool$/) {
13005:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13006:             return;
13007:         } else {
13008:             my ($checked,$use_passback);
13009:             if ($toolsymb ne '') {
13010:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13011:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13012:                     $checked = 1;
13013:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13014:                         $use_passback = 1;
13015:                     }
13016:                 }
13017:             }
13018:             unless ($checked) {
13019:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13020:                 $marker=~s/\D//g;
13021:                 if ($marker) {
13022:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13023:                     $use_passback = $toolsettings{'gradable'};
13024:                 }
13025:             }
13026:             if ($use_passback) {
13027:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13028:             } else {
13029:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13030:             }
13031:         }
13032:     }
13033: 
13034:     {
13035: # Imported parts would go here
13036:         my @origfiletagids=();
13037:         my $importedparts=0;
13038: 
13039: # Imported responseids would go here
13040:         my $importedresponses=0;
13041: #
13042: # Is this a recursive call for a library?
13043: #
13044: #	if (! exists($metacache{$uri})) {
13045: #	    $metacache{$uri}={};
13046: #	}
13047: 	my $cachetime = 60*60;
13048:         if ($liburi) {
13049: 	    $liburi=&declutter($liburi);
13050:             $filename=$liburi;
13051:         } else {
13052: 	    &devalidate_cache_new('meta',$uri);
13053: 	    undef(%metaentry);
13054: 	}
13055:         my %metathesekeys=();
13056:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13057: 	my $metastring;
13058: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13059: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13060: 	    $metastring = 
13061: 		&Apache::lonnet::ssi_body($which,
13062: 					  ('grade_target' => 'meta'));
13063: 	    $cachetime = 1; # only want this cached in the child not long term
13064: 	} elsif (($uri !~ m -^(editupload)/-) && 
13065:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13066: 	    my $file=&filelocation('',&clutter($filename));
13067: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13068: 	    $metastring=&getfile($file);
13069: 	}
13070:         my $parser=HTML::LCParser->new(\$metastring);
13071:         my $token;
13072:         undef %metathesekeys;
13073:         while ($token=$parser->get_token) {
13074: 	    if ($token->[0] eq 'S') {
13075: 		if (defined($token->[2]->{'package'})) {
13076: #
13077: # This is a package - get package info
13078: #
13079: 		    my $package=$token->[2]->{'package'};
13080: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13081: 		    if (defined($token->[2]->{'id'})) { 
13082: 			$keyroot.='_'.$token->[2]->{'id'}; 
13083: 		    }
13084: 		    if ($metaentry{':packages'}) {
13085: 			$metaentry{':packages'}.=','.$package.$keyroot;
13086: 		    } else {
13087: 			$metaentry{':packages'}=$package.$keyroot;
13088: 		    }
13089: 		    foreach my $pack_entry (keys(%packagetab)) {
13090: 			my $part=$keyroot;
13091: 			$part=~s/^\_//;
13092: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13093: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13094: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13095: 			    # ignore package.tab specified default values
13096:                             # here &package_tab_default() will fetch those
13097: 			    if ($subp eq 'default') { next; }
13098: 			    my $value=$packagetab{$pack_entry};
13099: 			    my $unikey;
13100: 			    if ($pack =~ /_0$/) {
13101: 				$unikey='parameter_0_'.$name;
13102: 				$part=0;
13103: 			    } else {
13104: 				$unikey='parameter'.$keyroot.'_'.$name;
13105: 			    }
13106: 			    if ($subp eq 'display') {
13107: 				$value.=' [Part: '.$part.']';
13108: 			    }
13109: 			    $metaentry{':'.$unikey.'.part'}=$part;
13110: 			    $metathesekeys{$unikey}=1;
13111: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13112: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13113: 			    }
13114: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13115: 				$metaentry{':'.$unikey}=
13116: 				    $metaentry{':'.$unikey.'.default'};
13117: 			    }
13118: 			}
13119: 		    }
13120: 		} else {
13121: #
13122: # This is not a package - some other kind of start tag
13123: #
13124: 		    my $entry=$token->[1];
13125: 		    my $unikey='';
13126: 
13127: 		    if ($entry eq 'import') {
13128: #
13129: # Importing a library here
13130: #
13131:                         my $location=$parser->get_text('/import');
13132:                         my $dir=$filename;
13133:                         $dir=~s|[^/]*$||;
13134:                         $location=&filelocation($dir,$location);
13135: 
13136:                         my $importid=$token->[2]->{'id'};
13137:                         my $importmode=$token->[2]->{'importmode'};
13138: #
13139: # Check metadata for imported file to
13140: # see if it contained response items
13141: #
13142:                         my ($origfile,@libfilekeys);
13143:                         my %currmetaentry = %metaentry;
13144:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13145:                                                            $depthcount+1));
13146:                         if (grep(/^responseorder$/,@libfilekeys)) {
13147:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13148:                                                              undef,$depthcount+1);
13149:                             if ($libresponseorder ne '') {
13150:                                 if ($#origfiletagids<0) {
13151:                                     undef(%importedrespids);
13152:                                     undef(%importedpartids);
13153:                                 }
13154:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13155:                                 if (@respids) {
13156:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13157:                                 }
13158:                                 if ($importedrespids{$importid} ne '') {
13159:                                     $importedresponses = 1;
13160: # We need to get the original file and the imported file to get the response order correct
13161: # Load and inspect original file
13162:                                     if ($#origfiletagids<0) {
13163:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13164:                                         $origfile=&getfile($origfilelocation);
13165:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13166:                                     }
13167:                                 }
13168:                             }
13169:                         }
13170: # Do not overwrite contents of %metaentry hash for resource itself with 
13171: # hash populated for imported library file
13172:                         %metaentry = %currmetaentry;
13173:                         undef(%currmetaentry);
13174:                         if ($importmode eq 'part') {
13175: # Import as part(s)
13176:                            $importedparts=1;
13177: # We need to get the original file and the imported file to get the part order correct
13178: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13179: # Load and inspect original file if we didn't do that already
13180:                            if ($#origfiletagids<0) {
13181:                                undef(%importedrespids);
13182:                                undef(%importedpartids);
13183:                                if ($origfile eq '') {
13184:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13185:                                    $origfile=&getfile($origfilelocation);
13186:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13187:                                }
13188:                            }
13189:                            my @impfilepartids;
13190: # If <partorder> tag is included in metadata for the imported file
13191: # get the parts in the imported file from that.
13192:                            if (grep(/^partorder$/,@libfilekeys)) {
13193:                                %currmetaentry = %metaentry;
13194:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13195:                                                             $depthcount+1);
13196:                                %metaentry = %currmetaentry;
13197:                                undef(%currmetaentry);
13198:                                if ($libpartorder ne '') {
13199:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13200:                                }
13201:                            } else {
13202: # If no <partorder> tag available, load and inspect imported file
13203:                                my $impfile=&getfile($location);
13204:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13205:                            }
13206:                            if ($#impfilepartids>=0) {
13207: # This problem had parts
13208:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13209:                            } else {
13210: # Importing by turning a single problem into a problem part
13211: # It gets the import-tags ID as part-ID
13212:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13213:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13214:                            }
13215:                         } else {
13216: # Import as problem or as normal import
13217:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13218:                             unless ($importmode eq 'problem') {
13219: # Normal import
13220:                                 if (defined($token->[2]->{'id'})) {
13221:                                     $unikey.='_'.$token->[2]->{'id'};
13222:                                 }
13223:                             }
13224: # Check metadata for imported file to
13225: # see if it contained parts
13226:                             if (grep(/^partorder$/,@libfilekeys)) {
13227:                                 %currmetaentry = %metaentry;
13228:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13229:                                                              $depthcount+1);
13230:                                 %metaentry = %currmetaentry;
13231:                                 undef(%currmetaentry);
13232:                                 if ($libpartorder ne '') {
13233:                                     $importedparts = 1;
13234:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13235:                                 }
13236:                             }
13237:                         }
13238: 			if ($depthcount<20) {
13239: 			    my $metadata = 
13240: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13241: 					  $depthcount+1);
13242: 			    foreach my $meta (split(',',$metadata)) {
13243: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13244: 				$metathesekeys{$meta}=1;
13245: 			    }
13246:                         }
13247: 		    } else {
13248: #
13249: # Not importing, some other kind of non-package, non-library start tag
13250: # 
13251:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13252:                         if (defined($token->[2]->{'id'})) {
13253:                             $unikey.='_'.$token->[2]->{'id'};
13254:                         }
13255: 			if (defined($token->[2]->{'name'})) { 
13256: 			    $unikey.='_'.$token->[2]->{'name'}; 
13257: 			}
13258: 			$metathesekeys{$unikey}=1;
13259: 			foreach my $param (@{$token->[3]}) {
13260: 			    $metaentry{':'.$unikey.'.'.$param} =
13261: 				$token->[2]->{$param};
13262: 			}
13263: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13264: 			my $default=$metaentry{':'.$unikey.'.default'};
13265: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13266: 		 # only ws inside the tag, and not in default, so use default
13267: 		 # as value
13268: 			    $metaentry{':'.$unikey}=$default;
13269: 			} elsif ( $internaltext =~ /\S/ ) {
13270: 		  # something interesting inside the tag
13271: 			    $metaentry{':'.$unikey}=$internaltext;
13272: 			} else {
13273: 		  # no interesting values, don't set a default
13274: 			}
13275: # end of not-a-package not-a-library import
13276: 		    }
13277: # end of not-a-package start tag
13278: 		}
13279: # the next is the end of "start tag"
13280: 	    }
13281: 	}
13282: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13283: 	$extension = lc($extension);
13284: 	if ($extension eq 'htm') { $extension='html'; }
13285: 
13286: 	foreach my $key (keys(%packagetab)) {
13287: 	    #no specific packages #how's our extension
13288: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13289: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13290: 					 \%metathesekeys);
13291: 	}
13292: 
13293: 	if (!exists($metaentry{':packages'})
13294: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13295: 	    foreach my $key (keys(%packagetab)) {
13296: 		#no specific packages well let's get default then
13297: 		if ($key!~/^default&/) { next; }
13298: 		&metadata_create_package_def($uri,$key,'default',
13299: 					     \%metathesekeys);
13300: 	    }
13301: 	}
13302: # are there custom rights to evaluate
13303: 	if ($metaentry{':copyright'} eq 'custom') {
13304: 
13305:     #
13306:     # Importing a rights file here
13307:     #
13308: 	    unless ($depthcount) {
13309: 		my $location=$metaentry{':customdistributionfile'};
13310: 		my $dir=$filename;
13311: 		$dir=~s|[^/]*$||;
13312: 		$location=&filelocation($dir,$location);
13313: 		my $rights_metadata =
13314: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13315: 			      $depthcount+1);
13316: 		foreach my $rights (split(',',$rights_metadata)) {
13317: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13318: 		    $metathesekeys{$rights}=1;
13319: 		}
13320: 	    }
13321: 	}
13322: 	# uniqifiy package listing
13323: 	my %seen;
13324: 	my @uniq_packages =
13325: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13326: 	$metaentry{':packages'} = join(',',@uniq_packages);
13327: 
13328:         if (($importedresponses) || ($importedparts)) {
13329:             if ($importedparts) {
13330: # We had imported parts and need to rebuild partorder
13331:                 $metaentry{':partorder'}='';
13332:                 $metathesekeys{'partorder'}=1;
13333:             }
13334:             if ($importedresponses) {
13335: # We had imported responses and need to rebuil responseorder
13336:                 $metaentry{':responseorder'}='';
13337:                 $metathesekeys{'responseorder'}=1;
13338:             }
13339:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13340:                 my $origid = $origfiletagids[$index+1];
13341:                 if ($origfiletagids[$index] eq 'part') {
13342: # Original part, part of the problem
13343:                     if ($importedparts) {
13344:                         $metaentry{':partorder'}.=','.$origid;
13345:                     }
13346:                 } elsif ($origfiletagids[$index] eq 'import') {
13347:                     if ($importedparts) {
13348: # We have imported parts at this position
13349:                         if ($importedpartids{$origid} ne '') {
13350:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13351:                         }
13352:                     }
13353:                     if ($importedresponses) {
13354: # We have imported responses at this position
13355:                         if ($importedrespids{$origid} ne '') {
13356:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13357:                         }
13358:                     }
13359:                 } else {
13360: # Original response item, part of the problem
13361:                     if ($importedresponses) {
13362:                         $metaentry{':responseorder'}.=','.$origid;
13363:                     }
13364:                 }
13365:             }
13366:             if ($importedparts) {
13367:                 $metaentry{':partorder'}=~s/^\,//;
13368:             }
13369:             if ($importedresponses) {
13370:                 $metaentry{':responseorder'}=~s/^\,//;
13371:             }
13372:         }
13373: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13374: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13375: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13376:         unless ($liburi) {
13377: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13378:         }
13379: # this is the end of "was not already recently cached
13380:     }
13381:     return $metaentry{':'.$what};
13382: }
13383: 
13384: sub metadata_create_package_def {
13385:     my ($uri,$key,$package,$metathesekeys)=@_;
13386:     my ($pack,$name,$subp)=split(/\&/,$key);
13387:     if ($subp eq 'default') { next; }
13388:     
13389:     if (defined($metaentry{':packages'})) {
13390: 	$metaentry{':packages'}.=','.$package;
13391:     } else {
13392: 	$metaentry{':packages'}=$package;
13393:     }
13394:     my $value=$packagetab{$key};
13395:     my $unikey;
13396:     $unikey='parameter_0_'.$name;
13397:     $metaentry{':'.$unikey.'.part'}=0;
13398:     $$metathesekeys{$unikey}=1;
13399:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13400: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13401:     }
13402:     if (defined($metaentry{':'.$unikey.'.default'})) {
13403: 	$metaentry{':'.$unikey}=
13404: 	    $metaentry{':'.$unikey.'.default'};
13405:     }
13406: }
13407: 
13408: sub metadata_generate_part0 {
13409:     my ($metadata,$metacache,$uri) = @_;
13410:     my %allnames;
13411:     foreach my $metakey (keys(%$metadata)) {
13412: 	if ($metakey=~/^parameter\_(.*)/) {
13413: 	  my $part=$$metacache{':'.$metakey.'.part'};
13414: 	  my $name=$$metacache{':'.$metakey.'.name'};
13415: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13416: 	    $allnames{$name}=$part;
13417: 	  }
13418: 	}
13419:     }
13420:     foreach my $name (keys(%allnames)) {
13421:       $$metadata{"parameter_0_$name"}=1;
13422:       my $key=":parameter_0_$name";
13423:       $$metacache{"$key.part"}='0';
13424:       $$metacache{"$key.name"}=$name;
13425:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13426: 					   $allnames{$name}.'_'.$name.
13427: 					   '.type'};
13428:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13429: 			     '.display'};
13430:       my $expr='[Part: '.$allnames{$name}.']';
13431:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13432:       $$metacache{"$key.display"}=$olddis;
13433:     }
13434: }
13435: 
13436: # ------------------------------------------------------ Devalidate title cache
13437: 
13438: sub devalidate_title_cache {
13439:     my ($url)=@_;
13440:     if (!$env{'request.course.id'}) { return; }
13441:     my $symb=&symbread($url);
13442:     if (!$symb) { return; }
13443:     my $key=$env{'request.course.id'}."\0".$symb;
13444:     &devalidate_cache_new('title',$key);
13445: }
13446: 
13447: # ------------------------------------------------- Get the title of a course
13448: 
13449: sub current_course_title {
13450:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13451: }
13452: # ------------------------------------------------- Get the title of a resource
13453: 
13454: sub gettitle {
13455:     my $urlsymb=shift;
13456:     my $symb=&symbread($urlsymb);
13457:     if ($symb) {
13458: 	my $key=$env{'request.course.id'}."\0".$symb;
13459: 	my ($result,$cached)=&is_cached_new('title',$key);
13460: 	if (defined($cached)) { 
13461: 	    return $result;
13462: 	}
13463: 	my ($map,$resid,$url)=&decode_symb($symb);
13464: 	my $title='';
13465: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13466: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13467: 	} else {
13468: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13469: 		    &GDBM_READER(),0640)) {
13470: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13471: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13472: 		untie(%bighash);
13473: 	    }
13474: 	}
13475: 	$title=~s/\&colon\;/\:/gs;
13476: 	if ($title) {
13477: # Remember both $symb and $title for dynamic metadata
13478:             $accesshash{$symb.'___crstitle'}=$title;
13479:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13480: # Cache this title and then return it
13481: 	    return &do_cache_new('title',$key,$title,600);
13482: 	}
13483: 	$urlsymb=$url;
13484:     }
13485:     my $title=&metadata($urlsymb,'title');
13486:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13487:     return $title;
13488: }
13489: 
13490: sub get_slot {
13491:     my ($which,$cnum,$cdom)=@_;
13492:     if (!$cnum || !$cdom) {
13493: 	(undef,my $courseid)=&whichuser();
13494: 	$cdom=$env{'course.'.$courseid.'.domain'};
13495: 	$cnum=$env{'course.'.$courseid.'.num'};
13496:     }
13497:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13498:     my %slotinfo;
13499:     if (exists($remembered{$key})) {
13500: 	$slotinfo{$which} = $remembered{$key};
13501:     } else {
13502: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13503: 	&Apache::lonhomework::showhash(%slotinfo);
13504: 	my ($tmp)=keys(%slotinfo);
13505: 	if ($tmp=~/^error:/) { return (); }
13506: 	$remembered{$key} = $slotinfo{$which};
13507:     }
13508:     if (ref($slotinfo{$which}) eq 'HASH') {
13509: 	return %{$slotinfo{$which}};
13510:     }
13511:     return $slotinfo{$which};
13512: }
13513: 
13514: sub get_reservable_slots {
13515:     my ($cnum,$cdom,$uname,$udom) = @_;
13516:     my $now = time;
13517:     my $reservable_info;
13518:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13519:     if (exists($remembered{$key})) {
13520:         $reservable_info = $remembered{$key};
13521:     } else {
13522:         my %resv;
13523:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13524:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13525:         $reservable_info = \%resv;
13526:         $remembered{$key} = $reservable_info;
13527:     }
13528:     return $reservable_info;
13529: }
13530: 
13531: sub get_course_slots {
13532:     my ($cnum,$cdom) = @_;
13533:     my $hashid=$cnum.':'.$cdom;
13534:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13535:     if (defined($cached)) {
13536:         if (ref($result) eq 'HASH') {
13537:             return %{$result};
13538:         }
13539:     } else {
13540:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13541:         my ($tmp) = keys(%slots);
13542:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13543:             &do_cache_new('allslots',$hashid,\%slots,600);
13544:             return %slots;
13545:         }
13546:     }
13547:     return;
13548: }
13549: 
13550: sub devalidate_slots_cache {
13551:     my ($cnum,$cdom)=@_;
13552:     my $hashid=$cnum.':'.$cdom;
13553:     &devalidate_cache_new('allslots',$hashid);
13554: }
13555: 
13556: sub get_coursechange {
13557:     my ($cdom,$cnum) = @_;
13558:     if ($cdom eq '' || $cnum eq '') {
13559:         return unless ($env{'request.course.id'});
13560:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13561:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13562:     }
13563:     my $hashid=$cdom.'_'.$cnum;
13564:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13565:     if ((defined($cached)) && ($change ne '')) {
13566:         return $change;
13567:     } else {
13568:         my %crshash;
13569:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13570:         if ($crshash{'internal.contentchange'} eq '') {
13571:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13572:             if ($change eq '') {
13573:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13574:                 $change = $crshash{'internal.created'};
13575:             }
13576:         } else {
13577:             $change = $crshash{'internal.contentchange'};
13578:         }
13579:         my $cachetime = 600;
13580:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13581:     }
13582:     return $change;
13583: }
13584: 
13585: sub devalidate_coursechange_cache {
13586:     my ($cnum,$cdom)=@_;
13587:     my $hashid=$cnum.':'.$cdom;
13588:     &devalidate_cache_new('crschange',$hashid);
13589: }
13590: 
13591: # ------------------------------------------------- Update symbolic store links
13592: 
13593: sub symblist {
13594:     my ($mapname,%newhash)=@_;
13595:     $mapname=&deversion(&declutter($mapname));
13596:     my %hash;
13597:     if (($env{'request.course.fn'}) && (%newhash)) {
13598:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13599:                       &GDBM_WRCREAT(),0640)) {
13600: 	    foreach my $url (keys(%newhash)) {
13601: 		next if ($url eq 'last_known'
13602: 			 && $env{'form.no_update_last_known'});
13603: 		$hash{declutter($url)}=&encode_symb($mapname,
13604: 						    $newhash{$url}->[1],
13605: 						    $newhash{$url}->[0]);
13606:             }
13607:             if (untie(%hash)) {
13608: 		return 'ok';
13609:             }
13610:         }
13611:     }
13612:     return 'error';
13613: }
13614: 
13615: # --------------------------------------------------------------- Verify a symb
13616: 
13617: sub symbverify {
13618:     my ($symb,$thisurl,$encstate)=@_;
13619:     my $thisfn=$thisurl;
13620:     $thisfn=&declutter($thisfn);
13621: # direct jump to resource in page or to a sequence - will construct own symbs
13622:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13623: # check URL part
13624:     my ($map,$resid,$url)=&decode_symb($symb);
13625: 
13626:     unless ($url eq $thisfn) { return 0; }
13627: 
13628:     $symb=&symbclean($symb);
13629:     $thisurl=&deversion($thisurl);
13630:     $thisfn=&deversion($thisfn);
13631: 
13632:     my %bighash;
13633:     my $okay=0;
13634: 
13635:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13636:                             &GDBM_READER(),0640)) {
13637:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13638:             $thisurl =~ s/\?.+$//;
13639:             if ($map =~ m{^uploaded/.+\.page$}) {
13640:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13641:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13642:             }
13643:         }
13644:         my $ids;
13645:         if ($map =~ m{^uploaded/.+\.page$}) {
13646:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13647:         } else {
13648:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13649:         }
13650:         unless ($ids) {
13651:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13652:             $ids=$bighash{$idkey};
13653:         }
13654:         if ($ids) {
13655: # ------------------------------------------------------------------- Has ID(s)
13656:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13657:                 $symb =~ s/\?.+$//;
13658:             }
13659: 	    foreach my $id (split(/\,/,$ids)) {
13660: 	       my ($mapid,$resid)=split(/\./,$id);
13661:                if (
13662:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13663:    eq $symb) {
13664:                    if (ref($encstate)) {
13665:                        $$encstate = $bighash{'encrypted_'.$id};
13666:                    }
13667: 		   if (($env{'request.role.adv'}) ||
13668: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13669:                        ($thisurl eq '/adm/navmaps')) {
13670: 		       $okay=1;
13671:                        last;
13672: 		   }
13673: 	       }
13674: 	   }
13675:         }
13676: 	untie(%bighash);
13677:     }
13678:     return $okay;
13679: }
13680: 
13681: # --------------------------------------------------------------- Clean-up symb
13682: 
13683: sub symbclean {
13684:     my $symb=shift;
13685:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13686: # remove version from map
13687:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13688: 
13689: # remove version from URL
13690:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13691: 
13692: # remove wrapper
13693: 
13694:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13695:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13696:     return $symb;
13697: }
13698: 
13699: # ---------------------------------------------- Split symb to find map and url
13700: 
13701: sub encode_symb {
13702:     my ($map,$resid,$url)=@_;
13703:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13704: }
13705: 
13706: sub decode_symb {
13707:     my $symb=shift;
13708:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13709:     my ($map,$resid,$url)=split(/___/,$symb);
13710:     return (&fixversion($map),$resid,&fixversion($url));
13711: }
13712: 
13713: sub fixversion {
13714:     my $fn=shift;
13715:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13716:     my %bighash;
13717:     my $uri=&clutter($fn);
13718:     my $key=$env{'request.course.id'}.'_'.$uri;
13719: # is this cached?
13720:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13721:     if (defined($cached)) { return $result; }
13722: # unfortunately not cached, or expired
13723:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13724: 	    &GDBM_READER(),0640)) {
13725:  	if ($bighash{'version_'.$uri}) {
13726:  	    my $version=$bighash{'version_'.$uri};
13727:  	    unless (($version eq 'mostrecent') || 
13728: 		    ($version==&getversion($uri))) {
13729:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13730:  	    }
13731:  	}
13732:  	untie %bighash;
13733:     }
13734:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13735: }
13736: 
13737: sub deversion {
13738:     my $url=shift;
13739:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13740:     return $url;
13741: }
13742: 
13743: # ------------------------------------------------------ Return symb list entry
13744: 
13745: sub symbread {
13746:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13747:         $ignoresymbdb,$noenccheck)=@_;
13748:     my $cache_str='request.symbread.cached.'.$thisfn;
13749:     if (defined($env{$cache_str})) {
13750:         unless (ref($possibles) eq 'HASH') {
13751:             if ($ignorecachednull) {
13752:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13753:             } else {
13754:                 return $env{$cache_str};
13755:             }
13756:         }
13757:     }
13758: # no filename provided? try from environment
13759:     unless ($thisfn) {
13760:         if ($env{'request.symb'}) {
13761:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13762: 	}
13763: 	$thisfn=$env{'request.filename'};
13764:     }
13765:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13766: # is that filename actually a symb? Verify, clean, and return
13767:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13768: 	if (&symbverify($thisfn,$1)) {
13769: 	    return $env{$cache_str}=&symbclean($thisfn);
13770: 	}
13771:     }
13772:     $thisfn=declutter($thisfn);
13773:     my %hash;
13774:     my %bighash;
13775:     my $syval='';
13776:     if (($env{'request.course.fn'}) && ($thisfn)) {
13777:         unless ($ignoresymbdb) {
13778:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13779:                           &GDBM_READER(),0640)) {
13780: 	        $syval=$hash{$thisfn};
13781:                 untie(%hash);
13782:             }
13783:             if ($syval && $checkforblock) {
13784:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13785:                 if (@blockers) {
13786:                     $syval='';
13787:                 }
13788:             }
13789:         }
13790: # ---------------------------------------------------------- There was an entry
13791:         if ($syval) {
13792: 	    #unless ($syval=~/\_\d+$/) {
13793: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13794: 		    #&appenv({'request.ambiguous' => $thisfn});
13795: 		    #return $env{$cache_str}='';
13796: 		#}    
13797: 		#$syval.=$1;
13798: 	    #}
13799:         } else {
13800: # ------------------------------------------------------- Was not in symb table
13801:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13802:                             &GDBM_READER(),0640)) {
13803: # ---------------------------------------------- Get ID(s) for current resource
13804:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13805:               unless ($ids) { 
13806:                  $ids=$bighash{'ids_/'.$thisfn};
13807:               }
13808:               unless ($ids) {
13809: # alias?
13810: 		  $ids=$bighash{'mapalias_'.$thisfn};
13811:               }
13812:               if ($ids) {
13813: # ------------------------------------------------------------------- Has ID(s)
13814:                  my @possibilities=split(/\,/,$ids);
13815:                  if ($#possibilities==0) {
13816: # ----------------------------------------------- There is only one possibility
13817: 		     my ($mapid,$resid)=split(/\./,$ids);
13818: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13819: 						    $resid,$thisfn);
13820:                      if (ref($possibles) eq 'HASH') {
13821:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13822:                              $possibles->{$syval} = 1;
13823:                          }
13824:                      }
13825:                      if ($checkforblock) {
13826:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13827:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13828:                              if (@blockers) {
13829:                                  $syval = '';
13830:                                  untie(%bighash);
13831:                                  return $env{$cache_str}='';
13832:                              }
13833:                          }
13834:                      }
13835:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13836: # ------------------------------------------ There is more than one possibility
13837:                      my $realpossible=0;
13838:                      foreach my $id (@possibilities) {
13839: 			 my $file=$bighash{'src_'.$id};
13840:                          my $canaccess;
13841:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13842:                              $canaccess = 1;
13843:                          } else { 
13844:                              $canaccess = &allowed('bre',$file);
13845:                          }
13846:                          if ($canaccess) {
13847:          		     my ($mapid,$resid)=split(/\./,$id);
13848:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13849:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13850: 						             $resid,$thisfn);
13851:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13852:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13853:                                  if ($checkforblock) {
13854:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13855:                                      if (@blockers > 0) {
13856:                                          $syval = '';
13857:                                      } else {
13858:                                          $syval = $poss_syval;
13859:                                          $realpossible++;
13860:                                      }
13861:                                  } else {
13862:                                      $syval = $poss_syval;
13863:                                      $realpossible++;
13864:                                  }
13865:                                  if ($syval) {
13866:                                      if (ref($possibles) eq 'HASH') {
13867:                                          $possibles->{$syval} = 1;
13868:                                      }
13869:                                  }
13870:                              }
13871: 			 }
13872:                      }
13873: 		     if ($realpossible!=1) { $syval=''; }
13874:                  } else {
13875:                      $syval='';
13876:                  }
13877: 	      }
13878:               untie(%bighash);
13879:            }
13880:         }
13881:         if ($syval) {
13882: 	    return $env{$cache_str}=$syval;
13883:         }
13884:     }
13885:     &appenv({'request.ambiguous' => $thisfn});
13886:     return $env{$cache_str}='';
13887: }
13888: 
13889: # ---------------------------------------------------------- Return random seed
13890: 
13891: sub numval {
13892:     my $txt=shift;
13893:     $txt=~tr/A-J/0-9/;
13894:     $txt=~tr/a-j/0-9/;
13895:     $txt=~tr/K-T/0-9/;
13896:     $txt=~tr/k-t/0-9/;
13897:     $txt=~tr/U-Z/0-5/;
13898:     $txt=~tr/u-z/0-5/;
13899:     $txt=~s/\D//g;
13900:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13901:     return int($txt);
13902: }
13903: 
13904: sub numval2 {
13905:     my $txt=shift;
13906:     $txt=~tr/A-J/0-9/;
13907:     $txt=~tr/a-j/0-9/;
13908:     $txt=~tr/K-T/0-9/;
13909:     $txt=~tr/k-t/0-9/;
13910:     $txt=~tr/U-Z/0-5/;
13911:     $txt=~tr/u-z/0-5/;
13912:     $txt=~s/\D//g;
13913:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13914:     my $total;
13915:     foreach my $val (@txts) { $total+=$val; }
13916:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13917:     return int($total);
13918: }
13919: 
13920: sub numval3 {
13921:     use integer;
13922:     my $txt=shift;
13923:     $txt=~tr/A-J/0-9/;
13924:     $txt=~tr/a-j/0-9/;
13925:     $txt=~tr/K-T/0-9/;
13926:     $txt=~tr/k-t/0-9/;
13927:     $txt=~tr/U-Z/0-5/;
13928:     $txt=~tr/u-z/0-5/;
13929:     $txt=~s/\D//g;
13930:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13931:     my $total;
13932:     foreach my $val (@txts) { $total+=$val; }
13933:     if ($_64bit) { $total=(($total<<32)>>32); }
13934:     return $total;
13935: }
13936: 
13937: sub digest {
13938:     my ($data)=@_;
13939:     my $digest=&Digest::MD5::md5($data);
13940:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13941:     my ($e,$f);
13942:     {
13943:         use integer;
13944:         $e=($a+$b);
13945:         $f=($c+$d);
13946:         if ($_64bit) {
13947:             $e=(($e<<32)>>32);
13948:             $f=(($f<<32)>>32);
13949:         }
13950:     }
13951:     if (wantarray) {
13952: 	return ($e,$f);
13953:     } else {
13954: 	my $g;
13955: 	{
13956: 	    use integer;
13957: 	    $g=($e+$f);
13958: 	    if ($_64bit) {
13959: 		$g=(($g<<32)>>32);
13960: 	    }
13961: 	}
13962: 	return $g;
13963:     }
13964: }
13965: 
13966: sub latest_rnd_algorithm_id {
13967:     return '64bit5';
13968: }
13969: 
13970: sub get_rand_alg {
13971:     my ($courseid)=@_;
13972:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13973:     if ($courseid) {
13974: 	return $env{"course.$courseid.rndseed"};
13975:     }
13976:     return &latest_rnd_algorithm_id();
13977: }
13978: 
13979: sub validCODE {
13980:     my ($CODE)=@_;
13981:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13982:     return 0;
13983: }
13984: 
13985: sub getCODE {
13986:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13987:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13988: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13989: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13990: 	return $Apache::lonhomework::history{'resource.CODE'};
13991:     }
13992:     return undef;
13993: }
13994: #
13995: #  Determines the random seed for a specific context:
13996: #
13997: # parameters:
13998: #   symb      - in course context the symb for the seed.
13999: #   course_id - The course id of the form domain_coursenum.
14000: #   domain    - Domain for the user.
14001: #   course    - Course for the user.
14002: #   cenv      - environment of the course.
14003: #
14004: # NOTE:
14005: #   All parameters are picked out of the environment if missing
14006: #   or not defined.
14007: #   If a symb cannot be determined the current time is used instead.
14008: #
14009: #  For a given well defined symb, courside, domain, username,
14010: #  and course environment, the seed is reproducible.
14011: #
14012: sub rndseed {
14013:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14014:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14015:     if (!defined($symb)) {
14016: 	unless ($symb=$wsymb) { return time; }
14017:     }
14018:     if (!defined $courseid) { 
14019: 	$courseid=$wcourseid; 
14020:     }
14021:     if (!defined $domain) { $domain=$wdomain; }
14022:     if (!defined $username) { $username=$wusername }
14023: 
14024:     my $which;
14025:     if (defined($cenv->{'rndseed'})) {
14026: 	$which = $cenv->{'rndseed'};
14027:     } else {
14028: 	$which =&get_rand_alg($courseid);
14029:     }
14030:     if (defined(&getCODE())) {
14031: 
14032: 	if ($which eq '64bit5') {
14033: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14034: 	} elsif ($which eq '64bit4') {
14035: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14036: 	} else {
14037: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14038: 	}
14039:     } elsif ($which eq '64bit5') {
14040: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14041:     } elsif ($which eq '64bit4') {
14042: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14043:     } elsif ($which eq '64bit3') {
14044: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14045:     } elsif ($which eq '64bit2') {
14046: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14047:     } elsif ($which eq '64bit') {
14048: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14049:     }
14050:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14051: }
14052: 
14053: sub rndseed_32bit {
14054:     my ($symb,$courseid,$domain,$username)=@_;
14055:     {
14056: 	use integer;
14057: 	my $symbchck=unpack("%32C*",$symb) << 27;
14058: 	my $symbseed=numval($symb) << 22;
14059: 	my $namechck=unpack("%32C*",$username) << 17;
14060: 	my $nameseed=numval($username) << 12;
14061: 	my $domainseed=unpack("%32C*",$domain) << 7;
14062: 	my $courseseed=unpack("%32C*",$courseid);
14063: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14064: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14065: 	#&logthis("rndseed :$num:$symb");
14066: 	if ($_64bit) { $num=(($num<<32)>>32); }
14067: 	return $num;
14068:     }
14069: }
14070: 
14071: sub rndseed_64bit {
14072:     my ($symb,$courseid,$domain,$username)=@_;
14073:     {
14074: 	use integer;
14075: 	my $symbchck=unpack("%32S*",$symb) << 21;
14076: 	my $symbseed=numval($symb) << 10;
14077: 	my $namechck=unpack("%32S*",$username);
14078: 	
14079: 	my $nameseed=numval($username) << 21;
14080: 	my $domainseed=unpack("%32S*",$domain) << 10;
14081: 	my $courseseed=unpack("%32S*",$courseid);
14082: 	
14083: 	my $num1=$symbchck+$symbseed+$namechck;
14084: 	my $num2=$nameseed+$domainseed+$courseseed;
14085: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14086: 	#&logthis("rndseed :$num:$symb");
14087: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14088: 	return "$num1,$num2";
14089:     }
14090: }
14091: 
14092: sub rndseed_64bit2 {
14093:     my ($symb,$courseid,$domain,$username)=@_;
14094:     {
14095: 	use integer;
14096: 	# strings need to be an even # of cahracters long, it it is odd the
14097:         # last characters gets thrown away
14098: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14099: 	my $symbseed=numval($symb) << 10;
14100: 	my $namechck=unpack("%32S*",$username.' ');
14101: 	
14102: 	my $nameseed=numval($username) << 21;
14103: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14104: 	my $courseseed=unpack("%32S*",$courseid.' ');
14105: 	
14106: 	my $num1=$symbchck+$symbseed+$namechck;
14107: 	my $num2=$nameseed+$domainseed+$courseseed;
14108: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14109: 	#&logthis("rndseed :$num:$symb");
14110: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14111: 	return "$num1,$num2";
14112:     }
14113: }
14114: 
14115: sub rndseed_64bit3 {
14116:     my ($symb,$courseid,$domain,$username)=@_;
14117:     {
14118: 	use integer;
14119: 	# strings need to be an even # of cahracters long, it it is odd the
14120:         # last characters gets thrown away
14121: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14122: 	my $symbseed=numval2($symb) << 10;
14123: 	my $namechck=unpack("%32S*",$username.' ');
14124: 	
14125: 	my $nameseed=numval2($username) << 21;
14126: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14127: 	my $courseseed=unpack("%32S*",$courseid.' ');
14128: 	
14129: 	my $num1=$symbchck+$symbseed+$namechck;
14130: 	my $num2=$nameseed+$domainseed+$courseseed;
14131: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14132: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14133: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14134: 	
14135: 	return "$num1:$num2";
14136:     }
14137: }
14138: 
14139: sub rndseed_64bit4 {
14140:     my ($symb,$courseid,$domain,$username)=@_;
14141:     {
14142: 	use integer;
14143: 	# strings need to be an even # of cahracters long, it it is odd the
14144:         # last characters gets thrown away
14145: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14146: 	my $symbseed=numval3($symb) << 10;
14147: 	my $namechck=unpack("%32S*",$username.' ');
14148: 	
14149: 	my $nameseed=numval3($username) << 21;
14150: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14151: 	my $courseseed=unpack("%32S*",$courseid.' ');
14152: 	
14153: 	my $num1=$symbchck+$symbseed+$namechck;
14154: 	my $num2=$nameseed+$domainseed+$courseseed;
14155: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14156: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14157: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14158: 	
14159: 	return "$num1:$num2";
14160:     }
14161: }
14162: 
14163: sub rndseed_64bit5 {
14164:     my ($symb,$courseid,$domain,$username)=@_;
14165:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14166:     return "$num1:$num2";
14167: }
14168: 
14169: sub rndseed_CODE_64bit {
14170:     my ($symb,$courseid,$domain,$username)=@_;
14171:     {
14172: 	use integer;
14173: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14174: 	my $symbseed=numval2($symb);
14175: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14176: 	my $CODEseed=numval(&getCODE());
14177: 	my $courseseed=unpack("%32S*",$courseid.' ');
14178: 	my $num1=$symbseed+$CODEchck;
14179: 	my $num2=$CODEseed+$courseseed+$symbchck;
14180: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14181: 	#&logthis("rndseed :$num1:$num2:$symb");
14182: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14183: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14184: 	return "$num1:$num2";
14185:     }
14186: }
14187: 
14188: sub rndseed_CODE_64bit4 {
14189:     my ($symb,$courseid,$domain,$username)=@_;
14190:     {
14191: 	use integer;
14192: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14193: 	my $symbseed=numval3($symb);
14194: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14195: 	my $CODEseed=numval3(&getCODE());
14196: 	my $courseseed=unpack("%32S*",$courseid.' ');
14197: 	my $num1=$symbseed+$CODEchck;
14198: 	my $num2=$CODEseed+$courseseed+$symbchck;
14199: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14200: 	#&logthis("rndseed :$num1:$num2:$symb");
14201: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14202: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14203: 	return "$num1:$num2";
14204:     }
14205: }
14206: 
14207: sub rndseed_CODE_64bit5 {
14208:     my ($symb,$courseid,$domain,$username)=@_;
14209:     my $code = &getCODE();
14210:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14211:     return "$num1:$num2";
14212: }
14213: 
14214: sub setup_random_from_rndseed {
14215:     my ($rndseed)=@_;
14216:     if ($rndseed =~/([,:])/) {
14217:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14218:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14219:             &Math::Random::random_set_seed_from_phrase($rndseed);
14220:         } else {
14221:             &Math::Random::random_set_seed($num1,$num2);
14222:         }
14223:     } else {
14224: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14225:     }
14226: }
14227: 
14228: sub latest_receipt_algorithm_id {
14229:     return 'receipt3';
14230: }
14231: 
14232: sub recunique {
14233:     my $fucourseid=shift;
14234:     my $unique;
14235:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14236: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14237: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14238:     } else {
14239: 	$unique=$perlvar{'lonReceipt'};
14240:     }
14241:     return unpack("%32C*",$unique);
14242: }
14243: 
14244: sub recprefix {
14245:     my $fucourseid=shift;
14246:     my $prefix;
14247:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14248: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14249: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14250:     } else {
14251: 	$prefix=$perlvar{'lonHostID'};
14252:     }
14253:     return unpack("%32C*",$prefix);
14254: }
14255: 
14256: sub ireceipt {
14257:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14258: 
14259:     my $return =&recprefix($fucourseid).'-';
14260: 
14261:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14262: 	$env{'request.state'} eq 'construct') {
14263: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14264: 	return $return;
14265:     }
14266: 
14267:     my $cuname=unpack("%32C*",$funame);
14268:     my $cudom=unpack("%32C*",$fudom);
14269:     my $cucourseid=unpack("%32C*",$fucourseid);
14270:     my $cusymb=unpack("%32C*",$fusymb);
14271:     my $cunique=&recunique($fucourseid);
14272:     my $cpart=unpack("%32S*",$part);
14273:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14274: 
14275: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14276: 			       
14277: 	$return.= ($cunique%$cuname+
14278: 		   $cunique%$cudom+
14279: 		   $cusymb%$cuname+
14280: 		   $cusymb%$cudom+
14281: 		   $cucourseid%$cuname+
14282: 		   $cucourseid%$cudom+
14283: 		   $cpart%$cuname+
14284: 		   $cpart%$cudom);
14285:     } else {
14286: 	$return.= ($cunique%$cuname+
14287: 		   $cunique%$cudom+
14288: 		   $cusymb%$cuname+
14289: 		   $cusymb%$cudom+
14290: 		   $cucourseid%$cuname+
14291: 		   $cucourseid%$cudom);
14292:     }
14293:     return $return;
14294: }
14295: 
14296: sub receipt {
14297:     my ($part)=@_;
14298:     my ($symb,$courseid,$domain,$name) = &whichuser();
14299:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14300: }
14301: 
14302: sub whichuser {
14303:     my ($passedsymb)=@_;
14304:     my ($symb,$courseid,$domain,$name,$publicuser);
14305:     if (defined($env{'form.grade_symb'})) {
14306: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14307: 	my $allowed=&allowed('vgr',$tmp_courseid);
14308: 	if (!$allowed &&
14309: 	    exists($env{'request.course.sec'}) &&
14310: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14311: 	    $allowed=&allowed('vgr',$tmp_courseid.
14312: 			      '/'.$env{'request.course.sec'});
14313: 	}
14314: 	if ($allowed) {
14315: 	    ($symb)=&get_env_multiple('form.grade_symb');
14316: 	    $courseid=$tmp_courseid;
14317: 	    ($domain)=&get_env_multiple('form.grade_domain');
14318: 	    ($name)=&get_env_multiple('form.grade_username');
14319: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14320: 	}
14321:     }
14322:     if (!$passedsymb) {
14323: 	$symb=&symbread();
14324:     } else {
14325: 	$symb=$passedsymb;
14326:     }
14327:     $courseid=$env{'request.course.id'};
14328:     $domain=$env{'user.domain'};
14329:     $name=$env{'user.name'};
14330:     if ($name eq 'public' && $domain eq 'public') {
14331: 	if (!defined($env{'form.username'})) {
14332: 	    $env{'form.username'}.=time.rand(10000000);
14333: 	}
14334: 	$name.=$env{'form.username'};
14335:     }
14336:     return ($symb,$courseid,$domain,$name,$publicuser);
14337: 
14338: }
14339: 
14340: # ------------------------------------------------------------ Serves up a file
14341: # returns either the contents of the file or 
14342: # -1 if the file doesn't exist
14343: #
14344: # if the target is a file that was uploaded via DOCS, 
14345: # a check will be made to see if a current copy exists on the local server,
14346: # if it does this will be served, otherwise a copy will be retrieved from
14347: # the home server for the course and stored in /home/httpd/html/userfiles on
14348: # the local server.   
14349: 
14350: sub getfile {
14351:     my ($file) = @_;
14352:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14353:     &repcopy($file);
14354:     return &readfile($file);
14355: }
14356: 
14357: sub repcopy_userfile {
14358:     my ($file)=@_;
14359:     my $londocroot = $perlvar{'lonDocRoot'};
14360:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14361:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14362:     my ($cdom,$cnum,$filename) = 
14363: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14364:     my $uri="/uploaded/$cdom/$cnum/$filename";
14365:     if (-e "$file") {
14366: # we already have a local copy, check it out
14367: 	my @fileinfo = stat($file);
14368: 	my $rtncode;
14369: 	my $info;
14370: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14371: 	if ($lwpresp ne 'ok') {
14372: # there is no such file anymore, even though we had a local copy
14373: 	    if ($rtncode eq '404') {
14374: 		unlink($file);
14375: 	    }
14376: 	    return -1;
14377: 	}
14378: 	if ($info < $fileinfo[9]) {
14379: # nice, the file we have is up-to-date, just say okay
14380: 	    return 'ok';
14381: 	} else {
14382: # the file is outdated, get rid of it
14383: 	    unlink($file);
14384: 	}
14385:     }
14386: # one way or the other, at this point, we don't have the file
14387: # construct the correct path for the file
14388:     my @parts = ($cdom,$cnum); 
14389:     if ($filename =~ m|^(.+)/[^/]+$|) {
14390: 	push @parts, split(/\//,$1);
14391:     }
14392:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14393:     foreach my $part (@parts) {
14394: 	$path .= '/'.$part;
14395: 	if (!-e $path) {
14396: 	    mkdir($path,0770);
14397: 	}
14398:     }
14399: # now the path exists for sure
14400: # get a user agent
14401:     my $transferfile=$file.'.in.transfer';
14402: # FIXME: this should flock
14403:     if (-e $transferfile) { return 'ok'; }
14404:     my $request;
14405:     $uri=~s/^\///;
14406:     my $homeserver = &homeserver($cnum,$cdom);
14407:     my $hostname = &hostname($homeserver);
14408:     my $protocol = $protocol{$homeserver};
14409:     $protocol = 'http' if ($protocol ne 'https');
14410:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14411:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14412: # did it work?
14413:     if ($response->is_error()) {
14414: 	unlink($transferfile);
14415: 	&logthis("Userfile repcopy failed for $uri");
14416: 	return -1;
14417:     }
14418: # worked, rename the transfer file
14419:     rename($transferfile,$file);
14420:     return 'ok';
14421: }
14422: 
14423: sub tokenwrapper {
14424:     my $uri=shift;
14425:     $uri=~s|^https?\://([^/]+)||;
14426:     $uri=~s|^/||;
14427:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14428:     my $token=$1;
14429:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14430:     if ($udom && $uname && $file) {
14431: 	$file=~s|(\?\.*)*$||;
14432:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14433:         my $homeserver = &homeserver($uname,$udom);
14434:         my $hostname = &hostname($homeserver);
14435:         my $protocol = $protocol{$homeserver};
14436:         $protocol = 'http' if ($protocol ne 'https');
14437:         return $protocol.'://'.$hostname.'/'.$uri.
14438:                (($uri=~/\?/)?'&':'?').'token='.$token.
14439:                                '&tokenissued='.$perlvar{'lonHostID'};
14440:     } else {
14441:         return '/adm/notfound.html';
14442:     }
14443: }
14444: 
14445: # call with reqtype HEAD: get last modification time
14446: # call with reqtype GET: get the file contents
14447: # Do not call this with reqtype GET for large files! It loads everything into memory
14448: #
14449: sub getuploaded {
14450:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14451:     $uri=~s/^\///;
14452:     my $homeserver = &homeserver($cnum,$cdom);
14453:     my $hostname = &hostname($homeserver);
14454:     my $protocol = $protocol{$homeserver};
14455:     $protocol = 'http' if ($protocol ne 'https');
14456:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14457:     my $request=new HTTP::Request($reqtype,$uri);
14458:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14459:     $$rtncode = $response->code;
14460:     if (! $response->is_success()) {
14461: 	return 'failed';
14462:     }      
14463:     if ($reqtype eq 'HEAD') {
14464: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14465:     } elsif ($reqtype eq 'GET') {
14466: 	$$info = $response->content;
14467:     }
14468:     return 'ok';
14469: }
14470: 
14471: sub readfile {
14472:     my $file = shift;
14473:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14474:     my $fh;
14475:     open($fh,"<",$file);
14476:     my $a='';
14477:     while (my $line = <$fh>) { $a .= $line; }
14478:     return $a;
14479: }
14480: 
14481: sub filelocation {
14482:     my ($dir,$file) = @_;
14483:     my $location;
14484:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14485: 
14486:     if ($file =~ m-^/adm/-) {
14487: 	$file=~s-^/adm/wrapper/-/-;
14488: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14489:     }
14490: 
14491:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14492:         $location = $file;
14493:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14494:         my ($udom,$uname,$filename)=
14495:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14496:         my $home=&homeserver($uname,$udom);
14497:         my $is_me=0;
14498:         my @ids=&current_machine_ids();
14499:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14500:         if ($is_me) {
14501:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14502:         } else {
14503:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14504:   	      $udom.'/'.$uname.'/'.$filename;
14505:         }
14506:     } elsif ($file =~ m-^/adm/-) {
14507: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14508:     } else {
14509:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14510:         $file=~s:^/(res|priv)/:/:;
14511:         my $space=$1;
14512:         if ( !( $file =~ m:^/:) ) {
14513:             $location = $dir. '/'.$file;
14514:         } else {
14515:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14516:         }
14517:     }
14518:     $location=~s://+:/:g; # remove duplicate /
14519:     while ($location=~m{/\.\./}) {
14520: 	if ($location =~ m{/[^/]+/\.\./}) {
14521: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14522: 	} else {
14523: 	    $location=~ s{/\.\./}{/}g;
14524: 	}
14525:     } #remove dir/..
14526:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14527:     return $location;
14528: }
14529: 
14530: sub hreflocation {
14531:     my ($dir,$file)=@_;
14532:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14533: 	$file=filelocation($dir,$file);
14534:     } elsif ($file=~m-^/adm/-) {
14535: 	$file=~s-^/adm/wrapper/-/-;
14536: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14537:     }
14538:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14539: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14540:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14541: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14542: 	        {/uploaded/$1/$2/}x;
14543:     }
14544:     if ($file=~ m{^/userfiles/}) {
14545: 	$file =~ s{^/userfiles/}{/uploaded/};
14546:     }
14547:     return $file;
14548: }
14549: 
14550: 
14551: 
14552: 
14553: 
14554: sub current_machine_domains {
14555:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14556: }
14557: 
14558: sub machine_domains {
14559:     my ($hostname) = @_;
14560:     my @domains;
14561:     my %hostname = &all_hostnames();
14562:     while( my($id, $name) = each(%hostname)) {
14563: #	&logthis("-$id-$name-$hostname-");
14564: 	if ($hostname eq $name) {
14565: 	    push(@domains,&host_domain($id));
14566: 	}
14567:     }
14568:     return @domains;
14569: }
14570: 
14571: sub current_machine_ids {
14572:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14573: }
14574: 
14575: sub machine_ids {
14576:     my ($hostname) = @_;
14577:     $hostname ||= &hostname($perlvar{'lonHostID'});
14578:     my @ids;
14579:     my %name_to_host = &all_names();
14580:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14581: 	return @{ $name_to_host{$hostname} };
14582:     }
14583:     return;
14584: }
14585: 
14586: sub additional_machine_domains {
14587:     my @domains;
14588:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14589:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14590:             while (my $line = <$fh>) {
14591:                 chomp($line);           
14592:                 $line =~ s/\s//g;
14593:                 push(@domains,$line);
14594:             }
14595:             close($fh);
14596:         }
14597:     }
14598:     return @domains;
14599: }
14600: 
14601: sub default_login_domain {
14602:     my $domain = $perlvar{'lonDefDomain'};
14603:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14604:     foreach my $posdom (&current_machine_domains(),
14605:                         &additional_machine_domains()) {
14606:         if (lc($posdom) eq lc($testdomain)) {
14607:             $domain=$posdom;
14608:             last;
14609:         }
14610:     }
14611:     return $domain;
14612: }
14613: 
14614: sub shared_institution {
14615:     my ($dom,$lonhost) = @_;
14616:     if ($lonhost eq '') {
14617:         $lonhost = $perlvar{'lonHostID'};
14618:     }
14619:     my $same_intdom;
14620:     my $hostintdom = &internet_dom($lonhost);
14621:     if ($hostintdom ne '') {
14622:         my %iphost = &get_iphost();
14623:         my $primary_id = &domain($dom,'primary');
14624:         my $primary_ip = &get_host_ip($primary_id);
14625:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14626:             foreach my $id (@{$iphost{$primary_ip}}) {
14627:                 my $intdom = &internet_dom($id);
14628:                 if ($intdom eq $hostintdom) {
14629:                     $same_intdom = 1;
14630:                     last;
14631:                 }
14632:             }
14633:         }
14634:     }
14635:     return $same_intdom;
14636: }
14637: 
14638: sub uses_sts {
14639:     my ($ignore_cache) = @_;
14640:     my $lonhost = $perlvar{'lonHostID'};
14641:     my $hostname = &hostname($lonhost);
14642:     my $sts_on;
14643:     if ($protocol{$lonhost} eq 'https') {
14644:         my $cachetime = 12*3600;
14645:         if (!$ignore_cache) {
14646:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14647:             if (defined($cached)) {
14648:                 return $sts_on;
14649:             }
14650:         }
14651:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14652:         my $request=new HTTP::Request('HEAD',$url);
14653:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14654:         if ($response->is_success) {
14655:             my $has_sts = $response->header('Strict-Transport-Security');
14656:             if ($has_sts eq '') {
14657:                 $sts_on = 0;
14658:             } else {
14659:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14660:                     my $maxage = $1;
14661:                     if ($maxage) {
14662:                         $sts_on = 1;
14663:                     } else {
14664:                         $sts_on = 0;
14665:                     }
14666:                 } else {
14667:                     $sts_on = 0;
14668:                 }
14669:             }
14670:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14671:         }
14672:     }
14673:     return;
14674: }
14675: 
14676: sub waf_allssl {
14677:     my ($host_name) = @_;
14678:     my $alias = &get_proxy_alias();
14679:     if ($host_name eq '') {
14680:         $host_name = $ENV{'SERVER_NAME'};
14681:     }
14682:     if (($host_name ne '') && ($alias eq $host_name)) {
14683:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14684:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14685:         if ($defdomdefaults{'waf_sslopt'}) {
14686:             return $defdomdefaults{'waf_sslopt'};
14687:         }
14688:     }
14689:     return;
14690: }
14691: 
14692: sub get_requestor_ip {
14693:     my ($r,$nolookup,$noproxy) = @_;
14694:     my $from_ip;
14695:     if (ref($r)) {
14696:         if ($r->can('useragent_ip')) {
14697:             if ($noproxy && $r->can('client_ip')) {
14698:                 $from_ip = $r->client_ip();
14699:             } else {
14700:                 $from_ip = $r->useragent_ip();
14701:             }
14702:         } elsif ($r->connection->can('remote_ip')) {
14703:             $from_ip = $r->connection->remote_ip();
14704:         } else {
14705:             $from_ip = $r->get_remote_host($nolookup);
14706:         }
14707:     } else {
14708:         $from_ip = $ENV{'REMOTE_ADDR'};
14709:     }
14710:     return $from_ip if ($noproxy); 
14711:     # Who controls proxy settings for server
14712:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14713:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14714:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14715:         if ($proxyinfo->{'vpnint'}) {
14716:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14717:                 return $from_ip;
14718:             }
14719:         }
14720:         if ($proxyinfo->{'trusted'}) {
14721:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14722:                 my $ipheader = $proxyinfo->{'ipheader'};
14723:                 my ($ip,$xfor);
14724:                 if (ref($r)) {
14725:                     if ($ipheader) {
14726:                         $ip = $r->headers_in->{$ipheader};
14727:                     }
14728:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14729:                 } else {
14730:                     if ($ipheader) {
14731:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14732:                     }
14733:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14734:                 }
14735:                 if (($ip eq '') && ($xfor ne '')) {
14736:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14737:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14738:                             $ip = $poss_ip;
14739:                             last;
14740:                         }
14741:                     }
14742:                 }
14743:                 if ($ip ne '') {
14744:                     return $ip;
14745:                 }
14746:             }
14747:         }
14748:     }
14749:     return $from_ip;
14750: }
14751: 
14752: sub get_proxy_settings {
14753:     my ($dom_in_use) = @_;
14754:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14755:     my $proxyinfo = {
14756:                        ipheader => $domdefaults{'waf_ipheader'},
14757:                        trusted  => $domdefaults{'waf_trusted'},
14758:                        vpnint   => $domdefaults{'waf_vpnint'},
14759:                        vpnext   => $domdefaults{'waf_vpnext'},
14760:                        sslopt   => $domdefaults{'waf_sslopt'},
14761:                     };
14762:     return $proxyinfo;
14763: }
14764: 
14765: sub ip_match {
14766:     my ($ip,$pattern_str) = @_;
14767:     $ip=Net::CIDR::cidrvalidate($ip);
14768:     if ($ip) {
14769:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14770:     }
14771:     return;
14772: }
14773: 
14774: sub get_proxy_alias {
14775:     my ($lonid) = @_;
14776:     if ($lonid eq '') {
14777:         $lonid = $perlvar{'lonHostID'};
14778:     }
14779:     if (!defined(&hostname($lonid))) {
14780:         return;
14781:     }
14782:     if ($lonid ne '') {
14783:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14784:         if ($cached) {
14785:             return $alias;
14786:         }
14787:         my $dom = &Apache::lonnet::host_domain($lonid);
14788:         if ($dom ne '') {
14789:             my $cachetime = 60*60*24;
14790:             my %domconfig =
14791:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14792:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14793:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14794:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14795:                 }
14796:             }
14797:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14798:         }
14799:     }
14800:     return;
14801: }
14802: 
14803: sub use_proxy_alias {
14804:     my ($r,$lonid) = @_;
14805:     my $alias = &get_proxy_alias($lonid);
14806:     if ($alias) {
14807:         my $dom = &host_domain($lonid);
14808:         if ($dom ne '') {
14809:             my $proxyinfo = &get_proxy_settings($dom);
14810:             my ($vpnint,$remote_ip);
14811:             if (ref($proxyinfo) eq 'HASH') {
14812:                 $vpnint = $proxyinfo->{'vpnint'};
14813:                 if ($vpnint) {
14814:                     $remote_ip = &get_requestor_ip($r,1,1);
14815:                 }
14816:             }
14817:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14818:                 return $alias;
14819:             }
14820:         }
14821:     }
14822:     return;
14823: }
14824: 
14825: sub alias_sso {
14826:     my ($lonid) = @_;
14827:     if ($lonid eq '') {
14828:         $lonid = $perlvar{'lonHostID'};
14829:     }
14830:     if (!defined(&hostname($lonid))) {
14831:         return;
14832:     }
14833:     if ($lonid ne '') {
14834:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14835:         if ($cached) {
14836:             return $use_alias;
14837:         }
14838:         my $dom = &Apache::lonnet::host_domain($lonid);
14839:         if ($dom ne '') {
14840:             my $cachetime = 60*60*24;
14841:             my %domconfig =
14842:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14843:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14844:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14845:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14846:                 }
14847:             }
14848:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14849:         }
14850:     }
14851:     return;
14852: }
14853: 
14854: sub get_saml_landing {
14855:     my ($lonid) = @_;
14856:     if ($lonid eq '') {
14857:         my $defdom = &default_login_domain();
14858:         my @hosts = &current_machine_ids();
14859:         if (@hosts > 1) {
14860:             foreach my $hostid (@hosts) {
14861:                 if (&host_domain($hostid) eq $defdom) {
14862:                     $lonid = $hostid;
14863:                     last;
14864:                 }
14865:             }
14866:         } else {
14867:             $lonid = $perlvar{'lonHostID'};
14868:         }
14869:         if ($lonid) {
14870:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14871:                 return;
14872:             }
14873:         } else {
14874:             return;
14875:         }
14876:     } elsif (!defined(&hostname($lonid))) {
14877:         return;
14878:     }
14879:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14880:     if ($cached) {
14881:         return $landing;
14882:     }
14883:     my $dom = &Apache::lonnet::host_domain($lonid);
14884:     if ($dom ne '') {
14885:         my $cachetime = 60*60*24;
14886:         my %domconfig =
14887:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
14888:         if (ref($domconfig{'login'}) eq 'HASH') {
14889:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14890:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14891:                     $landing = 1;
14892:                 }
14893:             }
14894:         }
14895:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14896:     }
14897:     return;
14898: }
14899: 
14900: # ------------------------------------------------------------- Declutters URLs
14901: 
14902: sub declutter {
14903:     my $thisfn=shift;
14904:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14905:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14906:         $thisfn=~s{^/home/httpd/html}{};
14907:     }
14908:     $thisfn=~s/^\///;
14909:     $thisfn=~s|^adm/wrapper/||;
14910:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14911:     $thisfn=~s/^res\///;
14912:     $thisfn=~s/^priv\///;
14913:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14914:         $thisfn=~s/\?.+$//;
14915:     }
14916:     return $thisfn;
14917: }
14918: 
14919: # ------------------------------------------------------------- Clutter up URLs
14920: 
14921: sub clutter {
14922:     my $thisfn='/'.&declutter(shift);
14923:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14924: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14925:        $thisfn='/res'.$thisfn; 
14926:     }
14927:     if ($thisfn !~m|^/adm|) {
14928: 	if ($thisfn =~ m|^/ext/|) {
14929: 	    $thisfn='/adm/wrapper'.$thisfn;
14930: 	} else {
14931: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14932: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14933: 	    if ($embstyle eq 'ssi'
14934: 		|| ($embstyle eq 'hdn')
14935: 		|| ($embstyle eq 'rat')
14936: 		|| ($embstyle eq 'prv')
14937: 		|| ($embstyle eq 'ign')) {
14938: 		#do nothing with these
14939: 	    } elsif (($embstyle eq 'img') 
14940: 		|| ($embstyle eq 'emb')
14941: 		|| ($embstyle eq 'wrp')) {
14942: 		$thisfn='/adm/wrapper'.$thisfn;
14943: 	    } elsif ($embstyle eq 'unk'
14944: 		     && $thisfn!~/\.(sequence|page)$/) {
14945: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14946: 	    } else {
14947: #		&logthis("Got a blank emb style");
14948: 	    }
14949: 	}
14950:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14951:         $thisfn='/adm/wrapper'.$thisfn;
14952:     }
14953:     return $thisfn;
14954: }
14955: 
14956: sub clutter_with_no_wrapper {
14957:     my $uri = &clutter(shift);
14958:     if ($uri =~ m-^/adm/-) {
14959: 	$uri =~ s-^/adm/wrapper/-/-;
14960: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14961:     }
14962:     return $uri;
14963: }
14964: 
14965: sub freeze_escape {
14966:     my ($value)=@_;
14967:     if (ref($value)) {
14968: 	$value=&nfreeze($value);
14969: 	return '__FROZEN__'.&escape($value);
14970:     }
14971:     return &escape($value);
14972: }
14973: 
14974: 
14975: sub thaw_unescape {
14976:     my ($value)=@_;
14977:     if ($value =~ /^__FROZEN__/) {
14978: 	substr($value,0,10,undef);
14979: 	$value=&unescape($value);
14980: 	return &thaw($value);
14981:     }
14982:     return &unescape($value);
14983: }
14984: 
14985: sub correct_line_ends {
14986:     my ($result)=@_;
14987:     $$result =~s/\r\n/\n/mg;
14988:     $$result =~s/\r/\n/mg;
14989: }
14990: # ================================================================ Main Program
14991: 
14992: sub goodbye {
14993:    &logthis("Starting Shut down");
14994: #not converted to using infrastruture and probably shouldn't be
14995:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14996: #converted
14997: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14998:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14999: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15000: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15001: #1.1 only
15002: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15003: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15004: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15005: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15006:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15007:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15008:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15009:    &flushcourselogs();
15010:    &logthis("Shutting down");
15011: }
15012: 
15013: sub get_dns {
15014:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15015:     if (!$ignore_cache) {
15016: 	my ($content,$cached)=
15017: 	    &Apache::lonnet::is_cached_new('dns',$url);
15018: 	if ($cached) {
15019: 	    &$func($content,$hashref);
15020: 	    return;
15021: 	}
15022:     }
15023: 
15024:     my %alldns;
15025:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15026:         foreach my $dns (<$config>) {
15027: 	    next if ($dns !~ /^\^(\S*)/x);
15028:             my $line = $1;
15029:             my ($host,$protocol) = split(/:/,$line);
15030:             if ($protocol ne 'https') {
15031:                 $protocol = 'http';
15032:             }
15033: 	    $alldns{$host} = $protocol;
15034:         }
15035:         close($config);
15036:     }
15037:     while (%alldns) {
15038: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15039:         my ($contents,@content);
15040:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15041:             my $command = (split('/',$url))[3];
15042:             my ($dir,$file) = &parse_getdns_url($command,$url);
15043:             delete($alldns{$dns});
15044:             next if (($dir eq '') || ($file eq ''));
15045:             if (open(my $config,'<',"$dir/$file")) {
15046:                 @content = <$config>;
15047:                 close($config);
15048:             }
15049:             if ($url eq '/adm/dns/loncapaCRL') {
15050:                 $contents = join('',@content);
15051:             }
15052:         } else {
15053: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15054:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15055:             delete($alldns{$dns});
15056: 	    next if ($response->is_error());
15057:             if ($url eq '/adm/dns/loncapaCRL') {
15058:                 $contents = $response->content;
15059:             } else {
15060:                 @content = split("\n",$response->content);
15061:             }
15062:         }
15063:         if ($url eq '/adm/dns/loncapaCRL') {
15064:             return &$func($contents);
15065:         } else {
15066: 	    unless ($nocache) {
15067: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15068: 	    }
15069: 	    &$func(\@content,$hashref);
15070:             return;
15071:         }
15072:     }
15073:     my $which = (split('/',$url,4))[3];
15074:     if ($which eq 'loncapaCRL') {
15075:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15076:         if (-e $diskfile) {
15077:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15078:         } else {
15079:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15080:         }
15081:     } else {
15082:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15083:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15084:             my @content = <$config>;
15085:             close($config);
15086:             &$func(\@content,$hashref);
15087:         }
15088:     }
15089:     return;
15090: }
15091: 
15092: # ------------------------------------------------------Get DNS checksums file
15093: sub parse_dns_checksums_tab {
15094:     my ($lines,$hashref) = @_;
15095:     my $lonhost = $perlvar{'lonHostID'};
15096:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
15097:     my $loncaparev = &get_server_loncaparev($machine_dom);
15098:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15099:     my $webconfdir = '/etc/httpd/conf';
15100:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15101:         $webconfdir = '/etc/apache2';
15102:     } elsif ($distro =~ /^sles(\d+)$/) {
15103:         if ($1 >= 10) {
15104:             $webconfdir = '/etc/apache2';
15105:         }
15106:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15107:         if ($1 >= 10.0) {
15108:             $webconfdir = '/etc/apache2';
15109:         }
15110:     }
15111:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15112:     my (%chksum,%revnum);
15113:     if (ref($lines) eq 'ARRAY') {
15114:         chomp(@{$lines});
15115:         my $version = shift(@{$lines});
15116:         if ($version eq $release) {  
15117:             foreach my $line (@{$lines}) {
15118:                 my ($file,$version,$shasum) = split(/,/,$line);
15119:                 if ($file =~ m{^/etc/httpd/conf}) {
15120:                     if ($webconfdir eq '/etc/apache2') {
15121:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15122:                     }
15123:                 }
15124:                 $chksum{$file} = $shasum;
15125:                 $revnum{$file} = $version;
15126:             }
15127:             if (ref($hashref) eq 'HASH') {
15128:                 %{$hashref} = (
15129:                                 sums     => \%chksum,
15130:                                 versions => \%revnum,
15131:                               );
15132:             }
15133:         }
15134:     }
15135:     return;
15136: }
15137: 
15138: sub fetch_dns_checksums {
15139:     my %checksums;
15140:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
15141:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15142:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15143:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15144:              \%checksums);
15145:     return \%checksums;
15146: }
15147: 
15148: sub fetch_crl_pemfile {
15149:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15150: }
15151: 
15152: sub save_crl_pem {
15153:     my ($content) = @_;
15154:     my ($msg,$hadchanges);
15155:     if ($content ne '') {
15156:         my $now = time;
15157:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15158:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15159:         if (open(my $fh,'>',"$tmpcrl")) {
15160:             print $fh $content;
15161:             close($fh);
15162:             if (-e $lonca) {
15163:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15164:                     my $check = <PIPE>;
15165:                     close(PIPE);
15166:                     chomp($check);
15167:                     if ($check eq 'verify OK') {
15168:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15169:                         my $backup;
15170:                         if (-e $dest) {
15171:                             if (&File::Copy::move($dest,"$dest.bak")) {
15172:                                 $backup = 'ok';
15173:                             }
15174:                         }
15175:                         if (&File::Copy::move($tmpcrl,$dest)) {
15176:                             $msg = 'ok';
15177:                             if ($backup) {
15178:                                 my (%oldnums,%newnums);
15179:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15180:                                     while (<PIPE>) {
15181:                                         $oldnums{(split(/:/))[1]} = 1;
15182:                                     }
15183:                                     close(PIPE);
15184:                                 }
15185:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15186:                                     while(<PIPE>) {
15187:                                         $newnums{(split(/:/))[1]} = 1;
15188:                                     }
15189:                                     close(PIPE);
15190:                                 }
15191:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15192:                                     unless (exists($oldnums{$key})) {
15193:                                         $hadchanges = 1;
15194:                                         last;
15195:                                     }
15196:                                 }
15197:                                 unless ($hadchanges) {
15198:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15199:                                         unless (exists($newnums{$key})) {
15200:                                             $hadchanges = 1;
15201:                                             last;
15202:                                         }
15203:                                     }
15204:                                 }
15205:                             }
15206:                         }
15207:                     } else {
15208:                         unlink($tmpcrl);
15209:                     }
15210:                 } else {
15211:                     unlink($tmpcrl);
15212:                 }
15213:             } else {
15214:                 unlink($tmpcrl);
15215:             }
15216:         }
15217:     }
15218:     return ($msg,$hadchanges);
15219: }
15220: 
15221: sub parse_getdns_url {
15222:     my ($command,$url) = @_;
15223:     my $dir = $perlvar{'lonTabDir'};
15224:     my $file;
15225:     if ($command eq 'hosts') {
15226:         $file = 'dns_hosts.tab';
15227:     } elsif ($command eq 'domain') {
15228:         $file = 'dns_domain.tab';
15229:     } elsif ($command eq 'checksums') {
15230:         my $version = (split('/',$url))[4];
15231:         $file = "dns_checksums/$version.tab",
15232:     } elsif ($command eq 'loncapaCRL') {
15233:         $dir = $perlvar{'lonCertificateDirectory'};
15234:         $file = $perlvar{'lonnetCertRevocationList'};
15235:     }
15236:     return ($dir,$file);
15237: }
15238: 
15239: # ------------------------------------------------------------ Read domain file
15240: {
15241:     my $loaded;
15242:     my %domain;
15243: 
15244:     sub parse_domain_tab {
15245: 	my ($lines) = @_;
15246: 	foreach my $line (@$lines) {
15247: 	    next if ($line =~ /^(\#|\s*$ )/x);
15248: 
15249: 	    chomp($line);
15250: 	    my ($name,@elements) = split(/:/,$line,9);
15251: 	    my %this_domain;
15252: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15253: 			       'lang_def', 'city', 'longi', 'lati',
15254: 			       'primary') {
15255: 		$this_domain{$field} = shift(@elements);
15256: 	    }
15257: 	    $domain{$name} = \%this_domain;
15258: 	}
15259:     }
15260: 
15261:     sub reset_domain_info {
15262: 	undef($loaded);
15263: 	undef(%domain);
15264:     }
15265: 
15266:     sub load_domain_tab {
15267: 	my ($ignore_cache,$nocache) = @_;
15268: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15269: 	my $fh;
15270: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15271: 	    my @lines = <$fh>;
15272: 	    &parse_domain_tab(\@lines);
15273: 	}
15274: 	close($fh);
15275: 	$loaded = 1;
15276:     }
15277: 
15278:     sub domain {
15279: 	&load_domain_tab() if (!$loaded);
15280: 
15281: 	my ($name,$what) = @_;
15282: 	return if ( !exists($domain{$name}) );
15283: 
15284: 	if (!$what) {
15285: 	    return $domain{$name}{'description'};
15286: 	}
15287: 	return $domain{$name}{$what};
15288:     }
15289: 
15290:     sub domain_info {
15291:         &load_domain_tab() if (!$loaded);
15292:         return %domain;
15293:     }
15294: 
15295: }
15296: 
15297: 
15298: # ------------------------------------------------------------- Read hosts file
15299: {
15300:     my %hostname;
15301:     my %hostdom;
15302:     my %libserv;
15303:     my $loaded;
15304:     my %name_to_host;
15305:     my %internetdom;
15306:     my %LC_dns_serv;
15307: 
15308:     sub parse_hosts_tab {
15309: 	my ($file) = @_;
15310: 	foreach my $configline (@$file) {
15311: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15312:             chomp($configline);
15313: 	    if ($configline =~ /^\^/) {
15314:                 if ($configline =~ /^\^([\w.\-]+)/) {
15315:                     $LC_dns_serv{$1} = 1;
15316:                 }
15317:                 next;
15318:             }
15319: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15320: 	    $name=~s/\s//g;
15321: 	    if ($id && $domain && $role && $name) {
15322:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15323:                     my $curr = $hostname{$id};
15324:                     my $skip;
15325:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15326:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15327:                             $skip = 1;
15328:                         } else {
15329:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15330:                         }
15331:                     }
15332:                     unless ($skip) {
15333:                         push(@{$name_to_host{$name}},$id);
15334:                     }
15335:                 } else {
15336:                     push(@{$name_to_host{$name}},$id);
15337:                 }
15338: 		$hostname{$id}=$name;
15339: 		$hostdom{$id}=$domain;
15340: 		if ($role eq 'library') { $libserv{$id}=$name; }
15341:                 if (defined($protocol)) {
15342:                     if ($protocol eq 'https') {
15343:                         $protocol{$id} = $protocol;
15344:                     } else {
15345:                         $protocol{$id} = 'http'; 
15346:                     }
15347:                 } else {
15348:                     $protocol{$id} = 'http';
15349:                 }
15350:                 if (defined($intdom)) {
15351:                     $internetdom{$id} = $intdom;
15352:                 }
15353: 	    }
15354: 	}
15355:     }
15356:     
15357:     sub reset_hosts_info {
15358: 	&purge_remembered();
15359: 	&reset_domain_info();
15360: 	&reset_hosts_ip_info();
15361:         undef(%internetdom);
15362: 	undef(%name_to_host);
15363: 	undef(%hostname);
15364: 	undef(%hostdom);
15365: 	undef(%libserv);
15366: 	undef($loaded);
15367:     }
15368: 
15369:     sub load_hosts_tab {
15370: 	my ($ignore_cache,$nocache) = @_;
15371: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15372: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15373: 	my @config = <$config>;
15374: 	&parse_hosts_tab(\@config);
15375: 	close($config);
15376: 	$loaded=1;
15377:     }
15378: 
15379:     sub hostname {
15380: 	&load_hosts_tab() if (!$loaded);
15381: 
15382: 	my ($lonid) = @_;
15383: 	return $hostname{$lonid};
15384:     }
15385: 
15386:     sub all_hostnames {
15387: 	&load_hosts_tab() if (!$loaded);
15388: 
15389: 	return %hostname;
15390:     }
15391: 
15392:     sub all_names {
15393:         my ($ignore_cache,$nocache) = @_;
15394: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15395: 
15396: 	return %name_to_host;
15397:     }
15398: 
15399:     sub all_host_domain {
15400:         &load_hosts_tab() if (!$loaded);
15401:         return %hostdom;
15402:     }
15403: 
15404:     sub all_host_intdom {
15405:         &load_hosts_tab() if (!$loaded);
15406:         return %internetdom;
15407:     }
15408: 
15409:     sub is_library {
15410: 	&load_hosts_tab() if (!$loaded);
15411: 
15412: 	return exists($libserv{$_[0]});
15413:     }
15414: 
15415:     sub all_library {
15416: 	&load_hosts_tab() if (!$loaded);
15417: 
15418: 	return %libserv;
15419:     }
15420: 
15421:     sub unique_library {
15422: 	#2x reverse removes all hostnames that appear more than once
15423:         my %unique = reverse &all_library();
15424:         return reverse %unique;
15425:     }
15426: 
15427:     sub get_servers {
15428: 	&load_hosts_tab() if (!$loaded);
15429: 
15430: 	my ($domain,$type) = @_;
15431: 	my %possible_hosts = ($type eq 'library') ? %libserv
15432: 	                                          : %hostname;
15433: 	my %result;
15434: 	if (ref($domain) eq 'ARRAY') {
15435: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15436: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15437: 		    $result{$host} = $hostname;
15438: 		}
15439: 	    }
15440: 	} else {
15441: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15442: 		if ($hostdom{$host} eq $domain) {
15443: 		    $result{$host} = $hostname;
15444: 		}
15445: 	    }
15446: 	}
15447: 	return %result;
15448:     }
15449: 
15450:     sub get_unique_servers {
15451:         my %unique = reverse &get_servers(@_);
15452: 	return reverse %unique;
15453:     }
15454: 
15455:     sub host_domain {
15456: 	&load_hosts_tab() if (!$loaded);
15457: 
15458: 	my ($lonid) = @_;
15459: 	return $hostdom{$lonid};
15460:     }
15461: 
15462:     sub all_domains {
15463: 	&load_hosts_tab() if (!$loaded);
15464: 
15465: 	my %seen;
15466: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15467: 	return @uniq;
15468:     }
15469: 
15470:     sub internet_dom {
15471:         &load_hosts_tab() if (!$loaded);
15472: 
15473:         my ($lonid) = @_;
15474:         return $internetdom{$lonid};
15475:     }
15476: 
15477:     sub is_LC_dns {
15478:         &load_hosts_tab() if (!$loaded);
15479: 
15480:         my ($hostname) = @_;
15481:         return exists($LC_dns_serv{$hostname});
15482:     }
15483: 
15484: }
15485: 
15486: { 
15487:     my %iphost;
15488:     my %name_to_ip;
15489:     my %lonid_to_ip;
15490: 
15491:     sub get_hosts_from_ip {
15492: 	my ($ip) = @_;
15493: 	my %iphosts = &get_iphost();
15494: 	if (ref($iphosts{$ip})) {
15495: 	    return @{$iphosts{$ip}};
15496: 	}
15497: 	return;
15498:     }
15499:     
15500:     sub reset_hosts_ip_info {
15501: 	undef(%iphost);
15502: 	undef(%name_to_ip);
15503: 	undef(%lonid_to_ip);
15504:     }
15505: 
15506:     sub get_host_ip {
15507: 	my ($lonid) = @_;
15508: 	if (exists($lonid_to_ip{$lonid})) {
15509: 	    return $lonid_to_ip{$lonid};
15510: 	}
15511: 	my $name=&hostname($lonid);
15512:    	my $ip = gethostbyname($name);
15513: 	return if (!$ip || length($ip) ne 4);
15514: 	$ip=inet_ntoa($ip);
15515: 	$name_to_ip{$name}   = $ip;
15516: 	$lonid_to_ip{$lonid} = $ip;
15517: 	return $ip;
15518:     }
15519:     
15520:     sub get_iphost {
15521: 	my ($ignore_cache,$nocache) = @_;
15522: 
15523: 	if (!$ignore_cache) {
15524: 	    if (%iphost) {
15525: 		return %iphost;
15526: 	    }
15527: 	    my ($ip_info,$cached)=
15528: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15529: 	    if ($cached) {
15530: 		%iphost      = %{$ip_info->[0]};
15531: 		%name_to_ip  = %{$ip_info->[1]};
15532: 		%lonid_to_ip = %{$ip_info->[2]};
15533: 		return %iphost;
15534: 	    }
15535: 	}
15536: 
15537: 	# get yesterday's info for fallback
15538: 	my %old_name_to_ip;
15539: 	my ($ip_info,$cached)=
15540: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15541: 	if ($cached) {
15542: 	    %old_name_to_ip = %{$ip_info->[1]};
15543: 	}
15544: 
15545: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15546: 	foreach my $name (keys(%name_to_host)) {
15547: 	    my $ip;
15548: 	    if (!exists($name_to_ip{$name})) {
15549: 		$ip = gethostbyname($name);
15550: 		if (!$ip || length($ip) ne 4) {
15551: 		    if (defined($old_name_to_ip{$name})) {
15552: 			$ip = $old_name_to_ip{$name};
15553: 			&logthis("Can't find $name defaulting to old $ip");
15554: 		    } else {
15555: 			&logthis("Name $name no IP found");
15556: 			next;
15557: 		    }
15558: 		} else {
15559: 		    $ip=inet_ntoa($ip);
15560: 		}
15561: 		$name_to_ip{$name} = $ip;
15562: 	    } else {
15563: 		$ip = $name_to_ip{$name};
15564: 	    }
15565: 	    foreach my $id (@{ $name_to_host{$name} }) {
15566: 		$lonid_to_ip{$id} = $ip;
15567: 	    }
15568: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15569: 	}
15570:         unless ($nocache) {
15571: 	    &do_cache_new('iphost','iphost',
15572: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15573: 		          48*60*60);
15574:         }
15575: 
15576: 	return %iphost;
15577:     }
15578: 
15579:     #
15580:     #  Given a DNS returns the loncapa host name for that DNS 
15581:     # 
15582:     sub host_from_dns {
15583:         my ($dns) = @_;
15584:         my @hosts;
15585:         my $ip;
15586: 
15587:         if (exists($name_to_ip{$dns})) {
15588:             $ip = $name_to_ip{$dns};
15589:         }
15590:         if (!$ip) {
15591:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15592:             if (length($ip) == 4) { 
15593: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15594:             }
15595:         }
15596:         if ($ip) {
15597: 	    @hosts = get_hosts_from_ip($ip);
15598: 	    return $hosts[0];
15599:         }
15600:         return undef;
15601:     }
15602: 
15603:     sub get_internet_names {
15604:         my ($lonid) = @_;
15605:         return if ($lonid eq '');
15606:         my ($idnref,$cached)=
15607:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15608:         if ($cached) {
15609:             return $idnref;
15610:         }
15611:         my $ip = &get_host_ip($lonid);
15612:         my @hosts = &get_hosts_from_ip($ip);
15613:         my %iphost = &get_iphost();
15614:         my (@idns,%seen);
15615:         foreach my $id (@hosts) {
15616:             my $dom = &host_domain($id);
15617:             my $prim_id = &domain($dom,'primary');
15618:             my $prim_ip = &get_host_ip($prim_id);
15619:             next if ($seen{$prim_ip});
15620:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15621:                 foreach my $id (@{$iphost{$prim_ip}}) {
15622:                     my $intdom = &internet_dom($id);
15623:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15624:                         push(@idns,$intdom);
15625:                     }
15626:                 }
15627:             }
15628:             $seen{$prim_ip} = 1;
15629:         }
15630:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15631:     }
15632: 
15633: }
15634: 
15635: sub all_loncaparevs {
15636:     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);
15637: }
15638: 
15639: # ---------------------------------------------------------- Read loncaparev table
15640: {
15641:     sub load_loncaparevs { 
15642:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15643:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15644:                 while (my $configline=<$config>) {
15645:                     chomp($configline);
15646:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15647:                     $loncaparevs{$hostid}=$loncaparev;
15648:                 }
15649:                 close($config);
15650:             }
15651:         }
15652:     }
15653: }
15654: 
15655: # ---------------------------------------------------------- Read serverhostID table
15656: {
15657:     sub load_serverhomeIDs {
15658:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15659:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15660:                 while (my $configline=<$config>) {
15661:                     chomp($configline);
15662:                     my ($name,$id)=split(/:/,$configline);
15663:                     $serverhomeIDs{$name}=$id;
15664:                 }
15665:                 close($config);
15666:             }
15667:         }
15668:     }
15669: }
15670: 
15671: 
15672: BEGIN {
15673: 
15674: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15675:     unless ($readit) {
15676: {
15677:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15678:     %perlvar = (%perlvar,%{$configvars});
15679: }
15680: 
15681: 
15682: # ------------------------------------------------------ Read spare server file
15683: {
15684:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15685: 
15686:     while (my $configline=<$config>) {
15687:        chomp($configline);
15688:        if ($configline) {
15689: 	   my ($host,$type) = split(':',$configline,2);
15690: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15691: 	   push(@{ $spareid{$type} }, $host);
15692:        }
15693:     }
15694:     close($config);
15695: }
15696: # ------------------------------------------------------------ Read permissions
15697: {
15698:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15699: 
15700:     while (my $configline=<$config>) {
15701: 	chomp($configline);
15702: 	if ($configline) {
15703: 	    my ($role,$perm)=split(/ /,$configline);
15704: 	    if ($perm ne '') { $pr{$role}=$perm; }
15705: 	}
15706:     }
15707:     close($config);
15708: }
15709: 
15710: # -------------------------------------------- Read plain texts for permissions
15711: {
15712:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15713: 
15714:     while (my $configline=<$config>) {
15715: 	chomp($configline);
15716: 	if ($configline) {
15717: 	    my ($short,@plain)=split(/:/,$configline);
15718:             %{$prp{$short}} = ();
15719: 	    if (@plain > 0) {
15720:                 $prp{$short}{'std'} = $plain[0];
15721:                 for (my $i=1; $i<@plain; $i++) {
15722:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15723:                 }
15724:             }
15725: 	}
15726:     }
15727:     close($config);
15728: }
15729: 
15730: # ---------------------------------------------------------- Read package table
15731: {
15732:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15733: 
15734:     while (my $configline=<$config>) {
15735: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15736: 	chomp($configline);
15737: 	my ($short,$plain)=split(/:/,$configline);
15738: 	my ($pack,$name)=split(/\&/,$short);
15739: 	if ($plain ne '') {
15740: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15741: 	    $packagetab{$short}=$plain; 
15742: 	}
15743:     }
15744:     close($config);
15745: }
15746: 
15747: # ---------------------------------------------------------- Read loncaparev table
15748: 
15749: &load_loncaparevs();
15750: 
15751: # ---------------------------------------------------------- Read serverhostID table
15752: 
15753: &load_serverhomeIDs();
15754: 
15755: # ---------------------------------------------------------- Read releaseslist XML
15756: {
15757:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15758:     if (-e $file) {
15759:         my $parser = HTML::LCParser->new($file);
15760:         while (my $token = $parser->get_token()) {
15761:             if ($token->[0] eq 'S') {
15762:                 my $item = $token->[1];
15763:                 my $name = $token->[2]{'name'};
15764:                 my $value = $token->[2]{'value'};
15765:                 my $valuematch = $token->[2]{'valuematch'};
15766:                 my $namematch = $token->[2]{'namematch'};
15767:                 if ($item eq 'parameter') {
15768:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15769:                         my $release = $parser->get_text();
15770:                         $release =~ s/(^\s*|\s*$ )//gx;
15771:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15772:                     }
15773:                 } elsif ($item ne '' && $name ne '') {
15774:                     my $release = $parser->get_text();
15775:                     $release =~ s/(^\s*|\s*$ )//gx;
15776:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15777:                 }
15778:             }
15779:         }
15780:     }
15781: }
15782: 
15783: # ---------------------------------------------------------- Read managers table
15784: {
15785:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15786:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15787:             while (my $configline=<$config>) {
15788:                 chomp($configline);
15789:                 next if ($configline =~ /^\#/);
15790:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15791:                     $managerstab{$configline} = 1;
15792:                 }
15793:             }
15794:             close($config);
15795:         }
15796:     }
15797: }
15798: 
15799: # ------------- set up temporary directory
15800: {
15801:     $tmpdir = LONCAPA::tempdir();
15802: 
15803: }
15804: 
15805: # ------------- set default texengine (domain default overrides this)
15806: {
15807:     $deftex = LONCAPA::texengine();
15808: }
15809: 
15810: # ------------- set default minimum length for passwords for internal auth users
15811: {
15812:     $passwdmin = LONCAPA::passwd_min();
15813: }
15814: 
15815: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15816: 				'compress_threshold'=> 20_000,
15817:  			        });
15818: 
15819: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15820: $dumpcount=0;
15821: $locknum=0;
15822: 
15823: &logtouch();
15824: &logthis('<font color="yellow">INFO: Read configuration</font>');
15825: $readit=1;
15826:     {
15827: 	use integer;
15828: 	my $test=(2**32)+1;
15829: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15830: 	&logthis(" Detected 64bit platform ($_64bit)");
15831:     }
15832: }
15833: }
15834: 
15835: 1;
15836: __END__
15837: 
15838: =pod
15839: 
15840: =head1 NAME
15841: 
15842: Apache::lonnet - Subroutines to ask questions about things in the network.
15843: 
15844: =head1 SYNOPSIS
15845: 
15846: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15847: 
15848:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15849: 
15850: Common parameters:
15851: 
15852: =over 4
15853: 
15854: =item *
15855: 
15856: $uname : an internal username (if $cname expecting a course Id specifically)
15857: 
15858: =item *
15859: 
15860: $udom : a domain (if $cdom expecting a course's domain specifically)
15861: 
15862: =item *
15863: 
15864: $symb : a resource instance identifier
15865: 
15866: =item *
15867: 
15868: $namespace : the name of a .db file that contains the data needed or
15869: being set.
15870: 
15871: =back
15872: 
15873: =head1 OVERVIEW
15874: 
15875: lonnet provides subroutines which interact with the
15876: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15877: about classes, users, and resources.
15878: 
15879: For many of these objects you can also use this to store data about
15880: them or modify them in various ways.
15881: 
15882: =head2 Symbs
15883: 
15884: To identify a specific instance of a resource, LON-CAPA uses symbols
15885: or "symbs"X<symb>. These identifiers are built from the URL of the
15886: map, the resource number of the resource in the map, and the URL of
15887: the resource itself. The latter is somewhat redundant, but might help
15888: if maps change.
15889: 
15890: An example is
15891: 
15892:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15893: 
15894: The respective map entry is
15895: 
15896:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15897:   title="Problem 2">
15898:  </resource>
15899: 
15900: Symbs are used by the random number generator, as well as to store and
15901: restore data specific to a certain instance of for example a problem.
15902: 
15903: =head2 Storing And Retrieving Data
15904: 
15905: X<store()>X<cstore()>X<restore()>Three of the most important functions
15906: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15907: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15908: is is the non-critical message twin of cstore. These functions are for
15909: handlers to store a perl hash to a user's permanent data space in an
15910: easy manner, and to retrieve it again on another call. It is expected
15911: that a handler would use this once at the beginning to retrieve data,
15912: and then again once at the end to send only the new data back.
15913: 
15914: The data is stored in the user's data directory on the user's
15915: homeserver under the ID of the course.
15916: 
15917: The hash that is returned by restore will have all of the previous
15918: value for all of the elements of the hash.
15919: 
15920: Example:
15921: 
15922:  #creating a hash
15923:  my %hash;
15924:  $hash{'foo'}='bar';
15925: 
15926:  #storing it
15927:  &Apache::lonnet::cstore(\%hash);
15928: 
15929:  #changing a value
15930:  $hash{'foo'}='notbar';
15931: 
15932:  #adding a new value
15933:  $hash{'bar'}='foo';
15934:  &Apache::lonnet::cstore(\%hash);
15935: 
15936:  #retrieving the hash
15937:  my %history=&Apache::lonnet::restore();
15938: 
15939:  #print the hash
15940:  foreach my $key (sort(keys(%history))) {
15941:    print("\%history{$key} = $history{$key}");
15942:  }
15943: 
15944: Will print out:
15945: 
15946:  %history{1:foo} = bar
15947:  %history{1:keys} = foo:timestamp
15948:  %history{1:timestamp} = 990455579
15949:  %history{2:bar} = foo
15950:  %history{2:foo} = notbar
15951:  %history{2:keys} = foo:bar:timestamp
15952:  %history{2:timestamp} = 990455580
15953:  %history{bar} = foo
15954:  %history{foo} = notbar
15955:  %history{timestamp} = 990455580
15956:  %history{version} = 2
15957: 
15958: Note that the special hash entries C<keys>, C<version> and
15959: C<timestamp> were added to the hash. C<version> will be equal to the
15960: total number of versions of the data that have been stored. The
15961: C<timestamp> attribute will be the UNIX time the hash was
15962: stored. C<keys> is available in every historical section to list which
15963: keys were added or changed at a specific historical revision of a
15964: hash.
15965: 
15966: B<Warning>: do not store the hash that restore returns directly. This
15967: will cause a mess since it will restore the historical keys as if the
15968: were new keys. I.E. 1:foo will become 1:1:foo etc.
15969: 
15970: Calling convention:
15971: 
15972:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15973:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15974: 
15975: For more detailed information, see lonnet specific documentation.
15976: 
15977: =head1 RETURN MESSAGES
15978: 
15979: =over 4
15980: 
15981: =item * B<con_lost>: unable to contact remote host
15982: 
15983: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15984: when the connection is brought back up
15985: 
15986: =item * B<con_failed>: unable to contact remote host and unable to save message
15987: for later delivery
15988: 
15989: =item * B<error:>: an error a occurred, a description of the error follows the :
15990: 
15991: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15992: that was requested
15993: 
15994: =back
15995: 
15996: =head1 PUBLIC SUBROUTINES
15997: 
15998: =head2 Session Environment Functions
15999: 
16000: =over 4
16001: 
16002: =item * 
16003: X<appenv()>
16004: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16005: the user envirnoment file, and will be restored for each access this
16006: user makes during this session, also modifies the %env for the current
16007: process. Optional rolesarrayref - if defined contains a reference to an array
16008: of roles which are exempt from the restriction on modifying user.role entries 
16009: in the user's environment.db and in %env.    
16010: 
16011: =item *
16012: X<delenv()>
16013: B<delenv($delthis,$regexp)>: removes all items from the session
16014: environment file that begin with $delthis. If the 
16015: optional second arg - $regexp - is true, $delthis is treated as a 
16016: regular expression, otherwise \Q$delthis\E is used. 
16017: The values are also deleted from the current processes %env.
16018: 
16019: =item * get_env_multiple($name) 
16020: 
16021: gets $name from the %env hash, it seemlessly handles the cases where multiple
16022: values may be defined and end up as an array ref.
16023: 
16024: returns an array of values
16025: 
16026: =back
16027: 
16028: =head2 User Information
16029: 
16030: =over 4
16031: 
16032: =item *
16033: X<queryauthenticate()>
16034: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16035: authentication scheme
16036: 
16037: =item *
16038: X<authenticate()>
16039: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16040: authenticate user from domain's lib servers (first use the current
16041: one). C<$upass> should be the users password.
16042: $checkdefauth is optional (value is 1 if a check should be made to
16043:    authenticate user using default authentication method, and allow
16044:    account creation if username does not have account in the domain).
16045: $clientcancheckhost is optional (value is 1 if checking whether the
16046:    server can host will occur on the client side in lonauth.pm).   
16047: 
16048: =item *
16049: X<homeserver()>
16050: B<homeserver($uname,$udom)>: find the server which has
16051: the user's directory and files (there must be only one), this caches
16052: the answer, and also caches if there is a borken connection.
16053: 
16054: =item *
16055: X<idget()>
16056: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16057: a list of student/employee IDs or clicker IDs
16058: (student/employee IDs are a unique resource in a domain, there must be 
16059: only 1 ID per username, and only 1 username per ID in a specific domain).
16060: clickerIDs are not necessarily unique, as students might share clickers.
16061: (returns hash: id=>name,id=>name)
16062: 
16063: =item *
16064: X<idrget()>
16065: B<idrget($udom,@unames)>: find the IDs behind a list of
16066: usernames (returns hash: name=>id,name=>id)
16067: 
16068: =item *
16069: X<idput()>
16070: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16071: names and associated student/employee IDs or clicker IDs.
16072: 
16073: =item *
16074: X<iddel()>
16075: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16076: student/employee ID or clicker ID username look-ups from domain.
16077: The homeserver ($uhome) and namespace ($namespace) are optional.
16078: If no $uhome is provided, it will be determined usig &homeserver()
16079: for each user.  If no $namespace is provided, the default is ids.
16080: 
16081: =item *
16082: X<updateclickers()>
16083: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16084: clicker ID-to-username look-ups in clickers.db on library server.
16085: Permitted actions are add or del (i.e., add or delete). The 
16086: clickers.db contains clickerID as keys (escaped), and each corresponding
16087: value is an escaped comma-separated list of usernames (for whom the
16088: library server is the homeserver), who registered that particular ID.
16089: If $critical is true, the update will be sent via &critical, otherwise
16090: &reply() will be used.
16091: 
16092: =item *
16093: X<rolesinit()>
16094: B<rolesinit($udom,$username)>: get user privileges.
16095: returns user role, first access and timer interval hashes
16096: 
16097: =item *
16098: X<privileged()>
16099: B<privileged($username,$domain)>: returns a true if user has a
16100: privileged and active role (i.e. su or dc), false otherwise.
16101: 
16102: =item *
16103: X<getsection()>
16104: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16105: course $cname, return section name/number or '' for "not in course"
16106: and '-1' for "no section"
16107: 
16108: =item *
16109: X<userenvironment()>
16110: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16111: passed in @what from the requested user's environment, returns a hash
16112: 
16113: =item * 
16114: X<userlog_query()>
16115: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16116: activity.log file. %filters defines filters applied when parsing the
16117: log file. These can be start or end timestamps, or the type of action
16118: - log to look for Login or Logout events, check for Checkin or
16119: Checkout, role for role selection. The response is in the form
16120: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16121: escaped strings of the action recorded in the activity.log file.
16122: 
16123: =back
16124: 
16125: =head2 User Roles
16126: 
16127: =over 4
16128: 
16129: =item *
16130: 
16131: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16132: returns codes for allowed actions.
16133: 
16134: The first argument is required, all others are optional.
16135: 
16136: $priv is the privilege being checked.
16137: $uri contains additional information about what is being checked for access (e.g.,
16138: URL, course ID etc.). 
16139: $symb is the unique resource instance identifier in a course; if needed,
16140: but not provided, it will be retrieved via a call to &symbread(). 
16141: $role is the role for which a priv is being checked (only used if priv is evb). 
16142: $clientip is the user's IP address (only used when checking for access to portfolio 
16143: files).
16144: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16145: prevents recursive calls to &allowed.
16146: 
16147:  F: full access
16148:  U,I,K: authentication modes (cxx only)
16149:  '': forbidden
16150:  1: user needs to choose course
16151:  2: browse allowed
16152:  A: passphrase authentication needed
16153:  B: access temporarily blocked because of a blocking event in a course.
16154:  D: access blocked because access is required via session initiated via deep-link 
16155: 
16156: =item *
16157: 
16158: constructaccess($url,$setpriv) : check for access to construction space URL
16159: 
16160: See if the owner domain and name in the URL match those in the
16161: expected environment.  If so, return three element list
16162: ($ownername,$ownerdomain,$ownerhome).
16163: 
16164: Otherwise return the null string.
16165: 
16166: If second argument 'setpriv' is true, it assigns the privileges,
16167: and returns the same three element list, unless the owner has
16168: blocked "ad hoc" Domain Coordinator access to the Author Space,
16169: in which case the null string is returned.
16170: 
16171: =item *
16172: 
16173: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16174: define a custom role rolename set privileges in format of lonTabs/roles.tab
16175: for system, domain, and course level. $uname and $udom are optional (current
16176: user's username and domain will be used when either of $uname or $udom are absent.
16177: 
16178: =item *
16179: 
16180: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16181: (rolesplain.tab); plain text explanation of a user role term.
16182: $type is Course (default) or Community.
16183: If $forcedefault evaluates to true, text returned will be default 
16184: text for $type. Otherwise, if this is a course, the text returned 
16185: will be a custom name for the role (if defined in the course's 
16186: environment).  If no custom name is defined the default is returned.
16187:    
16188: =item *
16189: 
16190: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16191: All arguments are optional. Returns a hash of a roles, either for
16192: co-author/assistant author roles for a user's Construction Space
16193: (default), or if $context is 'userroles', roles for the user himself,
16194: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16195: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16196: For each key, value is set to colon-separated start and end times for
16197: the role.  If no username and domain are specified, will default to
16198: current user/domain. Types, roles, and roledoms are references to arrays
16199: of role statuses (active, future or previous), roles 
16200: (e.g., cc,in, st etc.) and domains of the roles which can be used
16201: to restrict the list of roles reported. If no array ref is 
16202: provided for types, will default to return only active roles.
16203: 
16204: =item *
16205: 
16206: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16207: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16208: 
16209: Additional optional arguments are: $type (if role checking is to be restricted 
16210: to certain user status types -- previous (expired roles), active (currently
16211: available roles) or future (roles available in the future), and
16212: $hideprivileged -- if true will not report course roles for users who
16213: have active Domain Coordinator role in course's domain or in additional
16214: domains (specified in 'Domains to check for privileged users' in course
16215: environment -- set via:  Course Settings -> Classlists and staff listing).
16216: 
16217: =item *
16218: 
16219: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16220: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16221: $possdomains and $possroles are optional array refs -- to domains to check and
16222: roles to check.  If $possdomains is not specified, a dump will be done of the
16223: users' roles.db to check for a dc or su role in any domain. This can be
16224: time consuming if &privileged is called repeatedly (e.g., when displaying a
16225: classlist), so in such cases, supplying a $possdomains array is preferred, as
16226: this then allows &privileged_by_domain() to be used, which caches the identity
16227: of privileged users, eliminating the need for repeated calls to &dump().
16228: 
16229: =item *
16230: 
16231: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16232: where the outer hash keys are domains specified in the $possdomains array ref,
16233: next inner hash keys are privileged roles specified in the $roles array ref,
16234: and the innermost hash contains key = value pairs for username:domain = end:start
16235: for active or future "privileged" users with that role in that domain. To avoid
16236: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16237: innerhash are cached using priv_$role and $dom as the identifiers.
16238: 
16239: =back
16240: 
16241: =head2 User Modification
16242: 
16243: =over 4
16244: 
16245: =item *
16246: 
16247: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16248: user for the level given by URL.  Optional start and end dates (leave empty
16249: string or zero for "no date")
16250: 
16251: =item *
16252: 
16253: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16254: change a users, password, possible return values are: ok,
16255: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16256: refused
16257: 
16258: =item *
16259: 
16260: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16261: 
16262: =item *
16263: 
16264: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16265:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16266: 
16267: will update user information (firstname,middlename,lastname,generation,
16268: permanentemail), and if forceid is true, student/employee ID also.
16269: A user's institutional affiliation(s) can also be updated.
16270: User information fields will not be overwritten with empty entries 
16271: unless the field is included in the $candelete array reference.
16272: This array is included when a single user is modified via "Manage Users",
16273: or when Autoupdate.pl is run by cron in a domain.
16274: 
16275: =item *
16276: 
16277: modifystudent
16278: 
16279: modify a student's enrollment and identification information.
16280: The course id is resolved based on the current user's environment.  
16281: This means the invoking user must be a course coordinator or otherwise
16282: associated with a course.
16283: 
16284: This call is essentially a wrapper for lonnet::modifyuser and
16285: lonnet::modify_student_enrollment
16286: 
16287: Inputs: 
16288: 
16289: =over 4
16290: 
16291: =item B<$udom> Student's loncapa domain
16292: 
16293: =item B<$uname> Student's loncapa login name
16294: 
16295: =item B<$uid> Student/Employee ID
16296: 
16297: =item B<$umode> Student's authentication mode
16298: 
16299: =item B<$upass> Student's password
16300: 
16301: =item B<$first> Student's first name
16302: 
16303: =item B<$middle> Student's middle name
16304: 
16305: =item B<$last> Student's last name
16306: 
16307: =item B<$gene> Student's generation
16308: 
16309: =item B<$usec> Student's section in course
16310: 
16311: =item B<$end> Unix time of the roles expiration
16312: 
16313: =item B<$start> Unix time of the roles start date
16314: 
16315: =item B<$forceid> If defined, allow $uid to be changed
16316: 
16317: =item B<$desiredhome> server to use as home server for student
16318: 
16319: =item B<$email> Student's permanent e-mail address
16320: 
16321: =item B<$type> Type of enrollment (auto or manual)
16322: 
16323: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16324: 
16325: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16326: 
16327: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16328: 
16329: =item B<$context> role change context (shown in User Management Logs display in a course)
16330: 
16331: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16332: 
16333: =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.
16334: 
16335: =back
16336: 
16337: =item *
16338: 
16339: modify_student_enrollment
16340: 
16341: Change a student's enrollment status in a class.  The environment variable
16342: 'role.request.course' must be defined for this function to proceed.
16343: 
16344: Inputs:
16345: 
16346: =over 4
16347: 
16348: =item $udom, student's domain
16349: 
16350: =item $uname, student's name
16351: 
16352: =item $uid, student's user id
16353: 
16354: =item $first, student's first name
16355: 
16356: =item $middle
16357: 
16358: =item $last
16359: 
16360: =item $gene
16361: 
16362: =item $usec
16363: 
16364: =item $end
16365: 
16366: =item $start
16367: 
16368: =item $type
16369: 
16370: =item $locktype
16371: 
16372: =item $cid
16373: 
16374: =item $selfenroll
16375: 
16376: =item $context
16377: 
16378: =item $credits, number of credits student will earn from this class
16379: 
16380: =item $instsec, institutional course section code for student
16381: 
16382: =back
16383: 
16384: 
16385: =item *
16386: 
16387: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16388: custom role; give a custom role to a user for the level given by URL.  Specify
16389: name and domain of role author, and role name
16390: 
16391: =item *
16392: 
16393: revokerole($udom,$uname,$url,$role) : revoke a role for url
16394: 
16395: =item *
16396: 
16397: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16398: 
16399: =back
16400: 
16401: =head2 Course Infomation
16402: 
16403: =over 4
16404: 
16405: =item *
16406: 
16407: coursedescription($courseid,$options) : returns a hash of information about the
16408: specified course id, including all environment settings for the
16409: course, the description of the course will be in the hash under the
16410: key 'description'
16411: 
16412: $options is an optional parameter that if supplied is a hash reference that controls
16413: what how this function works.  It has the following key/values:
16414: 
16415: =over 4
16416: 
16417: =item freshen_cache
16418: 
16419: If defined, and the environment cache for the course is valid, it is 
16420: returned in the returned hash.
16421: 
16422: =item one_time
16423: 
16424: If defined, the last cache time is set to _now_
16425: 
16426: =item user
16427: 
16428: If defined, the supplied username is used instead of the current user.
16429: 
16430: 
16431: =back
16432: 
16433: =item *
16434: 
16435: resdata($name,$domain,$type,@which) : request for current parameter
16436: setting for a specific $type, where $type is either 'course' or 'user',
16437: @what should be a list of parameters to ask about. This routine caches
16438: answers for 10 minutes.
16439: 
16440: =item *
16441: 
16442: get_courseresdata($courseid, $domain) : dump the entire course resource
16443: data base, returning a hash that is keyed by the resource name and has
16444: values that are the resource value.  I believe that the timestamps and
16445: versions are also returned.
16446: 
16447: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16448: supplemental content area. This routine caches the number of files for 
16449: 10 minutes.
16450: 
16451: =back
16452: 
16453: =head2 Course Modification
16454: 
16455: =over 4
16456: 
16457: =item *
16458: 
16459: writecoursepref($courseid,%prefs) : write preferences (environment
16460: database) for a course
16461: 
16462: =item *
16463: 
16464: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16465: 
16466: =item *
16467: 
16468: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16469: 
16470: =item *
16471: 
16472: is_course($courseid), is_course($cdom, $cnum)
16473: 
16474: Accepts either a combined $courseid (in the form of domain_courseid) or the
16475: two component version $cdom, $cnum. It checks if the specified course exists.
16476: 
16477: Returns:
16478:     undef if the course doesn't exist, otherwise
16479:     in scalar context the combined courseid.
16480:     in list context the two components of the course identifier, domain and 
16481:     courseid.    
16482: 
16483: =back
16484: 
16485: =head2 Bubblesheet Configuration
16486: 
16487: =over 4
16488: 
16489: =item *
16490: 
16491: get_scantron_config($which)
16492: 
16493: $which - the name of the configuration to parse from the file.
16494: 
16495: Parses and returns the bubblesheet configuration line selected as a
16496: hash of configuration file fields.
16497: 
16498: 
16499: Returns:
16500:     If the named configuration is not in the file, an empty
16501:     hash is returned.
16502: 
16503:     a hash with the fields
16504:       name         - internal name for the this configuration setup
16505:       description  - text to display to operator that describes this config
16506:       CODElocation - if 0 or the string 'none'
16507:                           - no CODE exists for this config
16508:                      if -1 || the string 'letter'
16509:                           - a CODE exists for this config and is
16510:                             a string of letters
16511:                      Unsupported value (but planned for future support)
16512:                           if a positive integer
16513:                                - The CODE exists as the first n items from
16514:                                  the question section of the form
16515:                           if the string 'number'
16516:                                - The CODE exists for this config and is
16517:                                  a string of numbers
16518:       CODEstart   - (only matter if a CODE exists) column in the line where
16519:                      the CODE starts
16520:       CODElength  - length of the CODE
16521:       IDstart     - column where the student/employee ID starts
16522:       IDlength    - length of the student/employee ID info
16523:       Qstart      - column where the information from the bubbled
16524:                     'questions' start
16525:       Qlength     - number of columns comprising a single bubble line from
16526:                     the sheet. (usually either 1 or 10)
16527:       Qon         - either a single character representing the character used
16528:                     to signal a bubble was chosen in the positional setup, or
16529:                     the string 'letter' if the letter of the chosen bubble is
16530:                     in the final, or 'number' if a number representing the
16531:                     chosen bubble is in the file (1->A 0->J)
16532:       Qoff        - the character used to represent that a bubble was
16533:                     left blank
16534:       PaperID     - if the scanning process generates a unique number for each
16535:                     sheet scanned the column that this ID number starts in
16536:       PaperIDlength - number of columns that comprise the unique ID number
16537:                       for the sheet of paper
16538:       FirstName   - column that the first name starts in
16539:       FirstNameLength - number of columns that the first name spans
16540:       LastName    - column that the last name starts in
16541:       LastNameLength - number of columns that the last name spans
16542:       BubblesPerRow - number of bubbles available in each row used to
16543:                       bubble an answer. (If not specified, 10 assumed).
16544: 
16545: 
16546: =item *
16547: 
16548: get_scantronformat_file($cdom)
16549: 
16550: $cdom - the course's domain (optional); if not supplied, uses
16551: domain for current $env{'request.course.id'}.
16552: 
16553: Returns an array containing lines from the scantron format file for
16554: the domain of the course.
16555: 
16556: If a url for a custom.tab file is listed in domain's configuration.db,
16557: lines are from this file.
16558: 
16559: Otherwise, if a default.tab has been published in RES space by the
16560: domainconfig user, lines are from this file.
16561: 
16562: Otherwise, fall back to getting lines from the legacy file on the
16563: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16564: 
16565: =back
16566: 
16567: =head2 Resource Subroutines
16568: 
16569: =over 4
16570: 
16571: =item *
16572: 
16573: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16574: 
16575: =item *
16576: 
16577: repcopy($filename) : subscribes to the requested file, and attempts to
16578: replicate from the owning library server, Might return
16579: 'unavailable', 'not_found', 'forbidden', 'ok', or
16580: 'bad_request', also attempts to grab the metadata for the
16581: resource. Expects the local filesystem pathname
16582: (/home/httpd/html/res/....)
16583: 
16584: =back
16585: 
16586: =head2 Resource Information
16587: 
16588: =over 4
16589: 
16590: =item *
16591: 
16592: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16593: and returns the value of a variety of different possible values,
16594: $varname should be a request string, and the other parameters can be
16595: used to specify who and what one is asking about. Ordinarily, $cid 
16596: does not need to be specified, as it is retrived from 
16597: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16598: within lonuserstate::loadmap() when initializing a course, before
16599: $env{'request.course.id'} has been set, so it needs to be provided
16600: in that one case.
16601: 
16602: Possible values for $varname are environment.lastname (or other item
16603: from the envirnment hash), user.name (or someother aspect about the
16604: user), resource.0.maxtries (or some other part and parameter of a
16605: resource)
16606: 
16607: =item *
16608: 
16609: directcondval($number) : get current value of a condition; reads from a state
16610: string
16611: 
16612: =item *
16613: 
16614: condval($condidx) : value of condition index based on state
16615: 
16616: =item *
16617: 
16618: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16619: resource's metadata, $what should be either a specific key, or either
16620: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16621: packages that this resource currently uses, the last 3 arguments are 
16622: only used internally for recursive metadata.
16623: 
16624: the toolsymb is only used where the uri is for an external tool (for which
16625: the uri as well as the symb are guaranteed to be unique).
16626: 
16627: this function automatically caches all requests except any made recursively
16628: to retrieve a list of metadata keys for an imported library file ($liburi is 
16629: defined).
16630: 
16631: =item *
16632: 
16633: metadata_query($query,$custom,$customshow) : make a metadata query against the
16634: network of library servers; returns file handle of where SQL and regex results
16635: will be stored for query
16636: 
16637: =item *
16638: 
16639: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16640: return symbolic list entry (all arguments optional). 
16641: 
16642: Args: filename is the filename (including path) for the file for which a symb 
16643: is required; donotrecurse, if true will prevent calls to allowed() being made 
16644: to check access status if more than one resource was found in the bighash 
16645: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16646: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16647: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16648: cause possible symbs to be checked to determine if they are subject to content
16649: blocking, if so they will not be included as possible symbs; possibles is a
16650: ref to a hash, which, as a side effect, will be populated with all possible 
16651: symbs (content blocking not tested).
16652:  
16653: returns the data handle
16654: 
16655: =item *
16656: 
16657: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16658: and is a possible symb for the URL in $thisfn, and if is an encrypted
16659: resource that the user accessed using /enc/ returns a 1 on success, 0
16660: on failure, user must be in a course, as it assumes the existence of
16661: the course initial hash, and uses $env('request.course.id'}.  The third
16662: arg is an optional reference to a scalar.  If this arg is passed in the 
16663: call to symbverify, it will be set to 1 if the symb has been set to be 
16664: encrypted; otherwise it will be null.  
16665: 
16666: =item *
16667: 
16668: symbclean($symb) : removes versions numbers from a symb, returns the
16669: cleaned symb
16670: 
16671: =item *
16672: 
16673: is_on_map($uri) : checks if the $uri is somewhere on the current
16674: course map, user must be in a course for it to work.
16675: 
16676: =item *
16677: 
16678: numval($salt) : return random seed value (addend for rndseed)
16679: 
16680: =item *
16681: 
16682: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16683: a random seed, all arguments are optional, if they aren't sent it uses the
16684: environment to derive them. Note: if symb isn't sent and it can't get one
16685: from &symbread it will use the current time as its return value
16686: 
16687: =item *
16688: 
16689: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16690: unfakeable, receipt
16691: 
16692: =item *
16693: 
16694: receipt() : API to ireceipt working off of env values; given out to users
16695: 
16696: =item *
16697: 
16698: countacc($url) : count the number of accesses to a given URL
16699: 
16700: =item *
16701: 
16702: 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
16703: 
16704: =item *
16705: 
16706: 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)
16707: 
16708: =item *
16709: 
16710: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16711: 
16712: =item *
16713: 
16714: devalidate($symb) : devalidate temporary spreadsheet calculations,
16715: forcing spreadsheet to reevaluate the resource scores next time.
16716: 
16717: =item * 
16718: 
16719: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16720: when viewing in course context.
16721: 
16722:  input: six args -- filename (decluttered), course number, course domain,
16723:                     url, symb (if registered) and group (if this is a 
16724:                     group item -- e.g., bulletin board, group page etc.).
16725: 
16726:  output: array of five scalars --
16727:          $cfile -- url for file editing if editable on current server
16728:          $home -- homeserver of resource (i.e., for author if published,
16729:                                           or course if uploaded.).
16730:          $switchserver --  1 if server switch will be needed.
16731:          $forceedit -- 1 if icon/link should be to go to edit mode 
16732:          $forceview -- 1 if icon/link should be to go to view mode
16733: 
16734: =item *
16735: 
16736: is_course_upload($file,$cnum,$cdom)
16737: 
16738: Used in course context to determine if current file was uploaded to 
16739: the course (i.e., would be found in /userfiles/docs on the course's 
16740: homeserver.
16741: 
16742:   input: 3 args -- filename (decluttered), course number and course domain.
16743:   output: boolean -- 1 if file was uploaded.
16744: 
16745: =back
16746: 
16747: =head2 Storing/Retreiving Data
16748: 
16749: =over 4
16750: 
16751: =item *
16752: 
16753: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16754: permanently for this url; hashref needs to be given and should be a \%hashname;
16755: the remaining args aren't required and if they aren't passed or are '' they will
16756: be derived from the env (with the exception of $laststore, which is an 
16757: optional arg used when a user's submission is stored in grading).
16758: $laststore is $version=$timestamp, where $version is the most recent version
16759: number retrieved for the corresponding $symb in the $namespace db file, and
16760: $timestamp is the timestamp for that transaction (UNIX time).
16761: $laststore is currently only passed when cstore() is called by 
16762: structuretags::finalize_storage().
16763: 
16764: =item *
16765: 
16766: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16767: but uses critical subroutine
16768: 
16769: =item *
16770: 
16771: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16772: all args are optional
16773: 
16774: =item *
16775: 
16776: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16777: dumps the complete (or key matching regexp) namespace into a hash
16778: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16779: normally &store()ed into
16780: 
16781: $range should be either an integer '100' (give me the first 100
16782:                                            matching records)
16783:               or be  two integers sperated by a - with no spaces
16784:                  '30-50' (give me the 30th through the 50th matching
16785:                           records)
16786: 
16787: 
16788: =item *
16789: 
16790: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16791: replaces a &store() version of data with a replacement set of data
16792: for a particular resource in a namespace passed in the $storehash hash 
16793: reference. If $tolog is true, the transaction is logged in the courselog
16794: with an action=PUTSTORE.
16795: 
16796: =item *
16797: 
16798: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16799: works very similar to store/cstore, but all data is stored in a
16800: temporary location and can be reset using tmpreset, $storehash should
16801: be a hash reference, returns nothing on success
16802: 
16803: =item *
16804: 
16805: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16806: similar to restore, but all data is stored in a temporary location and
16807: can be reset using tmpreset. Returns a hash of values on success,
16808: error string otherwise.
16809: 
16810: =item *
16811: 
16812: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16813: deltes all keys for $symb form the temporary storage hash.
16814: 
16815: =item *
16816: 
16817: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16818: reference filled in from namesp ($udom and $uname are optional)
16819: 
16820: =item *
16821: 
16822: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16823: namesp ($udom and $uname are optional)
16824: 
16825: =item *
16826: 
16827: dump($namespace,$udom,$uname,$regexp,$range) : 
16828: dumps the complete (or key matching regexp) namespace into a hash
16829: ($udom, $uname, $regexp, $range are optional)
16830: 
16831: $range should be either an integer '100' (give me the first 100
16832:                                            matching records)
16833:               or be  two integers sperated by a - with no spaces
16834:                  '30-50' (give me the 30th through the 50th matching
16835:                           records)
16836: =item *
16837: 
16838: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16839: $store can be a scalar, an array reference, or if the amount to be 
16840: incremented is > 1, a hash reference.
16841: 
16842: ($udom and $uname are optional)
16843: 
16844: =item *
16845: 
16846: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16847: ($udom and $uname are optional)
16848: 
16849: =item *
16850: 
16851: cput($namespace,$storehash,$udom,$uname) : critical put
16852: ($udom and $uname are optional)
16853: 
16854: =item *
16855: 
16856: newput($namespace,$storehash,$udom,$uname) :
16857: 
16858: Attempts to store the items in the $storehash, but only if they don't
16859: currently exist, if this succeeds you can be certain that you have 
16860: successfully created a new key value pair in the $namespace db.
16861: 
16862: 
16863: Args:
16864:  $namespace: name of database to store values to
16865:  $storehash: hashref to store to the db
16866:  $udom: (optional) domain of user containing the db
16867:  $uname: (optional) name of user caontaining the db
16868: 
16869: Returns:
16870:  'ok' -> succeeded in storing all keys of $storehash
16871:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16872:                         least <key> already existed in the db (other
16873:                         requested keys may also already exist)
16874:  'error: <msg>' -> unable to tie the DB or other error occurred
16875:  'con_lost' -> unable to contact request server
16876:  'refused' -> action was not allowed by remote machine
16877: 
16878: 
16879: =item *
16880: 
16881: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16882: reference filled in from namesp (encrypts the return communication)
16883: ($udom and $uname are optional)
16884: 
16885: =item *
16886: 
16887: log($udom,$name,$home,$message) : write to permanent log for user; use
16888: critical subroutine
16889: 
16890: =item *
16891: 
16892: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16893: array reference filled in from namespace found in domain level on either
16894: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16895: 
16896: =item *
16897: 
16898: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16899: domain level either on specified domain server ($uhome) or primary domain 
16900: server ($udom and $uhome are optional)
16901: 
16902: =item * 
16903: 
16904: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16905: for: authentication, language, quotas, timezone, date locale, and portal URL in
16906: the target domain.
16907: 
16908: May also include additional key => value pairs for the following groups:
16909: 
16910: =over
16911: 
16912: =item
16913: disk quotas (MB allocated by default to portfolios and authoring spaces).
16914: 
16915: =over
16916: 
16917: =item defaultquota, authorquota
16918: 
16919: =back
16920: 
16921: =item
16922: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16923: portfolio for users).
16924: 
16925: =over
16926: 
16927: =item
16928: aboutme, blog, webdav, portfolio
16929: 
16930: =back
16931: 
16932: =item
16933: requestcourses: ability to request courses, and how requests are processed.
16934: 
16935: =over
16936: 
16937: =item
16938: official, unofficial, community, textbook, placement
16939: 
16940: =back
16941: 
16942: =item
16943: inststatus: types of institutional affiliation, and order in which they are displayed.
16944: 
16945: =over
16946: 
16947: =item
16948: inststatustypes, inststatusorder, inststatusguest
16949: 
16950: =back
16951: 
16952: =item
16953: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16954: for course's uploaded content.
16955: 
16956: =over
16957: 
16958: =item
16959: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16960: communityquota, textbookquota, placementquota
16961: 
16962: =back
16963: 
16964: =item
16965: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16966: on your servers.
16967: 
16968: =over
16969: 
16970: =item 
16971: remotesessions, hostedsessions
16972: 
16973: =back
16974: 
16975: =back
16976: 
16977: In cases where a domain coordinator has never used the "Set Domain Configuration"
16978: utility to create a configuration.db file on a domain's primary library server 
16979: only the following domain defaults: auth_def, auth_arg_def, lang_def
16980: -- corresponding values are authentication type (internal, krb4, krb5,
16981: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16982: will be available. Values are retrieved from cache (if current), unless the
16983: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16984: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16985: 
16986: Typical usage:
16987: 
16988: %domdefaults = &get_domain_defaults($target_domain);
16989: 
16990: =back
16991: 
16992: =head2 Network Status Functions
16993: 
16994: =over 4
16995: 
16996: =item *
16997: 
16998: dirlist() : return directory list based on URI (first arg).
16999: 
17000: Inputs: 1 required, 5 optional.
17001: 
17002: =over
17003: 
17004: =item 
17005: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17006: 
17007: =item
17008: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17009: 
17010: =item
17011: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17012: 
17013: =item
17014: $getpropath - boolean: 1 if prepend path using &propath(). 
17015: 
17016: =item
17017: $getuserdir - boolean: 1 if prepend path for "userfiles".
17018: 
17019: =item 
17020: $alternateRoot - path to prepend in place of path from $uri.
17021: 
17022: =back
17023: 
17024: Returns: Array of up to two items.
17025: 
17026: =over
17027: 
17028: a reference to an array of files/subdirectories
17029: 
17030: =over
17031: 
17032: Each element in the array of files/subdirectories is a & separated list of
17033: item name and the result of running stat on the item.  If dirlist was requested
17034: for a file instead of a directory, the item name will be ''. For a directory 
17035: listing, if the item is a metadata file, the element will end &N&M 
17036: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17037: default copyright set (1).  
17038: 
17039: =back
17040: 
17041: a scalar containing error condition (if encountered).
17042: 
17043: =over
17044: 
17045: =item 
17046: no_host (no homeserver identified for $username:$domain).
17047: 
17048: =item 
17049: no_such_host (server contacted for listing not identified as valid host).
17050: 
17051: =item 
17052: con_lost (connection to remote server failed).
17053: 
17054: =item 
17055: refused (invalid $username:$domain received on lond side).
17056: 
17057: =item 
17058: no_such_dir (directory at specified path on lond side does not exist). 
17059: 
17060: =item 
17061: empty (directory at specified path on lond side is empty).
17062: 
17063: =over
17064: 
17065: This is currently not encountered because the &ls3, &ls2, 
17066: &ls (_handler) routines on the lond side do not filter out
17067: . and .. from a directory listing. 
17068: 
17069: =back
17070: 
17071: =back
17072: 
17073: =back
17074: 
17075: =item *
17076: 
17077: spareserver() : find server with least workload from spare.tab
17078: 
17079: 
17080: =item *
17081: 
17082: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17083: if there is no corresponding loncapa host.
17084: 
17085: =back
17086: 
17087: 
17088: =head2 Apache Request
17089: 
17090: =over 4
17091: 
17092: =item *
17093: 
17094: ssi($url,%hash) : server side include, does a complete request cycle on url to
17095: localhost, posts hash
17096: 
17097: =back
17098: 
17099: =head2 Data to String to Data
17100: 
17101: =over 4
17102: 
17103: =item *
17104: 
17105: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17106: and '&' separators, supports elements that are arrayrefs and hashrefs
17107: 
17108: =item *
17109: 
17110: hashref2str($hashref) : convert a hashref into a string complete with
17111: escaping and '=' and '&' separators, supports elements that are
17112: arrayrefs and hashrefs
17113: 
17114: =item *
17115: 
17116: arrayref2str($arrayref) : convert an arrayref into a string complete
17117: with escaping and '&' separators, supports elements that are arrayrefs
17118: and hashrefs
17119: 
17120: =item *
17121: 
17122: str2hash($string) : convert string to hash using unescaping and
17123: splitting on '=' and '&', supports elements that are arrayrefs and
17124: hashrefs
17125: 
17126: =item *
17127: 
17128: str2array($string) : convert string to hash using unescaping and
17129: splitting on '&', supports elements that are arrayrefs and hashrefs
17130: 
17131: =back
17132: 
17133: =head2 Logging Routines
17134: 
17135: 
17136: These routines allow one to make log messages in the lonnet.log and
17137: lonnet.perm logfiles.
17138: 
17139: =over 4
17140: 
17141: =item *
17142: 
17143: logtouch() : make sure the logfile, lonnet.log, exists
17144: 
17145: =item *
17146: 
17147: logthis() : append message to the normal lonnet.log file, it gets
17148: preiodically rolled over and deleted.
17149: 
17150: =item *
17151: 
17152: logperm() : append a permanent message to lonnet.perm.log, this log
17153: file never gets deleted by any automated portion of the system, only
17154: messages of critical importance should go in here.
17155: 
17156: 
17157: =back
17158: 
17159: =head2 General File Helper Routines
17160: 
17161: =over 4
17162: 
17163: =item *
17164: 
17165: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17166: (a) files in /uploaded
17167:   (i) If a local copy of the file exists - 
17168:       compares modification date of local copy with last-modified date for 
17169:       definitive version stored on home server for course. If local copy is 
17170:       stale, requests a new version from the home server and stores it. 
17171:       If the original has been removed from the home server, then local copy 
17172:       is unlinked.
17173:   (ii) If local copy does not exist -
17174:       requests the file from the home server and stores it. 
17175:   
17176:   If $caller is 'uploadrep':  
17177:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17178:     for request for files originally uploaded via DOCS. 
17179:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17180:   
17181:   Otherwise:
17182:      This indicates a call from the content generation phase of the request.
17183:      -  returns the entire contents of the file or -1.
17184:      
17185: (b) files in /res
17186:    - returns the entire contents of a file or -1; 
17187:    it properly subscribes to and replicates the file if neccessary.
17188: 
17189: 
17190: =item *
17191: 
17192: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17193:                   reference
17194: 
17195: returns either a stat() list of data about the file or an empty list
17196: if the file doesn't exist or couldn't find out about it (connection
17197: problems or user unknown)
17198: 
17199: =item *
17200: 
17201: filelocation($dir,$file) : returns file system location of a file
17202: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17203: directory that relative $file lookups are to looked in ($dir of /a/dir
17204: and a file of ../bob will become /a/bob)
17205: 
17206: =item *
17207: 
17208: hreflocation($dir,$file) : returns file system location or a URL; same as
17209: filelocation except for hrefs
17210: 
17211: =item *
17212: 
17213: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17214: also removes beginning /home/httpd/html unless /priv/ follows it.
17215: 
17216: =back
17217: 
17218: =head2 Usererfile file routines (/uploaded*)
17219: 
17220: =over 4
17221: 
17222: =item *
17223: 
17224: userfileupload(): main rotine for putting a file in a user or course's
17225:                   filespace, arguments are,
17226: 
17227:  formname - required - this is the name of the element in $env where the
17228:            filename, and the contents of the file to create/modifed exist
17229:            the filename is in $env{'form.'.$formname.'.filename'} and the
17230:            contents of the file is located in $env{'form.'.$formname}
17231:  context - if coursedoc, store the file in the course of the active role
17232:              of the current user; 
17233:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17234:            if 'canceloverwrite': delete file in tmp/overwrites directory
17235:  subdir - required - subdirectory to put the file in under ../userfiles/
17236:          if undefined, it will be placed in "unknown"
17237: 
17238:  (This routine calls clean_filename() to remove any dangerous
17239:  characters from the filename, and then calls finuserfileupload() to
17240:  complete the transaction)
17241: 
17242:  returns either the url of the uploaded file (/uploaded/....) if successful
17243:  and /adm/notfound.html if unsuccessful
17244: 
17245: =item *
17246: 
17247: clean_filename(): routine for cleaing a filename up for storage in
17248:                  userfile space, argument is:
17249: 
17250:  filename - proposed filename
17251: 
17252: returns: the new clean filename
17253: 
17254: =item *
17255: 
17256: finishuserfileupload(): routine that creates and sends the file to
17257: userspace, probably shouldn't be called directly
17258: 
17259:   docuname: username or courseid of destination for the file
17260:   docudom: domain of user/course of destination for the file
17261:   formname: same as for userfileupload()
17262:   fname: filename (including subdirectories) for the file
17263:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17264:           if hashref, and context is scantron, will convert csv format to standard format
17265:   allfiles: reference to hash used to store objects found by parser
17266:   codebase: reference to hash used for codebases of java objects found by parser
17267:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17268:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17269:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17270:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17271:   context: if 'overwrite', will move the uploaded file from its temporary location to
17272:             userfiles to facilitate overwriting a previously uploaded file with same name.
17273:   mimetype: reference to scalar to accommodate mime type determined
17274:             from File::MMagic if $parser = parse.
17275: 
17276:  returns either the url of the uploaded file (/uploaded/....) if successful
17277:  and /adm/notfound.html if unsuccessful (or an error message if context 
17278:  was 'overwrite').
17279:  
17280: 
17281: =item *
17282: 
17283: renameuserfile(): renames an existing userfile to a new name
17284: 
17285:   Args:
17286:    docuname: username or courseid of destination for the file
17287:    docudom: domain of user/course of destination for the file
17288:    old: current file name (including any subdirs under userfiles)
17289:    new: desired file name (including any subdirs under userfiles)
17290: 
17291: =item *
17292: 
17293: mkdiruserfile(): creates a directory is a userfiles dir
17294: 
17295:   Args:
17296:    docuname: username or courseid of destination for the file
17297:    docudom: domain of user/course of destination for the file
17298:    dir: dir to create (including any subdirs under userfiles)
17299: 
17300: =item *
17301: 
17302: removeuserfile(): removes a file that exists in userfiles
17303: 
17304:   Args:
17305:    docuname: username or courseid of destination for the file
17306:    docudom: domain of user/course of destination for the file
17307:    fname: filname to delete (including any subdirs under userfiles)
17308: 
17309: =item *
17310: 
17311: removeuploadedurl(): convience function for removeuserfile()
17312: 
17313:   Args:
17314:    url:  a full /uploaded/... url to delete
17315: 
17316: =item * 
17317: 
17318: get_portfile_permissions():
17319:   Args:
17320:     domain: domain of user or course contain the portfolio files
17321:     user: name of user or num of course contain the portfolio files
17322:   Returns:
17323:     hashref of a dump of the proper file_permissions.db
17324:    
17325: 
17326: =item * 
17327: 
17328: get_access_controls():
17329: 
17330: Args:
17331:   current_permissions: the hash ref returned from get_portfile_permissions()
17332:   group: (optional) the group you want the files associated with
17333:   file: (optional) the file you want access info on
17334: 
17335: Returns:
17336:     a hash (keys are file names) of hashes containing
17337:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17338:         values are XML containing access control settings (see below) 
17339: 
17340: Internal notes:
17341: 
17342:  access controls are stored in file_permissions.db as key=value pairs.
17343:     key -> path to file/file_name\0uniqueID:scope_end_start
17344:         where scope -> public,guest,course,group,domains or users.
17345:               end -> UNIX time for end of access (0 -> no end date)
17346:               start -> UNIX time for start of access
17347: 
17348:     value -> XML description of access control
17349:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17350:             <start></start>
17351:             <end></end>
17352: 
17353:             <password></password>  for scope type = guest
17354: 
17355:             <domain></domain>     for scope type = course or group
17356:             <number></number>
17357:             <roles id="">
17358:              <role></role>
17359:              <access></access>
17360:              <section></section>
17361:              <group></group>
17362:             </roles>
17363: 
17364:             <dom></dom>         for scope type = domains
17365: 
17366:             <users>             for scope type = users
17367:              <user>
17368:               <uname></uname>
17369:               <udom></udom>
17370:              </user>
17371:             </users>
17372:            </scope> 
17373:               
17374:  Access data is also aggregated for each file in an additional key=value pair:
17375:  key -> path to file/file_name\0accesscontrol 
17376:  value -> reference to hash
17377:           hash contains key = value pairs
17378:           where key = uniqueID:scope_end_start
17379:                 value = UNIX time record was last updated
17380: 
17381:           Used to improve speed of look-ups of access controls for each file.  
17382:  
17383:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17384: 
17385: =item *
17386: 
17387: modify_access_controls():
17388: 
17389: Modifies access controls for a portfolio file
17390: Args
17391: 1. file name
17392: 2. reference to hash of required changes,
17393: 3. domain
17394: 4. username
17395:   where domain,username are the domain of the portfolio owner 
17396:   (either a user or a course) 
17397: 
17398: Returns:
17399: 1. result of additions or updates ('ok' or 'error', with error message). 
17400: 2. result of deletions ('ok' or 'error', with error message).
17401: 3. reference to hash of any new or updated access controls.
17402: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17403:    key = integer (inbound ID)
17404:    value = uniqueID
17405: 
17406: =item *
17407: 
17408: get_timebased_id():
17409: 
17410: Attempts to get a unique timestamp-based suffix for use with items added to a 
17411: course via the Course Editor (e.g., folders, composite pages, 
17412: group bulletin boards).
17413: 
17414: Args: (first three required; six others optional)
17415: 
17416: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17417:    docssequence, or name of group
17418: 
17419: 2. keyid (alphanumeric): name of temporary locking key in hash,
17420:    e.g., num, boardids
17421: 
17422: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17423:    file will be named nohist_namespace.db
17424: 
17425: 4. cdom: domain of course; default is current course domain from %env
17426: 
17427: 5. cnum: course number; default is current course number from %env
17428: 
17429: 6. idtype: set to concat if an additional digit is to be appended to the 
17430:    unix timestamp to form the suffix, if the plain timestamp is already
17431:    in use.  Default is to not do this, but simply increment the unix 
17432:    timestamp by 1 until a unique key is obtained.
17433: 
17434: 7. who: holder of locking key; defaults to user:domain for user.
17435: 
17436: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17437:    retrying); default is 3.
17438: 
17439: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17440: 
17441: Returns:
17442: 
17443: 1. suffix obtained (numeric)
17444: 
17445: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17446: 
17447: 3. error: contains (localized) error message if an error occurred.
17448: 
17449: 
17450: =back
17451: 
17452: =head2 HTTP Helper Routines
17453: 
17454: =over 4
17455: 
17456: =item *
17457: 
17458: escape() : unpack non-word characters into CGI-compatible hex codes
17459: 
17460: =item *
17461: 
17462: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17463: 
17464: =back
17465: 
17466: =head1 PRIVATE SUBROUTINES
17467: 
17468: =head2 Underlying communication routines (Shouldn't call)
17469: 
17470: =over 4
17471: 
17472: =item *
17473: 
17474: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17475: 
17476: =item *
17477: 
17478: reply() : uses subreply to send a message to remote machine, logs all failures
17479: 
17480: =item *
17481: 
17482: critical() : passes a critical message to another server; if cannot
17483: get through then place message in connection buffer directory and
17484: returns con_delayed, if incapable of saving message, returns
17485: con_failed
17486: 
17487: =item *
17488: 
17489: reconlonc() : tries to reconnect lonc client processes.
17490: 
17491: =back
17492: 
17493: =head2 Resource Access Logging
17494: 
17495: =over 4
17496: 
17497: =item *
17498: 
17499: flushcourselogs() : flush (save) buffer logs and access logs
17500: 
17501: =item *
17502: 
17503: courselog($what) : save message for course in hash
17504: 
17505: =item *
17506: 
17507: courseacclog($what) : save message for course using &courselog().  Perform
17508: special processing for specific resource types (problems, exams, quizzes, etc).
17509: 
17510: =item *
17511: 
17512: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17513: as a PerlChildExitHandler
17514: 
17515: =back
17516: 
17517: =head2 Other
17518: 
17519: =over 4
17520: 
17521: =item *
17522: 
17523: symblist($mapname,%newhash) : update symbolic storage links
17524: 
17525: =back
17526: 
17527: =cut
17528: 

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