File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1410: download - view: text, annotated - select for diffs
Mon May 6 19:28:24 2019 UTC (5 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain configuration which allows Course Owner to change a student's
  password (with conditions):
  - Restrict to specified institutional status types for (a) course owner
    and (b) student.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1410 2019/05/06 19:28:24 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);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: use LONCAPA::transliterate;
  105: 
  106: use File::Copy;
  107: 
  108: my $readit;
  109: my $max_connection_retries = 20;     # Or some such value.
  110: 
  111: require Exporter;
  112: 
  113: our @ISA = qw (Exporter);
  114: our @EXPORT = qw(%env);
  115: 
  116: 
  117: # ------------------------------------ Logging (parameters, docs, slots, roles)
  118: {
  119:     my $logid;
  120:     sub write_log {
  121: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  122:         if ($context eq 'course') {
  123:             if (($cnum eq '') || ($cdom eq '')) {
  124:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  125:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  126:             }
  127:         }
  128: 	$logid ++;
  129:         my $now = time();
  130: 	my $id=$now.'00000'.$$.'00000'.$logid;
  131:         my $logentry = { 
  132:                           $id => {
  133:                                    'exe_uname' => $env{'user.name'},
  134:                                    'exe_udom'  => $env{'user.domain'},
  135:                                    'exe_time'  => $now,
  136:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  137:                                    'delflag'   => $delflag,
  138:                                    'logentry'  => $storehash,
  139:                                    'uname'     => $uname,
  140:                                    'udom'      => $udom,
  141:                                   }
  142:                        };
  143: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  144:     }
  145: }
  146: 
  147: sub logtouch {
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     unless (-e "$execdir/logs/lonnet.log") {	
  150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  151: 	close $fh;
  152:     }
  153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  155: }
  156: 
  157: sub logthis {
  158:     my $message=shift;
  159:     my $execdir=$perlvar{'lonDaemons'};
  160:     my $now=time;
  161:     my $local=localtime($now);
  162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  164: 	print $fh $logstring;
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub logperm {
  171:     my $message=shift;
  172:     my $execdir=$perlvar{'lonDaemons'};
  173:     my $now=time;
  174:     my $local=localtime($now);
  175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  176: 	print $fh "$now:$message:$local\n";
  177: 	close($fh);
  178:     }
  179:     return 1;
  180: }
  181: 
  182: sub create_connection {
  183:     my ($hostname,$lonid) = @_;
  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  185: 				     Type    => SOCK_STREAM,
  186: 				     Timeout => 10);
  187:     return 0 if (!$client);
  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  189:     my $result = <$client>;
  190:     chomp($result);
  191:     return 1 if ($result eq 'done');
  192:     return 0;
  193: }
  194: 
  195: sub get_server_timezone {
  196:     my ($cnum,$cdom) = @_;
  197:     my $home=&homeserver($cnum,$cdom);
  198:     if ($home ne 'no_host') {
  199:         my $cachetime = 24*3600;
  200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  201:         if (defined($cached)) {
  202:             return $timezone;
  203:         } else {
  204:             my $timezone = &reply('servertimezone',$home);
  205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  206:         }
  207:     }
  208: }
  209: 
  210: sub get_server_distarch {
  211:     my ($lonhost,$ignore_cache) = @_;
  212:     if (defined($lonhost)) {
  213:         if (!defined(&hostname($lonhost))) {
  214:             return;
  215:         }
  216:         my $cachetime = 12*3600;
  217:         if (!$ignore_cache) {
  218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  219:             if (defined($cached)) {
  220:                 return $distarch;
  221:             }
  222:         }
  223:         my $rep = &reply('serverdistarch',$lonhost);
  224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  226:                 $rep eq '') {
  227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  228:         }
  229:     }
  230:     return;
  231: }
  232: 
  233: sub get_servercerts_info {
  234:     my ($lonhost,$hostname,$context) = @_;
  235:     return if ($lonhost eq '');
  236:     if ($hostname eq '') {
  237:         $hostname = &hostname($lonhost);
  238:     }
  239:     return if ($hostname eq '');
  240:     my ($rep,$uselocal);
  241:     if ($context eq 'install') {
  242:         $uselocal = 1;
  243:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  244:         $uselocal = 1;
  245:     }
  246:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  247:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  248:         if ($distro eq '') {
  249:             $uselocal = 0;
  250:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  251:             if ($1 < 6) {
  252:                 $uselocal = 0;
  253:             }
  254:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  255:             if ($1 < 12) {
  256:                 $uselocal = 0;
  257:             }
  258:         }
  259:     }
  260:     if ($uselocal) {
  261:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  262:     } else {
  263:         $rep=&reply('servercerts',$lonhost);
  264:     }
  265:     my ($result,%returnhash);
  266:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  267:         ($rep eq 'unknown_cmd')) {
  268:         $result = $rep;
  269:     } else {
  270:         $result = 'ok';
  271:         my @pairs=split(/\&/,$rep);
  272:         foreach my $item (@pairs) {
  273:             my ($key,$value)=split(/=/,$item,2);
  274:             my $what = &unescape($key);
  275:             $returnhash{$what}=&thaw_unescape($value);
  276:         }
  277:     }
  278:     return ($result,\%returnhash);
  279: }
  280: 
  281: sub get_server_loncaparev {
  282:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  283:     if (defined($lonhost)) {
  284:         if (!defined(&hostname($lonhost))) {
  285:             undef($lonhost);
  286:         }
  287:     }
  288:     if (!defined($lonhost)) {
  289:         if (defined(&domain($dom,'primary'))) {
  290:             $lonhost=&domain($dom,'primary');
  291:             if ($lonhost eq 'no_host') {
  292:                 undef($lonhost);
  293:             }
  294:         }
  295:     }
  296:     if (defined($lonhost)) {
  297:         my $cachetime = 12*3600;
  298:         if (!$ignore_cache) {
  299:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  300:             if (defined($cached)) {
  301:                 return $loncaparev;
  302:             }
  303:         }
  304:         my ($answer,$loncaparev);
  305:         my @ids=&current_machine_ids();
  306:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  307:             $answer = $perlvar{'lonVersion'};
  308:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  309:                 $loncaparev = $1;
  310:             }
  311:         } else {
  312:             $answer = &reply('serverloncaparev',$lonhost);
  313:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  314:                 if ($caller eq 'loncron') {
  315:                     my $hostname = &hostname($lonhost);
  316:                     my $protocol = $protocol{$lonhost};
  317:                     $protocol = 'http' if ($protocol ne 'https');
  318:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  319:                     my $request=new HTTP::Request('GET',$url);
  320:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  321:                     unless ($response->is_error()) {
  322:                         my $content = $response->content;
  323:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  324:                             $loncaparev = $1;
  325:                         }
  326:                     }
  327:                 } else {
  328:                     $loncaparev = $loncaparevs{$lonhost};
  329:                 }
  330:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  331:                 $loncaparev = $1;
  332:             }
  333:         }
  334:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  335:     }
  336: }
  337: 
  338: sub get_server_homeID {
  339:     my ($hostname,$ignore_cache,$caller) = @_;
  340:     unless ($ignore_cache) {
  341:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  342:         if (defined($cached)) {
  343:             return $serverhomeID;
  344:         }
  345:     }
  346:     my $cachetime = 12*3600;
  347:     my $serverhomeID;
  348:     if ($caller eq 'loncron') { 
  349:         my @machine_ids = &machine_ids($hostname);
  350:         foreach my $id (@machine_ids) {
  351:             my $response = &reply('serverhomeID',$id);
  352:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  353:                 $serverhomeID = $response;
  354:                 last;
  355:             }
  356:         }
  357:         if ($serverhomeID eq '') {
  358:             $serverhomeID = $machine_ids[-1];
  359:         }
  360:     } else {
  361:         $serverhomeID = $serverhomeIDs{$hostname};
  362:     }
  363:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  364: }
  365: 
  366: sub get_remote_globals {
  367:     my ($lonhost,$whathash,$ignore_cache) = @_;
  368:     my ($result,%returnhash,%whatneeded);
  369:     if (ref($whathash) eq 'HASH') {
  370:         foreach my $what (sort(keys(%{$whathash}))) {
  371:             my $hashid = $lonhost.'-'.$what;
  372:             my ($response,$cached);
  373:             unless ($ignore_cache) {
  374:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  375:             }
  376:             if (defined($cached)) {
  377:                 $returnhash{$what} = $response;
  378:             } else {
  379:                 $whatneeded{$what} = 1;
  380:             }
  381:         }
  382:         if (keys(%whatneeded) == 0) {
  383:             $result = 'ok';
  384:         } else {
  385:             my $requested = &freeze_escape(\%whatneeded);
  386:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  387:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  388:                 ($rep eq 'unknown_cmd')) {
  389:                 $result = $rep;
  390:             } else {
  391:                 $result = 'ok';
  392:                 my @pairs=split(/\&/,$rep);
  393:                 foreach my $item (@pairs) {
  394:                     my ($key,$value)=split(/=/,$item,2);
  395:                     my $what = &unescape($key);
  396:                     my $hashid = $lonhost.'-'.$what;
  397:                     $returnhash{$what}=&thaw_unescape($value);
  398:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  399:                 }
  400:             }
  401:         }
  402:     }
  403:     return ($result,\%returnhash);
  404: }
  405: 
  406: sub remote_devalidate_cache {
  407:     my ($lonhost,$cachekeys) = @_;
  408:     my $items;
  409:     return unless (ref($cachekeys) eq 'ARRAY');
  410:     my $cachestr = join('&',@{$cachekeys});
  411:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  412:     return $response;
  413: }
  414: 
  415: # -------------------------------------------------- Non-critical communication
  416: sub subreply {
  417:     my ($cmd,$server)=@_;
  418:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  419:     #
  420:     #  With loncnew process trimming, there's a timing hole between lonc server
  421:     #  process exit and the master server picking up the listen on the AF_UNIX
  422:     #  socket.  In that time interval, a lock file will exist:
  423: 
  424:     my $lockfile=$peerfile.".lock";
  425:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  426: 	sleep(0.1);
  427:     }
  428:     # At this point, either a loncnew parent is listening or an old lonc
  429:     # or loncnew child is listening so we can connect or everything's dead.
  430:     #
  431:     #   We'll give the connection a few tries before abandoning it.  If
  432:     #   connection is not possible, we'll con_lost back to the client.
  433:     #   
  434:     my $client;
  435:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  436: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  437: 				      Type    => SOCK_STREAM,
  438: 				      Timeout => 10);
  439: 	if ($client) {
  440: 	    last;		# Connected!
  441: 	} else {
  442: 	    &create_connection(&hostname($server),$server);
  443: 	}
  444:         sleep(0.1);	# Try again later if failed connection.
  445:     }
  446:     my $answer;
  447:     if ($client) {
  448: 	print $client "sethost:$server:$cmd\n";
  449: 	$answer=<$client>;
  450: 	if (!$answer) { $answer="con_lost"; }
  451: 	chomp($answer);
  452:     } else {
  453: 	$answer = 'con_lost';	# Failed connection.
  454:     }
  455:     return $answer;
  456: }
  457: 
  458: sub reply {
  459:     my ($cmd,$server)=@_;
  460:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  461:     my $answer=subreply($cmd,$server);
  462:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  463:         my $logged = $cmd;
  464:         if ($cmd =~ /^encrypt:([^:]+):/) {
  465:             my $subcmd = $1;
  466:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  467:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  468:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  469:                 (undef,undef,my @rest) = split(/:/,$cmd);
  470:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  471:                     splice(@rest,2,1,'Hidden');
  472:                 } elsif ($subcmd eq 'passwd') {
  473:                     splice(@rest,2,2,('Hidden','Hidden'));
  474:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  475:                          ($subcmd eq 'autoexportgrades')) {
  476:                     splice(@rest,3,1,'Hidden');
  477:                 }
  478:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  479:             }
  480:         }
  481:         &logthis("<font color=\"blue\">WARNING:".
  482:                  " $logged to $server returned $answer</font>");
  483:     }
  484:     return $answer;
  485: }
  486: 
  487: # ----------------------------------------------------------- Send USR1 to lonc
  488: 
  489: sub reconlonc {
  490:     my ($lonid) = @_;
  491:     if ($lonid) {
  492:         my $hostname = &hostname($lonid);
  493: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  494: 	if ($hostname && -e $peerfile) {
  495: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  496: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  497: 					     Type    => SOCK_STREAM,
  498: 					     Timeout => 10);
  499: 	    if ($client) {
  500: 		print $client ("reset_retries\n");
  501: 		my $answer=<$client>;
  502: 		#reset just this one.
  503: 	    }
  504: 	}
  505: 	return;
  506:     }
  507: 
  508:     &logthis("Trying to reconnect lonc");
  509:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  510:     if (open(my $fh,"<",$loncfile)) {
  511: 	my $loncpid=<$fh>;
  512:         chomp($loncpid);
  513:         if (kill 0 => $loncpid) {
  514: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  515:             kill USR1 => $loncpid;
  516:             sleep 1;
  517:         } else {
  518: 	    &logthis(
  519:                "<font color=\"blue\">WARNING:".
  520:                " lonc at pid $loncpid not responding, giving up</font>");
  521:         }
  522:     } else {
  523: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  524:     }
  525: }
  526: 
  527: # ------------------------------------------------------ Critical communication
  528: 
  529: sub critical {
  530:     my ($cmd,$server)=@_;
  531:     unless (&hostname($server)) {
  532:         &logthis("<font color=\"blue\">WARNING:".
  533:                " Critical message to unknown server ($server)</font>");
  534:         return 'no_such_host';
  535:     }
  536:     my $answer=reply($cmd,$server);
  537:     if ($answer eq 'con_lost') {
  538: 	&reconlonc($server);
  539: 	my $answer=reply($cmd,$server);
  540:         if ($answer eq 'con_lost') {
  541:             my $now=time;
  542:             my $middlename=$cmd;
  543:             $middlename=substr($middlename,0,16);
  544:             $middlename=~s/\W//g;
  545:             my $dfilename=
  546:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  547:             $dumpcount++;
  548:             {
  549: 		my $dfh;
  550: 		if (open($dfh,">",$dfilename)) {
  551: 		    print $dfh "$cmd\n"; 
  552: 		    close($dfh);
  553: 		}
  554:             }
  555:             sleep 1;
  556:             my $wcmd='';
  557:             {
  558: 		my $dfh;
  559: 		if (open($dfh,"<",$dfilename)) {
  560: 		    $wcmd=<$dfh>; 
  561: 		    close($dfh);
  562: 		}
  563:             }
  564:             chomp($wcmd);
  565:             if ($wcmd eq $cmd) {
  566: 		&logthis("<font color=\"blue\">WARNING: ".
  567:                          "Connection buffer $dfilename: $cmd</font>");
  568:                 &logperm("D:$server:$cmd");
  569: 	        return 'con_delayed';
  570:             } else {
  571:                 &logthis("<font color=\"red\">CRITICAL:"
  572:                         ." Critical connection failed: $server $cmd</font>");
  573:                 &logperm("F:$server:$cmd");
  574:                 return 'con_failed';
  575:             }
  576:         }
  577:     }
  578:     return $answer;
  579: }
  580: 
  581: # ------------------------------------------- check if return value is an error
  582: 
  583: sub error {
  584:     my ($result) = @_;
  585:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  586: 	if ($2 == 2) { return undef; }
  587: 	return $1;
  588:     }
  589:     return undef;
  590: }
  591: 
  592: sub convert_and_load_session_env {
  593:     my ($lonidsdir,$handle)=@_;
  594:     my @profile;
  595:     {
  596: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  597: 	if (!$opened) {
  598: 	    return 0;
  599: 	}
  600: 	flock($idf,LOCK_SH);
  601: 	@profile=<$idf>;
  602: 	close($idf);
  603:     }
  604:     my %temp_env;
  605:     foreach my $line (@profile) {
  606: 	if ($line !~ m/=/) {
  607: 	    return 0;
  608: 	}
  609: 	chomp($line);
  610: 	my ($envname,$envvalue)=split(/=/,$line,2);
  611: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  612:     }
  613:     unlink("$lonidsdir/$handle.id");
  614:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  615: 	    0640)) {
  616: 	%disk_env = %temp_env;
  617: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  618: 	untie(%disk_env);
  619:     }
  620:     return 1;
  621: }
  622: 
  623: # ------------------------------------------- Transfer profile into environment
  624: my $env_loaded;
  625: sub transfer_profile_to_env {
  626:     my ($lonidsdir,$handle,$force_transfer) = @_;
  627:     if (!$force_transfer && $env_loaded) { return; } 
  628: 
  629:     if (!defined($lonidsdir)) {
  630: 	$lonidsdir = $perlvar{'lonIDsDir'};
  631:     }
  632:     if (!defined($handle)) {
  633:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  634:     }
  635: 
  636:     my $convert;
  637:     {
  638:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  639: 	if (!$opened) {
  640: 	    return;
  641: 	}
  642: 	flock($idf,LOCK_SH);
  643: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  644: 		&GDBM_READER(),0640)) {
  645: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  646: 	    untie(%disk_env);
  647: 	} else {
  648: 	    $convert = 1;
  649: 	}
  650:     }
  651:     if ($convert) {
  652: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  653: 	    &logthis("Failed to load session, or convert session.");
  654: 	}
  655:     }
  656: 
  657:     my %remove;
  658:     while ( my $envname = each(%env) ) {
  659:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  660:             if ($time < time-300) {
  661:                 $remove{$key}++;
  662:             }
  663:         }
  664:     }
  665: 
  666:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  667:     $env_loaded=1;
  668:     foreach my $expired_key (keys(%remove)) {
  669:         &delenv($expired_key);
  670:     }
  671: }
  672: 
  673: # ---------------------------------------------------- Check for valid session 
  674: sub check_for_valid_session {
  675:     my ($r,$name,$userhashref,$domref) = @_;
  676:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  677:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  678:     if ($name eq 'lonDAV') {
  679:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  680:     } else {
  681:         $lonidsdir=$r->dir_config('lonIDsDir');
  682:         if ($name eq '') {
  683:             $name = 'lonID';
  684:         }
  685:     }
  686:     if ($name eq 'lonID') {
  687:         $secure = 'lonSID';
  688:         $linkname = 'lonLinkID';
  689:         $pubname = 'lonPubID';
  690:         if (exists($cookies{$secure})) {
  691:             $lonid=$cookies{$secure};
  692:         } elsif (exists($cookies{$name})) {
  693:             $lonid=$cookies{$name};
  694:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  695:             $lonid=$cookies{$linkname};
  696:         } elsif (exists($cookies{$pubname})) {
  697:             $lonid=$cookies{$pubname};
  698:         }
  699:     } else {
  700:         $lonid=$cookies{$name};
  701:     }
  702:     return undef if (!$lonid);
  703: 
  704:     my $handle=&LONCAPA::clean_handle($lonid->value);
  705:     if (-l "$lonidsdir/$handle.id") {
  706:         my $link = readlink("$lonidsdir/$handle.id");
  707:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  708:             $handle = $1;
  709:         }
  710:     }
  711:     if (!-e "$lonidsdir/$handle.id") {
  712:         if ((ref($domref)) && ($name eq 'lonID') && 
  713:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  714:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  715:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  716:                 $$domref = $possudom;
  717:             }
  718:         }
  719:         return undef;
  720:     }
  721: 
  722:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  723:     return undef if (!$opened);
  724: 
  725:     flock($idf,LOCK_SH);
  726:     my %disk_env;
  727:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  728: 	    &GDBM_READER(),0640)) {
  729: 	return undef;	
  730:     }
  731: 
  732:     if (!defined($disk_env{'user.name'})
  733: 	|| !defined($disk_env{'user.domain'})) {
  734:         untie(%disk_env);
  735: 	return undef;
  736:     }
  737: 
  738:     if (ref($userhashref) eq 'HASH') {
  739:         $userhashref->{'name'} = $disk_env{'user.name'};
  740:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  741:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  742:         if ($userhashref->{'lti'}) {
  743:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  744:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  745:         }
  746:     }
  747:     untie(%disk_env);
  748: 
  749:     return $handle;
  750: }
  751: 
  752: sub timed_flock {
  753:     my ($file,$lock_type) = @_;
  754:     my $failed=0;
  755:     eval {
  756: 	local $SIG{__DIE__}='DEFAULT';
  757: 	local $SIG{ALRM}=sub {
  758: 	    $failed=1;
  759: 	    die("failed lock");
  760: 	};
  761: 	alarm(13);
  762: 	flock($file,$lock_type);
  763: 	alarm(0);
  764:     };
  765:     if ($failed) {
  766: 	return undef;
  767:     } else {
  768: 	return 1;
  769:     }
  770: }
  771: 
  772: sub get_sessionfile_vars {
  773:     my ($handle,$lonidsdir,$storearr) = @_;
  774:     my %returnhash;
  775:     unless (ref($storearr) eq 'ARRAY') {
  776:         return %returnhash;
  777:     }
  778:     if (-l "$lonidsdir/$handle.id") {
  779:         my $link = readlink("$lonidsdir/$handle.id");
  780:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  781:             $handle = $1;
  782:         }
  783:     }
  784:     if ((-e "$lonidsdir/$handle.id") &&
  785:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  786:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  787:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  788:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  789:                 flock($idf,LOCK_SH);
  790:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  791:                         &GDBM_READER(),0640)) {
  792:                     foreach my $item (@{$storearr}) {
  793:                         $returnhash{$item} = $disk_env{$item};
  794:                     }
  795:                     untie(%disk_env);
  796:                 }
  797:             }
  798:         }
  799:     }
  800:     return %returnhash;
  801: }
  802: 
  803: # ---------------------------------------------------------- Append Environment
  804: 
  805: sub appenv {
  806:     my ($newenv,$roles) = @_;
  807:     if (ref($newenv) eq 'HASH') {
  808:         foreach my $key (keys(%{$newenv})) {
  809:             my $refused = 0;
  810: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  811:                 $refused = 1;
  812:                 if (ref($roles) eq 'ARRAY') {
  813:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  814:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  815:                         $refused = 0;
  816:                     }
  817:                 }
  818:             }
  819:             if ($refused) {
  820:                 &logthis("<font color=\"blue\">WARNING: ".
  821:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  822:                          .'</font>');
  823: 	        delete($newenv->{$key});
  824:             } else {
  825:                 $env{$key}=$newenv->{$key};
  826:             }
  827:         }
  828:         my $lonids = $perlvar{'lonIDsDir'};
  829:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  830:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  831:             if ($opened
  832: 	        && &timed_flock($env_file,LOCK_EX)
  833: 	        &&
  834: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  835: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  836: 	        while (my ($key,$value) = each(%{$newenv})) {
  837: 	            $disk_env{$key} = $value;
  838: 	        }
  839: 	        untie(%disk_env);
  840:             }
  841:         }
  842:     }
  843:     return 'ok';
  844: }
  845: # ----------------------------------------------------- Delete from Environment
  846: 
  847: sub delenv {
  848:     my ($delthis,$regexp,$roles) = @_;
  849:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  850:         my $refused = 1;
  851:         if (ref($roles) eq 'ARRAY') {
  852:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  853:             if (grep(/^\Q$role\E$/,@{$roles})) {
  854:                 $refused = 0;
  855:             }
  856:         }
  857:         if ($refused) {
  858:             &logthis("<font color=\"blue\">WARNING: ".
  859:                      "Attempt to delete from environment ".$delthis);
  860:             return 'error';
  861:         }
  862:     }
  863:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  864:     if ($opened
  865: 	&& &timed_flock($env_file,LOCK_EX)
  866: 	&&
  867: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  868: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  869: 	foreach my $key (keys(%disk_env)) {
  870: 	    if ($regexp) {
  871:                 if ($key=~/^$delthis/) {
  872:                     delete($env{$key});
  873:                     delete($disk_env{$key});
  874:                 } 
  875:             } else {
  876:                 if ($key=~/^\Q$delthis\E/) {
  877: 		    delete($env{$key});
  878: 		    delete($disk_env{$key});
  879: 	        }
  880:             }
  881: 	}
  882: 	untie(%disk_env);
  883:     }
  884:     return 'ok';
  885: }
  886: 
  887: sub get_env_multiple {
  888:     my ($name) = @_;
  889:     my @values;
  890:     if (defined($env{$name})) {
  891:         # exists is it an array
  892:         if (ref($env{$name})) {
  893:             @values=@{ $env{$name} };
  894:         } else {
  895:             $values[0]=$env{$name};
  896:         }
  897:     }
  898:     return(@values);
  899: }
  900: 
  901: # ------------------------------------------------------------------- Locking
  902: 
  903: sub set_lock {
  904:     my ($text)=@_;
  905:     $locknum++;
  906:     my $id=$$.'-'.$locknum;
  907:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  908:              'session.lock.'.$id => $text});
  909:     return $id;
  910: }
  911: 
  912: sub get_locks {
  913:     my $num=0;
  914:     my %texts=();
  915:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  916:        if ($lock=~/\w/) {
  917:           $num++;
  918:           $texts{$lock}=$env{'session.lock.'.$lock};
  919:        }
  920:    }
  921:    return ($num,%texts);
  922: }
  923: 
  924: sub remove_lock {
  925:     my ($id)=@_;
  926:     my $newlocks='';
  927:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  928:        if (($lock=~/\w/) && ($lock ne $id)) {
  929:           $newlocks.=','.$lock;
  930:        }
  931:     }
  932:     &appenv({'session.locks' => $newlocks});
  933:     &delenv('session.lock.'.$id);
  934: }
  935: 
  936: sub remove_all_locks {
  937:     my $activelocks=$env{'session.locks'};
  938:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  939:        if ($lock=~/\w/) {
  940:           &remove_lock($lock);
  941:        }
  942:     }
  943: }
  944: 
  945: 
  946: # ------------------------------------------ Find out current server userload
  947: sub userload {
  948:     my $numusers=0;
  949:     {
  950: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  951: 	my $filename;
  952: 	my $curtime=time;
  953: 	while ($filename=readdir(LONIDS)) {
  954: 	    next if ($filename eq '.' || $filename eq '..');
  955: 	    next if ($filename =~ /publicuser_\d+\.id/);
  956:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  957: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  958: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  959: 	}
  960: 	closedir(LONIDS);
  961:     }
  962:     my $userloadpercent=0;
  963:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  964:     if ($maxuserload) {
  965: 	$userloadpercent=100*$numusers/$maxuserload;
  966:     }
  967:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  968:     return $userloadpercent;
  969: }
  970: 
  971: # ------------------------------ Find server with least workload from spare.tab
  972: 
  973: sub spareserver {
  974:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  975:     my $spare_server;
  976:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  977:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  978:                                                      :  $userloadpercent;
  979:     my ($uint_dom,$remotesessions);
  980:     if (($udom ne '') && (&domain($udom) ne '')) {
  981:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  982:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  983:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  984:         $remotesessions = $udomdefaults{'remotesessions'};
  985:     }
  986:     my $spareshash = &this_host_spares($udom);
  987:     if (ref($spareshash) eq 'HASH') {
  988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  990:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  991:                                              $try_server));
  992: 	        ($spare_server, $lowest_load) =
  993: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  994:             }
  995:         }
  996: 
  997:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  998: 
  999:         if (!$found_server) {
 1000:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1001: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1002:                     next unless (&spare_can_host($udom,$uint_dom,
 1003:                                                  $remotesessions,$try_server));
 1004: 	            ($spare_server, $lowest_load) =
 1005: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1006:                 }
 1007: 	    }
 1008:         }
 1009:     }
 1010: 
 1011:     if (!$want_server_name) {
 1012:         if (defined($spare_server)) {
 1013:             my $hostname = &hostname($spare_server);
 1014:             if (defined($hostname)) {
 1015:                 my $protocol = 'http';
 1016:                 if ($protocol{$spare_server} eq 'https') {
 1017:                     $protocol = $protocol{$spare_server};
 1018:                 }
 1019: 	        $spare_server = $protocol.'://'.$hostname;
 1020:             }
 1021:         }
 1022:     }
 1023:     return $spare_server;
 1024: }
 1025: 
 1026: sub compare_server_load {
 1027:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1028: 
 1029:     if ($required) {
 1030:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1031:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1032:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1033:         if (($major eq '' && $minor eq '') ||
 1034:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1035:             return ($spare_server,$lowest_load);
 1036:         }
 1037:     }
 1038: 
 1039:     my $loadans     = &reply('load',    $try_server);
 1040:     my $userloadans = &reply('userload',$try_server);
 1041: 
 1042:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1043: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1044:     }
 1045: 
 1046:     my $load;
 1047:     if ($loadans =~ /\d/) {
 1048: 	if ($userloadans =~ /\d/) {
 1049: 	    #both are numbers, pick the bigger one
 1050: 	    $load = ($loadans > $userloadans) ? $loadans 
 1051: 		                              : $userloadans;
 1052: 	} else {
 1053: 	    $load = $loadans;
 1054: 	}
 1055:     } else {
 1056: 	$load = $userloadans;
 1057:     }
 1058: 
 1059:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1060: 	$spare_server = $try_server;
 1061: 	$lowest_load  = $load;
 1062:     }
 1063:     return ($spare_server,$lowest_load);
 1064: }
 1065: 
 1066: # --------------------------- ask offload servers if user already has a session
 1067: sub find_existing_session {
 1068:     my ($udom,$uname) = @_;
 1069:     my $spareshash = &this_host_spares($udom);
 1070:     if (ref($spareshash) eq 'HASH') {
 1071:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1072:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1073:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1074:             }
 1075:         }
 1076:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1077:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1078:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1079:             }
 1080:         }
 1081:     }
 1082:     return;
 1083: }
 1084: 
 1085: # check if user's browser sent load balancer cookie and server still has session
 1086: # and is not overloaded.
 1087: sub check_for_balancer_cookie {
 1088:     my ($r,$update_mtime) = @_;
 1089:     my ($otherserver,$cookie);
 1090:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1091:     if (exists($cookies{'balanceID'})) {
 1092:         my $balid = $cookies{'balanceID'};
 1093:         $cookie=&LONCAPA::clean_handle($balid->value);
 1094:         my $balancedir=$r->dir_config('lonBalanceDir');
 1095:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1096:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1097:                 my ($possudom,$possuname) = ($1,$2);
 1098:                 my $has_session = 0;
 1099:                 if ((&domain($possudom) ne '') &&
 1100:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1101:                     my $try_server;
 1102:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1103:                     if ($opened) {
 1104:                         flock($idf,LOCK_SH);
 1105:                         while (my $line = <$idf>) {
 1106:                             chomp($line);
 1107:                             if (&hostname($line) ne '') {
 1108:                                 $try_server = $line;
 1109:                                 last;
 1110:                             }
 1111:                         }
 1112:                         close($idf);
 1113:                         if (($try_server) &&
 1114:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1115:                             my $lowest_load = 30000;
 1116:                             ($otherserver,$lowest_load) =
 1117:                                 &compare_server_load($try_server,undef,$lowest_load);
 1118:                             if ($otherserver ne '' && $lowest_load < 100) {
 1119:                                 $has_session = 1;
 1120:                             } else {
 1121:                                 undef($otherserver);
 1122:                             }
 1123:                         }
 1124:                     }
 1125:                 }
 1126:                 if ($has_session) {
 1127:                     if ($update_mtime) {
 1128:                         my $atime = my $mtime = time;
 1129:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1130:                     }
 1131:                 } else {
 1132:                     unlink("$balancedir/$cookie.id");
 1133:                 }
 1134:             }
 1135:         }
 1136:     }
 1137:     return ($otherserver,$cookie);
 1138: }
 1139: 
 1140: sub delbalcookie {
 1141:     my ($cookie,$balancer) =@_;
 1142:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1143:         my ($udom,$uname) = ($1,$2);
 1144:         my $uprimary_id = &domain($udom,'primary');
 1145:         my $uintdom = &internet_dom($uprimary_id);
 1146:         my $intdom = &internet_dom($balancer);
 1147:         my $serverhomedom = &host_domain($balancer);
 1148:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1149:             return &reply("delbalcookie:$cookie",$balancer);
 1150:         }
 1151:     }
 1152: }
 1153: 
 1154: # -------------------------------- ask if server already has a session for user
 1155: sub has_user_session {
 1156:     my ($lonid,$udom,$uname) = @_;
 1157:     my $result = &reply(join(':','userhassession',
 1158: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1159:     return 1 if ($result eq 'ok');
 1160: 
 1161:     return 0;
 1162: }
 1163: 
 1164: # --------- determine least loaded server in a user's domain which allows login
 1165: 
 1166: sub choose_server {
 1167:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1168:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1169:     my %servers = &get_servers($udom);
 1170:     my $lowest_load = 30000;
 1171:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1172:     if ($skiploadbal) {
 1173:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1174:         unless (defined($cached)) {
 1175:             my $cachetime = 60*60*24;
 1176:             my %domconfig =
 1177:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1178:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1179:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1180:                                            $cachetime);
 1181:             }
 1182:         }
 1183:     }
 1184:     foreach my $lonhost (keys(%servers)) {
 1185:         if ($skiploadbal) {
 1186:             if (ref($balancers) eq 'HASH') {
 1187:                 next if (exists($balancers->{$lonhost}));
 1188:             }
 1189:         }
 1190:         my $loginvia;
 1191:         if ($checkloginvia) {
 1192:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1193:             if ($loginvia) {
 1194:                 my ($server,$path) = split(/:/,$loginvia);
 1195:                 ($login_host, $lowest_load) =
 1196:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1197:                 if ($login_host eq $server) {
 1198:                     $portal_path = $path;
 1199:                     $isredirect = 1;
 1200:                 }
 1201:             } else {
 1202:                 ($login_host, $lowest_load) =
 1203:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1204:                 if ($login_host eq $lonhost) {
 1205:                     $portal_path = '';
 1206:                     $isredirect = ''; 
 1207:                 }
 1208:             }
 1209:         } else {
 1210:             ($login_host, $lowest_load) =
 1211:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1212:         }
 1213:     }
 1214:     if ($login_host ne '') {
 1215:         $hostname = &hostname($login_host);
 1216:     }
 1217:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1218: }
 1219: 
 1220: # --------------------------------------------- Try to change a user's password
 1221: 
 1222: sub changepass {
 1223:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1224:     $currentpass = &escape($currentpass);
 1225:     $newpass     = &escape($newpass);
 1226:     my $lonhost = $perlvar{'lonHostID'};
 1227:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1228: 		       $server);
 1229:     if (! $answer) {
 1230: 	&logthis("No reply on password change request to $server ".
 1231: 		 "by $uname in domain $udom.");
 1232:     } elsif ($answer =~ "^ok") {
 1233:         &logthis("$uname in $udom successfully changed their password ".
 1234: 		 "on $server.");
 1235:     } elsif ($answer =~ "^pwchange_failure") {
 1236: 	&logthis("$uname in $udom was unable to change their password ".
 1237: 		 "on $server.  The action was blocked by either lcpasswd ".
 1238: 		 "or pwchange");
 1239:     } elsif ($answer =~ "^non_authorized") {
 1240:         &logthis("$uname in $udom did not get their password correct when ".
 1241: 		 "attempting to change it on $server.");
 1242:     } elsif ($answer =~ "^auth_mode_error") {
 1243:         &logthis("$uname in $udom attempted to change their password despite ".
 1244: 		 "not being locally or internally authenticated on $server.");
 1245:     } elsif ($answer =~ "^unknown_user") {
 1246:         &logthis("$uname in $udom attempted to change their password ".
 1247: 		 "on $server but were unable to because $server is not ".
 1248: 		 "their home server.");
 1249:     } elsif ($answer =~ "^refused") {
 1250: 	&logthis("$server refused to change $uname in $udom password because ".
 1251: 		 "it was sent an unencrypted request to change the password.");
 1252:     } elsif ($answer =~ "invalid_client") {
 1253:         &logthis("$server refused to change $uname in $udom password because ".
 1254:                  "it was a reset by e-mail originating from an invalid server.");
 1255:     } elsif ($answer =~ "^prioruse") {
 1256:        &logthis("$server refused to change $uname in $udom password because ".
 1257:                 "the password had been used before");
 1258:     }
 1259:     return $answer;
 1260: }
 1261: 
 1262: # ----------------------- Try to determine user's current authentication scheme
 1263: 
 1264: sub queryauthenticate {
 1265:     my ($uname,$udom)=@_;
 1266:     my $uhome=&homeserver($uname,$udom);
 1267:     if (!$uhome) {
 1268: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1269: 	return 'no_host';
 1270:     }
 1271:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1272:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1273: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1274:     }
 1275:     return $answer;
 1276: }
 1277: 
 1278: # --------- Try to authenticate user from domain's lib servers (first this one)
 1279: 
 1280: sub authenticate {
 1281:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1282:     $upass=&escape($upass);
 1283:     $uname= &LONCAPA::clean_username($uname);
 1284:     my $uhome=&homeserver($uname,$udom,1);
 1285:     my $newhome;
 1286:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1287: # Maybe the machine was offline and only re-appeared again recently?
 1288:         &reconlonc();
 1289: # One more
 1290: 	$uhome=&homeserver($uname,$udom,1);
 1291:         if (($uhome eq 'no_host') && $checkdefauth) {
 1292:             if (defined(&domain($udom,'primary'))) {
 1293:                 $newhome=&domain($udom,'primary');
 1294:             }
 1295:             if ($newhome ne '') {
 1296:                 $uhome = $newhome;
 1297:             }
 1298:         }
 1299: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1300: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1301: 	    return 'no_host';
 1302:         }
 1303:     }
 1304:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1305:     if ($answer eq 'authorized') {
 1306:         if ($newhome) {
 1307:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1308:             return 'no_account_on_host'; 
 1309:         } else {
 1310:             &logthis("User $uname at $udom authorized by $uhome");
 1311:             return $uhome;
 1312:         }
 1313:     }
 1314:     if ($answer eq 'non_authorized') {
 1315: 	&logthis("User $uname at $udom rejected by $uhome");
 1316: 	return 'no_host'; 
 1317:     }
 1318:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1319:     return 'no_host';
 1320: }
 1321: 
 1322: sub can_host_session {
 1323:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1324:     my $canhost = 1;
 1325:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1326:     if (ref($remotesessions) eq 'HASH') {
 1327:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1328:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1329:                 $canhost = 0;
 1330:             } else {
 1331:                 $canhost = 1;
 1332:             }
 1333:         }
 1334:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1335:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1336:                 $canhost = 1;
 1337:             } else {
 1338:                 $canhost = 0;
 1339:             }
 1340:         }
 1341:         if ($canhost) {
 1342:             if ($remotesessions->{'version'} ne '') {
 1343:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1344:                 if ($reqmajor ne '' && $reqminor ne '') {
 1345:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1346:                         my $major = $1;
 1347:                         my $minor = $2;
 1348:                         if (($major < $reqmajor ) ||
 1349:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1350:                             $canhost = 0;
 1351:                         }
 1352:                     } else {
 1353:                         $canhost = 0;
 1354:                     }
 1355:                 }
 1356:             }
 1357:         }
 1358:     }
 1359:     if ($canhost) {
 1360:         if (ref($hostedsessions) eq 'HASH') {
 1361:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1362:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1363:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1364:                 if (($uint_dom ne '') && 
 1365:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1366:                     $canhost = 0;
 1367:                 } else {
 1368:                     $canhost = 1;
 1369:                 }
 1370:             }
 1371:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1372:                 if (($uint_dom ne '') && 
 1373:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1374:                     $canhost = 1;
 1375:                 } else {
 1376:                     $canhost = 0;
 1377:                 }
 1378:             }
 1379:         }
 1380:     }
 1381:     return $canhost;
 1382: }
 1383: 
 1384: sub spare_can_host {
 1385:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1386:     my $canhost=1;
 1387:     my $try_server_hostname = &hostname($try_server);
 1388:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1389:     my $serverhomedom = &host_domain($serverhomeID);
 1390:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1391:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1392:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1393:             $canhost = 0;
 1394:         }
 1395:     }
 1396:     if (($canhost) && ($uint_dom)) {
 1397:         my @intdoms;
 1398:         my $internet_names = &get_internet_names($try_server);
 1399:         if (ref($internet_names) eq 'ARRAY') {
 1400:             @intdoms = @{$internet_names};
 1401:         }
 1402:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1403:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1404:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1405:                                          $remotesessions,
 1406:                                          $defdomdefaults{'hostedsessions'});
 1407:         }
 1408:     }
 1409:     return $canhost;
 1410: }
 1411: 
 1412: sub this_host_spares {
 1413:     my ($dom) = @_;
 1414:     my ($dom_in_use,$lonhost_in_use,$result);
 1415:     my @hosts = &current_machine_ids();
 1416:     foreach my $lonhost (@hosts) {
 1417:         if (&host_domain($lonhost) eq $dom) {
 1418:             $dom_in_use = $dom;
 1419:             $lonhost_in_use = $lonhost;
 1420:             last;
 1421:         }
 1422:     }
 1423:     if ($dom_in_use ne '') {
 1424:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1425:     }
 1426:     if (ref($result) ne 'HASH') {
 1427:         $lonhost_in_use = $perlvar{'lonHostID'};
 1428:         $dom_in_use = &host_domain($lonhost_in_use);
 1429:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1430:         if (ref($result) ne 'HASH') {
 1431:             $result = \%spareid;
 1432:         }
 1433:     }
 1434:     return $result;
 1435: }
 1436: 
 1437: sub spares_for_offload  {
 1438:     my ($dom_in_use,$lonhost_in_use) = @_;
 1439:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1440:     if (defined($cached)) {
 1441:         return $result;
 1442:     } else {
 1443:         my $cachetime = 60*60*24;
 1444:         my %domconfig =
 1445:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1446:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1447:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1448:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1449:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1450:                 }
 1451:             }
 1452:         }
 1453:     }
 1454:     return;
 1455: }
 1456: 
 1457: sub get_lonbalancer_config {
 1458:     my ($servers) = @_;
 1459:     my ($currbalancer,$currtargets);
 1460:     if (ref($servers) eq 'HASH') {
 1461:         foreach my $server (keys(%{$servers})) {
 1462:             my %what = (
 1463:                          spareid => 1,
 1464:                          perlvar => 1,
 1465:                        );
 1466:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1467:             if ($result eq 'ok') {
 1468:                 if (ref($returnhash) eq 'HASH') {
 1469:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1470:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1471:                             $currbalancer = $server;
 1472:                             $currtargets = {};
 1473:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1474:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1475:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1476:                                 }
 1477:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1478:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1479:                                 }
 1480:                             }
 1481:                             last;
 1482:                         }
 1483:                     }
 1484:                 }
 1485:             }
 1486:         }
 1487:     }
 1488:     return ($currbalancer,$currtargets);
 1489: }
 1490: 
 1491: sub check_loadbalancing {
 1492:     my ($uname,$udom,$caller) = @_;
 1493:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1494:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1495:     my $lonhost = $perlvar{'lonHostID'};
 1496:     my @hosts = &current_machine_ids();
 1497:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1498:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1499:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1500:     my $serverhomedom = &host_domain($lonhost);
 1501:     my $domneedscache;
 1502:     my $cachetime = 60*60*24;
 1503: 
 1504:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1505:         $dom_in_use = $udom;
 1506:         $homeintdom = 1;
 1507:     } else {
 1508:         $dom_in_use = $serverhomedom;
 1509:     }
 1510:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1511:     unless (defined($cached)) {
 1512:         my %domconfig =
 1513:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1514:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1515:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1516:         } else {
 1517:             $domneedscache = $dom_in_use;
 1518:         }
 1519:     }
 1520:     if (ref($result) eq 'HASH') {
 1521:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1522:             &check_balancer_result($result,@hosts);
 1523:         if ($is_balancer) {
 1524:             if (ref($currrules) eq 'HASH') {
 1525:                 if ($homeintdom) {
 1526:                     if ($uname ne '') {
 1527:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1528:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1529:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1530:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1531:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1532:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1533:                             }
 1534:                         }
 1535:                         if ($rule_in_effect eq '') {
 1536:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1537:                             if ($userenv{'inststatus'} ne '') {
 1538:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1539:                                 my ($othertitle,$usertypes,$types) =
 1540:                                     &Apache::loncommon::sorted_inst_types($udom);
 1541:                                 if (ref($types) eq 'ARRAY') {
 1542:                                     foreach my $type (@{$types}) {
 1543:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1544:                                             if (exists($currrules->{$type})) {
 1545:                                                 $rule_in_effect = $currrules->{$type};
 1546:                                             }
 1547:                                         }
 1548:                                     }
 1549:                                 }
 1550:                             } else {
 1551:                                 if (exists($currrules->{'default'})) {
 1552:                                     $rule_in_effect = $currrules->{'default'};
 1553:                                 }
 1554:                             }
 1555:                         }
 1556:                     } else {
 1557:                         if (exists($currrules->{'default'})) {
 1558:                             $rule_in_effect = $currrules->{'default'};
 1559:                         }
 1560:                     }
 1561:                 } else {
 1562:                     if ($currrules->{'_LC_external'} ne '') {
 1563:                         $rule_in_effect = $currrules->{'_LC_external'};
 1564:                     }
 1565:                 }
 1566:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1567:                                                        $uname,$udom);
 1568:             }
 1569:         }
 1570:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1571:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1572:         unless (defined($cached)) {
 1573:             my %domconfig =
 1574:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1575:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1576:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1577:             } else {
 1578:                 $domneedscache = $serverhomedom;
 1579:             }
 1580:         }
 1581:         if (ref($result) eq 'HASH') {
 1582:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1583:                 &check_balancer_result($result,@hosts);
 1584:             if ($is_balancer) {
 1585:                 if (ref($currrules) eq 'HASH') {
 1586:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1587:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1588:                     }
 1589:                 }
 1590:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1591:                                                        $uname,$udom);
 1592:             }
 1593:         } else {
 1594:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1595:                 $is_balancer = 1;
 1596:                 $offloadto = &this_host_spares($dom_in_use);
 1597:             }
 1598:             unless (defined($cached)) {
 1599:                 $domneedscache = $serverhomedom;
 1600:             }
 1601:         }
 1602:     } else {
 1603:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1604:             $is_balancer = 1;
 1605:             $offloadto = &this_host_spares($dom_in_use);
 1606:         }
 1607:         unless (defined($cached)) {
 1608:             $domneedscache = $serverhomedom;
 1609:         }
 1610:     }
 1611:     if ($domneedscache) {
 1612:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1613:     }
 1614:     if ($is_balancer) {
 1615:         my $lowest_load = 30000;
 1616:         if (ref($offloadto) eq 'HASH') {
 1617:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1618:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1619:                     ($otherserver,$lowest_load) =
 1620:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1621:                 }
 1622:             }
 1623:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1624: 
 1625:             if (!$found_server) {
 1626:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1627:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1628:                         ($otherserver,$lowest_load) =
 1629:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1630:                     }
 1631:                 }
 1632:             }
 1633:         } elsif (ref($offloadto) eq 'ARRAY') {
 1634:             if (@{$offloadto} == 1) {
 1635:                 $otherserver = $offloadto->[0];
 1636:             } elsif (@{$offloadto} > 1) {
 1637:                 foreach my $try_server (@{$offloadto}) {
 1638:                     ($otherserver,$lowest_load) =
 1639:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1640:                 }
 1641:             }
 1642:         }
 1643:         unless ($caller eq 'login') {
 1644:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1645:                 $is_balancer = 0;
 1646:                 if ($uname ne '' && $udom ne '') {
 1647:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1648:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1649:                                  'user.loadbalcheck.time' => time});
 1650:                     }
 1651:                 }
 1652:             }
 1653:         }
 1654:         unless ($homeintdom) {
 1655:             undef($setcookie);
 1656:         }
 1657:     }
 1658:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1659: }
 1660: 
 1661: sub check_balancer_result {
 1662:     my ($result,@hosts) = @_;
 1663:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1664:     if (ref($result) eq 'HASH') {
 1665:         if ($result->{'lonhost'} ne '') {
 1666:             my $currbalancer = $result->{'lonhost'};
 1667:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1668:                 $is_balancer = 1;
 1669:                 $currtargets = $result->{'targets'};
 1670:                 $currrules = $result->{'rules'};
 1671:             }
 1672:             $dom_balancers = $currbalancer;
 1673:         } else {
 1674:             if (keys(%{$result})) {
 1675:                 foreach my $key (keys(%{$result})) {
 1676:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1677:                         (ref($result->{$key}) eq 'HASH')) {
 1678:                         $is_balancer = 1;
 1679:                         $currrules = $result->{$key}{'rules'};
 1680:                         $currtargets = $result->{$key}{'targets'};
 1681:                         $setcookie = $result->{$key}{'cookie'};
 1682:                         last;
 1683:                     }
 1684:                 }
 1685:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1686:             }
 1687:         }
 1688:     }
 1689:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1690: }
 1691: 
 1692: sub get_loadbalancer_targets {
 1693:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1694:     my $offloadto;
 1695:     if ($rule_in_effect eq 'none') {
 1696:         return [$perlvar{'lonHostID'}];
 1697:     } elsif ($rule_in_effect eq '') {
 1698:         $offloadto = $currtargets;
 1699:     } else {
 1700:         if ($rule_in_effect eq 'homeserver') {
 1701:             my $homeserver = &homeserver($uname,$udom);
 1702:             if ($homeserver ne 'no_host') {
 1703:                 $offloadto = [$homeserver];
 1704:             }
 1705:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1706:             my %domconfig =
 1707:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1708:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1709:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1710:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1711:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1712:                     }
 1713:                 }
 1714:             } else {
 1715:                 my %servers = &internet_dom_servers($udom);
 1716:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1717:                 if (&hostname($remotebalancer) ne '') {
 1718:                     $offloadto = [$remotebalancer];
 1719:                 }
 1720:             }
 1721:         } elsif (&hostname($rule_in_effect) ne '') {
 1722:             $offloadto = [$rule_in_effect];
 1723:         }
 1724:     }
 1725:     return $offloadto;
 1726: }
 1727: 
 1728: sub internet_dom_servers {
 1729:     my ($dom) = @_;
 1730:     my (%uniqservers,%servers);
 1731:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1732:     my @machinedoms = &machine_domains($primaryserver);
 1733:     foreach my $mdom (@machinedoms) {
 1734:         my %currservers = %servers;
 1735:         my %server = &get_servers($mdom);
 1736:         %servers = (%currservers,%server);
 1737:     }
 1738:     my %by_hostname;
 1739:     foreach my $id (keys(%servers)) {
 1740:         push(@{$by_hostname{$servers{$id}}},$id);
 1741:     }
 1742:     foreach my $hostname (sort(keys(%by_hostname))) {
 1743:         if (@{$by_hostname{$hostname}} > 1) {
 1744:             my $match = 0;
 1745:             foreach my $id (@{$by_hostname{$hostname}}) {
 1746:                 if (&host_domain($id) eq $dom) {
 1747:                     $uniqservers{$id} = $hostname;
 1748:                     $match = 1;
 1749:                 }
 1750:             }
 1751:             unless ($match) {
 1752:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1753:             }
 1754:         } else {
 1755:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1756:         }
 1757:     }
 1758:     return %uniqservers;
 1759: }
 1760: 
 1761: sub trusted_domains {
 1762:     my ($cmdtype,$calldom) = @_;
 1763:     my ($trusted,$untrusted);
 1764:     if (&domain($calldom) eq '') {
 1765:         return ($trusted,$untrusted);
 1766:     }
 1767:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1768:         return ($trusted,$untrusted);
 1769:     }
 1770:     my $callprimary = &domain($calldom,'primary');
 1771:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1772:     if ($intcalldom eq '') {
 1773:         return ($trusted,$untrusted);
 1774:     }
 1775: 
 1776:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1777:     unless (defined($cached)) {
 1778:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1779:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1780:         $trustconfig = $domconfig{'trust'};
 1781:     }
 1782:     if (ref($trustconfig)) {
 1783:         my (%possexc,%possinc,@allexc,@allinc); 
 1784:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1785:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1786:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1787:             }
 1788:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1789:                 $possinc{$intcalldom} = 1;
 1790:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1791:             }
 1792:         }
 1793:         if (keys(%possexc)) {
 1794:             if (keys(%possinc)) {
 1795:                 foreach my $key (sort(keys(%possexc))) {
 1796:                     next if ($key eq $intcalldom);
 1797:                     unless ($possinc{$key}) {
 1798:                         push(@allexc,$key);
 1799:                     }
 1800:                 }
 1801:             } else {
 1802:                 @allexc = sort(keys(%possexc));
 1803:             }
 1804:         }
 1805:         if (keys(%possinc)) {
 1806:             $possinc{$intcalldom} = 1;
 1807:             @allinc = sort(keys(%possinc));
 1808:         }
 1809:         if ((@allexc > 0) || (@allinc > 0)) {
 1810:             my %doms_by_intdom;
 1811:             my %allintdoms = &all_host_intdom();
 1812:             my %alldoms = &all_host_domain();
 1813:             foreach my $key (%allintdoms) {
 1814:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1815:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1816:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1817:                     }
 1818:                 } else {
 1819:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1820:                 }
 1821:             }
 1822:             foreach my $exc (@allexc) {
 1823:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1824:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1825:                 }
 1826:             }
 1827:             foreach my $inc (@allinc) {
 1828:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1829:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1830:                 }
 1831:             }
 1832:         }
 1833:     }
 1834:     return ($trusted,$untrusted);
 1835: }
 1836: 
 1837: sub will_trust {
 1838:     my ($cmdtype,$domain,$possdom) = @_;
 1839:     return 1 if ($domain eq $possdom);
 1840:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1841:     my $willtrust; 
 1842:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1843:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1844:             $willtrust = 1;
 1845:         }
 1846:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1847:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1848:             $willtrust = 1;
 1849:         }
 1850:     } else {
 1851:         $willtrust = 1;
 1852:     }
 1853:     return $willtrust;
 1854: }
 1855: 
 1856: # ---------------------- Find the homebase for a user from domain's lib servers
 1857: 
 1858: my %homecache;
 1859: sub homeserver {
 1860:     my ($uname,$udom,$ignoreBadCache)=@_;
 1861:     my $index="$uname:$udom";
 1862: 
 1863:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1864: 
 1865:     my %servers = &get_servers($udom,'library');
 1866:     foreach my $tryserver (keys(%servers)) {
 1867:         next if ($ignoreBadCache ne 'true' && 
 1868: 		 exists($badServerCache{$tryserver}));
 1869: 
 1870: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1871: 	if ($answer eq 'found') {
 1872: 	    delete($badServerCache{$tryserver}); 
 1873: 	    return $homecache{$index}=$tryserver;
 1874: 	} elsif ($answer eq 'no_host') {
 1875: 	    $badServerCache{$tryserver}=1;
 1876: 	}
 1877:     }    
 1878:     return 'no_host';
 1879: }
 1880: 
 1881: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1882: 
 1883: sub idget {
 1884:     my ($udom,$idsref,$namespace)=@_;
 1885:     my %returnhash=();
 1886:     my @ids=(); 
 1887:     if (ref($idsref) eq 'ARRAY') {
 1888:         @ids = @{$idsref};
 1889:     } else {
 1890:         return %returnhash; 
 1891:     }
 1892:     if ($namespace eq '') {
 1893:         $namespace = 'ids';
 1894:     }
 1895:     
 1896:     my %servers = &get_servers($udom,'library');
 1897:     foreach my $tryserver (keys(%servers)) {
 1898: 	my $idlist=join('&', map { &escape($_); } @ids);
 1899: 	if ($namespace eq 'ids') {
 1900: 	    $idlist=~tr/A-Z/a-z/;
 1901: 	}
 1902: 	my $reply;
 1903: 	if ($namespace eq 'ids') {
 1904: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1905: 	} else {
 1906: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1907: 	}
 1908: 	my @answer=();
 1909: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1910: 	    @answer=split(/\&/,$reply);
 1911: 	}                    ;
 1912: 	my $i;
 1913: 	for ($i=0;$i<=$#ids;$i++) {
 1914: 	    if ($answer[$i]) {
 1915: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1916: 	    }
 1917: 	}
 1918:     }
 1919:     return %returnhash;
 1920: }
 1921: 
 1922: # ------------------------------------- Find the IDs behind a list of usernames
 1923: 
 1924: sub idrget {
 1925:     my ($udom,@unames)=@_;
 1926:     my %returnhash=();
 1927:     foreach my $uname (@unames) {
 1928:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1929:     }
 1930:     return %returnhash;
 1931: }
 1932: 
 1933: # Store away a list of names and associated student/employee IDs or clicker IDs
 1934: 
 1935: sub idput {
 1936:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1937:     my %servers=();
 1938:     my %ids=();
 1939:     my %byid = ();
 1940:     if (ref($idsref) eq 'HASH') {
 1941:         %ids=%{$idsref};
 1942:     }
 1943:     if ($namespace eq '') {
 1944:         $namespace = 'ids'; 
 1945:     }
 1946:     foreach my $uname (keys(%ids)) {
 1947: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1948:         if ($uhom eq '') {
 1949:             $uhom=&homeserver($uname,$udom);
 1950:         }
 1951:         if ($uhom ne 'no_host') {
 1952:             my $esc_unam=&escape($uname);
 1953:             if ($namespace eq 'ids') {
 1954:                 my $id=&escape($ids{$uname});
 1955:                 $id=~tr/A-Z/a-z/;
 1956:                 my $esc_unam=&escape($uname);
 1957:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1958:             } else {
 1959:                 my @currids = split(/,/,$ids{$uname});
 1960:                 foreach my $id (@currids) {
 1961:                     $byid{$uhom}{$id} .= $uname.',';
 1962:                 }
 1963:             }
 1964:         }
 1965:     }
 1966:     if ($namespace eq 'clickers') {
 1967:         foreach my $server (keys(%byid)) {
 1968:             if (ref($byid{$server}) eq 'HASH') {
 1969:                 foreach my $id (keys(%{$byid{$server}})) {
 1970:                     $byid{$server} =~ s/,$//;
 1971:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1972:                 }
 1973:             }
 1974:         }
 1975:     }
 1976:     foreach my $server (keys(%servers)) {
 1977:         $servers{$server} =~ s/\&$//;
 1978:         if ($namespace eq 'ids') {     
 1979:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1980:         } else {
 1981:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1982:         }
 1983:     }
 1984: }
 1985: 
 1986: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1987: 
 1988: sub iddel {
 1989:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1990:     my %result=();
 1991:     my %ids=();
 1992:     my %byid = ();
 1993:     if (ref($idshashref) eq 'HASH') {
 1994:         %ids=%{$idshashref};
 1995:     } else {
 1996:         return %result;
 1997:     }
 1998:     if ($namespace eq '') {
 1999:         $namespace = 'ids';
 2000:     }
 2001:     my %servers=();
 2002:     while (my ($id,$unamestr) = each(%ids)) {
 2003:         if ($namespace eq 'ids') {
 2004:             my $uhom = $uhome;
 2005:             if ($uhom eq '') { 
 2006:                 $uhom=&homeserver($unamestr,$udom);
 2007:             }
 2008:             if ($uhom ne 'no_host') {
 2009:                 $servers{$uhom}.='&'.&escape($id);
 2010:             }
 2011:          } else {
 2012:             my @curritems = split(/,/,$ids{$id});
 2013:             foreach my $uname (@curritems) {
 2014:                 my $uhom = $uhome;
 2015:                 if ($uhom eq '') {
 2016:                     $uhom=&homeserver($uname,$udom);
 2017:                 }
 2018:                 if ($uhom ne 'no_host') { 
 2019:                     $byid{$uhom}{$id} .= $uname.',';
 2020:                 }
 2021:             }
 2022:         }
 2023:     }
 2024:     if ($namespace eq 'clickers') {
 2025:         foreach my $server (keys(%byid)) {
 2026:             if (ref($byid{$server}) eq 'HASH') {
 2027:                 foreach my $id (keys(%{$byid{$server}})) {
 2028:                     $byid{$server}{$id} =~ s/,$//;
 2029:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2030:                 }
 2031:             }
 2032:         }
 2033:     }
 2034:     foreach my $server (keys(%servers)) {
 2035:         $servers{$server} =~ s/\&$//;
 2036:         if ($namespace eq 'ids') {
 2037:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2038:         } elsif ($namespace eq 'clickers') {
 2039:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2040:         }
 2041:     }
 2042:     return %result;
 2043: }
 2044: 
 2045: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2046: 
 2047: sub updateclickers {
 2048:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2049:     my %clickers;
 2050:     if (ref($idshashref) eq 'HASH') {
 2051:         %clickers=%{$idshashref};
 2052:     } else {
 2053:         return;
 2054:     }
 2055:     my $items='';
 2056:     foreach my $item (keys(%clickers)) {
 2057:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2058:     }
 2059:     $items=~s/\&$//;
 2060:     my $request = "updateclickers:$udom:$action:$items";
 2061:     if ($critical) {
 2062:         return &critical($request,$uhome);
 2063:     } else {
 2064:         return &reply($request,$uhome);
 2065:     }
 2066: }
 2067: 
 2068: # ------------------------------dump from db file owned by domainconfig user
 2069: sub dump_dom {
 2070:     my ($namespace, $udom, $regexp) = @_;
 2071: 
 2072:     $udom ||= $env{'user.domain'};
 2073: 
 2074:     return () unless $udom;
 2075: 
 2076:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2077: }
 2078: 
 2079: # ------------------------------------------ get items from domain db files   
 2080: 
 2081: sub get_dom {
 2082:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2083:     return if ($udom eq 'public');
 2084:     my $items='';
 2085:     foreach my $item (@$storearr) {
 2086:         $items.=&escape($item).'&';
 2087:     }
 2088:     $items=~s/\&$//;
 2089:     if (!$udom) {
 2090:         $udom=$env{'user.domain'};
 2091:         return if ($udom eq 'public');
 2092:         if (defined(&domain($udom,'primary'))) {
 2093:             $uhome=&domain($udom,'primary');
 2094:         } else {
 2095:             undef($uhome);
 2096:         }
 2097:     } else {
 2098:         if (!$uhome) {
 2099:             if (defined(&domain($udom,'primary'))) {
 2100:                 $uhome=&domain($udom,'primary');
 2101:             }
 2102:         }
 2103:     }
 2104:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2105:         my $rep;
 2106:         if ($namespace =~ /^enc/) {
 2107:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2108:         } else {
 2109:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2110:         }
 2111:         my %returnhash;
 2112:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2113:             return %returnhash;
 2114:         }
 2115:         my @pairs=split(/\&/,$rep);
 2116:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2117:             return @pairs;
 2118:         }
 2119:         my $i=0;
 2120:         foreach my $item (@$storearr) {
 2121:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2122:             $i++;
 2123:         }
 2124:         return %returnhash;
 2125:     } else {
 2126:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2127:     }
 2128: }
 2129: 
 2130: # -------------------------------------------- put items in domain db files 
 2131: 
 2132: sub put_dom {
 2133:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2134:     if (!$udom) {
 2135:         $udom=$env{'user.domain'};
 2136:         if (defined(&domain($udom,'primary'))) {
 2137:             $uhome=&domain($udom,'primary');
 2138:         } else {
 2139:             undef($uhome);
 2140:         }
 2141:     } else {
 2142:         if (!$uhome) {
 2143:             if (defined(&domain($udom,'primary'))) {
 2144:                 $uhome=&domain($udom,'primary');
 2145:             }
 2146:         }
 2147:     } 
 2148:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2149:         my $items='';
 2150:         foreach my $item (keys(%$storehash)) {
 2151:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2152:         }
 2153:         $items=~s/\&$//;
 2154:         if ($namespace =~ /^enc/) {
 2155:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2156:         } else {
 2157:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2158:         }
 2159:     } else {
 2160:         &logthis("put_dom failed - no homeserver and/or domain");
 2161:     }
 2162: }
 2163: 
 2164: # --------------------- newput for items in db file owned by domainconfig user
 2165: sub newput_dom {
 2166:     my ($namespace,$storehash,$udom) = @_;
 2167:     my $result;
 2168:     if (!$udom) {
 2169:         $udom=$env{'user.domain'};
 2170:     }
 2171:     if ($udom) {
 2172:         my $uname = &get_domainconfiguser($udom);
 2173:         $result = &newput($namespace,$storehash,$udom,$uname);
 2174:     }
 2175:     return $result;
 2176: }
 2177: 
 2178: # --------------------- delete for items in db file owned by domainconfig user
 2179: sub del_dom {
 2180:     my ($namespace,$storearr,$udom)=@_;
 2181:     if (ref($storearr) eq 'ARRAY') {
 2182:         if (!$udom) {
 2183:             $udom=$env{'user.domain'};
 2184:         }
 2185:         if ($udom) {
 2186:             my $uname = &get_domainconfiguser($udom); 
 2187:             return &del($namespace,$storearr,$udom,$uname);
 2188:         }
 2189:     }
 2190: }
 2191: 
 2192: # ----------------------------------construct domainconfig user for a domain 
 2193: sub get_domainconfiguser {
 2194:     my ($udom) = @_;
 2195:     return $udom.'-domainconfig';
 2196: }
 2197: 
 2198: sub retrieve_inst_usertypes {
 2199:     my ($udom) = @_;
 2200:     my (%returnhash,@order);
 2201:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2202:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2203:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2204:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2205:     } else {
 2206:         if (defined(&domain($udom,'primary'))) {
 2207:             my $uhome=&domain($udom,'primary');
 2208:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2209:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2210:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2211:                 return (\%returnhash,\@order);
 2212:             }
 2213:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2214:             my @pairs=split(/\&/,$hashitems);
 2215:             foreach my $item (@pairs) {
 2216:                 my ($key,$value)=split(/=/,$item,2);
 2217:                 $key = &unescape($key);
 2218:                 next if ($key =~ /^error: 2 /);
 2219:                 $returnhash{$key}=&thaw_unescape($value);
 2220:             }
 2221:             my @esc_order = split(/\&/,$orderitems);
 2222:             foreach my $item (@esc_order) {
 2223:                 push(@order,&unescape($item));
 2224:             }
 2225:         } else {
 2226:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2227:         }
 2228:         return (\%returnhash,\@order);
 2229:     }
 2230: }
 2231: 
 2232: sub is_domainimage {
 2233:     my ($url) = @_;
 2234:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2235:         if (&domain($1) ne '') {
 2236:             return '1';
 2237:         }
 2238:     }
 2239:     return;
 2240: }
 2241: 
 2242: sub inst_directory_query {
 2243:     my ($srch) = @_;
 2244:     my $udom = $srch->{'srchdomain'};
 2245:     my %results;
 2246:     my $homeserver = &domain($udom,'primary');
 2247:     my $outcome;
 2248:     if ($homeserver ne '') {
 2249:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2250:             if ($srch->{'srchby'} eq 'email') {
 2251:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2252:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2253:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2254:                     (($major == 2) && ($minor < 12))) {
 2255:                     return;
 2256:                 }
 2257:             }
 2258:         }
 2259: 	my $queryid=&reply("querysend:instdirsearch:".
 2260: 			   &escape($srch->{'srchby'}).':'.
 2261: 			   &escape($srch->{'srchterm'}).':'.
 2262: 			   &escape($srch->{'srchtype'}),$homeserver);
 2263: 	my $host=&hostname($homeserver);
 2264: 	if ($queryid !~/^\Q$host\E\_/) {
 2265: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2266: 	    return;
 2267: 	}
 2268: 	my $response = &get_query_reply($queryid);
 2269: 	my $maxtries = 5;
 2270: 	my $tries = 1;
 2271: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2272: 	    $response = &get_query_reply($queryid);
 2273: 	    $tries ++;
 2274: 	}
 2275: 
 2276:         if (!&error($response) && $response ne 'refused') {
 2277:             if ($response eq 'unavailable') {
 2278:                 $outcome = $response;
 2279:             } else {
 2280:                 $outcome = 'ok';
 2281:                 my @matches = split(/\n/,$response);
 2282:                 foreach my $match (@matches) {
 2283:                     my ($key,$value) = split(/=/,$match);
 2284:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2285:                 }
 2286:             }
 2287:         }
 2288:     }
 2289:     return ($outcome,%results);
 2290: }
 2291: 
 2292: sub usersearch {
 2293:     my ($srch) = @_;
 2294:     my $dom = $srch->{'srchdomain'};
 2295:     my %results;
 2296:     my %libserv = &all_library();
 2297:     my $query = 'usersearch';
 2298:     foreach my $tryserver (keys(%libserv)) {
 2299:         if (&host_domain($tryserver) eq $dom) {
 2300:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2301:                 if ($srch->{'srchby'} eq 'email') {
 2302:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2303:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2304:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2305:                              (($major == 2) && ($minor < 12)));
 2306:                 }
 2307:             }
 2308:             my $host=&hostname($tryserver);
 2309:             my $queryid=
 2310:                 &reply("querysend:".&escape($query).':'.
 2311:                        &escape($srch->{'srchby'}).':'.
 2312:                        &escape($srch->{'srchtype'}).':'.
 2313:                        &escape($srch->{'srchterm'}),$tryserver);
 2314:             if ($queryid !~/^\Q$host\E\_/) {
 2315:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2316:                 next;
 2317:             }
 2318:             my $reply = &get_query_reply($queryid);
 2319:             my $maxtries = 1;
 2320:             my $tries = 1;
 2321:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2322:                 $reply = &get_query_reply($queryid);
 2323:                 $tries ++;
 2324:             }
 2325:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2326:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2327:             } else {
 2328:                 my @matches;
 2329:                 if ($reply =~ /\n/) {
 2330:                     @matches = split(/\n/,$reply);
 2331:                 } else {
 2332:                     @matches = split(/\&/,$reply);
 2333:                 }
 2334:                 foreach my $match (@matches) {
 2335:                     my ($uname,$udom,%userhash);
 2336:                     foreach my $entry (split(/:/,$match)) {
 2337:                         my ($key,$value) =
 2338:                             map {&unescape($_);} split(/=/,$entry);
 2339:                         $userhash{$key} = $value;
 2340:                         if ($key eq 'username') {
 2341:                             $uname = $value;
 2342:                         } elsif ($key eq 'domain') {
 2343:                             $udom = $value;
 2344:                         }
 2345:                     }
 2346:                     $results{$uname.':'.$udom} = \%userhash;
 2347:                 }
 2348:             }
 2349:         }
 2350:     }
 2351:     return %results;
 2352: }
 2353: 
 2354: sub get_instuser {
 2355:     my ($udom,$uname,$id) = @_;
 2356:     my $homeserver = &domain($udom,'primary');
 2357:     my ($outcome,%results);
 2358:     if ($homeserver ne '') {
 2359:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2360:                            &escape($id).':'.&escape($udom),$homeserver);
 2361:         my $host=&hostname($homeserver);
 2362:         if ($queryid !~/^\Q$host\E\_/) {
 2363:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2364:             return;
 2365:         }
 2366:         my $response = &get_query_reply($queryid);
 2367:         my $maxtries = 5;
 2368:         my $tries = 1;
 2369:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2370:             $response = &get_query_reply($queryid);
 2371:             $tries ++;
 2372:         }
 2373:         if (!&error($response) && $response ne 'refused') {
 2374:             if ($response eq 'unavailable') {
 2375:                 $outcome = $response;
 2376:             } else {
 2377:                 $outcome = 'ok';
 2378:                 my @matches = split(/\n/,$response);
 2379:                 foreach my $match (@matches) {
 2380:                     my ($key,$value) = split(/=/,$match);
 2381:                     $results{&unescape($key)} = &thaw_unescape($value);
 2382:                 }
 2383:             }
 2384:         }
 2385:     }
 2386:     my %userinfo;
 2387:     if (ref($results{$uname}) eq 'HASH') {
 2388:         %userinfo = %{$results{$uname}};
 2389:     } 
 2390:     return ($outcome,%userinfo);
 2391: }
 2392: 
 2393: sub get_multiple_instusers {
 2394:     my ($udom,$users,$caller) = @_;
 2395:     my ($outcome,$results);
 2396:     if (ref($users) eq 'HASH') {
 2397:         my $count = keys(%{$users}); 
 2398:         my $requested = &freeze_escape($users);
 2399:         my $homeserver = &domain($udom,'primary');
 2400:         if ($homeserver ne '') {
 2401:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2402:             my $host=&hostname($homeserver);
 2403:             if ($queryid !~/^\Q$host\E\_/) {
 2404:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2405:                          ' for host: '.$homeserver.'in domain '.$udom);
 2406:                 return ($outcome,$results);
 2407:             }
 2408:             my $response = &get_query_reply($queryid);
 2409:             my $maxtries = 5;
 2410:             if ($count > 100) {
 2411:                 $maxtries = 1+int($count/20);
 2412:             }
 2413:             my $tries = 1;
 2414:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2415:                 $response = &get_query_reply($queryid);
 2416:                 $tries ++;
 2417:             }
 2418:             if ($response eq '') {
 2419:                 $results = {};
 2420:                 foreach my $key (keys(%{$users})) {
 2421:                     my ($uname,$id);
 2422:                     if ($caller eq 'id') {
 2423:                         $id = $key;
 2424:                     } else {
 2425:                         $uname = $key;
 2426:                     }
 2427:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2428:                     $outcome = $resp;
 2429:                     if ($resp eq 'ok') {
 2430:                         %{$results} = (%{$results}, %info);
 2431:                     } else {
 2432:                         last;
 2433:                     }
 2434:                 }
 2435:             } elsif(!&error($response) && ($response ne 'refused')) {
 2436:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2437:                     $outcome = $response;
 2438:                 } else {
 2439:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2440:                     if ($outcome eq 'ok') {
 2441:                         $results = &thaw_unescape($userdata); 
 2442:                     }
 2443:                 }
 2444:             }
 2445:         }
 2446:     }
 2447:     return ($outcome,$results);
 2448: }
 2449: 
 2450: sub inst_rulecheck {
 2451:     my ($udom,$uname,$id,$item,$rules) = @_;
 2452:     my %returnhash;
 2453:     if ($udom ne '') {
 2454:         if (ref($rules) eq 'ARRAY') {
 2455:             @{$rules} = map {&escape($_);} (@{$rules});
 2456:             my $rulestr = join(':',@{$rules});
 2457:             my $homeserver=&domain($udom,'primary');
 2458:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2459:                 my $response;
 2460:                 if ($item eq 'username') {                
 2461:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2462:                                               ':'.&escape($uname).':'.$rulestr,
 2463:                                               $homeserver));
 2464:                 } elsif ($item eq 'id') {
 2465:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2466:                                               ':'.&escape($id).':'.$rulestr,
 2467:                                               $homeserver));
 2468:                 } elsif ($item eq 'selfcreate') {
 2469:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2470:                                                &escape($udom).':'.&escape($uname).
 2471:                                               ':'.$rulestr,$homeserver));
 2472:                 }
 2473:                 if ($response ne 'refused') {
 2474:                     my @pairs=split(/\&/,$response);
 2475:                     foreach my $item (@pairs) {
 2476:                         my ($key,$value)=split(/=/,$item,2);
 2477:                         $key = &unescape($key);
 2478:                         next if ($key =~ /^error: 2 /);
 2479:                         $returnhash{$key}=&thaw_unescape($value);
 2480:                     }
 2481:                 }
 2482:             }
 2483:         }
 2484:     }
 2485:     return %returnhash;
 2486: }
 2487: 
 2488: sub inst_userrules {
 2489:     my ($udom,$check) = @_;
 2490:     my (%ruleshash,@ruleorder);
 2491:     if ($udom ne '') {
 2492:         my $homeserver=&domain($udom,'primary');
 2493:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2494:             my $response;
 2495:             if ($check eq 'id') {
 2496:                 $response=&reply('instidrules:'.&escape($udom),
 2497:                                  $homeserver);
 2498:             } elsif ($check eq 'email') {
 2499:                 $response=&reply('instemailrules:'.&escape($udom),
 2500:                                  $homeserver);
 2501:             } else {
 2502:                 $response=&reply('instuserrules:'.&escape($udom),
 2503:                                  $homeserver);
 2504:             }
 2505:             if (($response ne 'refused') && ($response ne 'error') && 
 2506:                 ($response ne 'unknown_cmd') && 
 2507:                 ($response ne 'no_such_host')) {
 2508:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2509:                 my @pairs=split(/\&/,$hashitems);
 2510:                 foreach my $item (@pairs) {
 2511:                     my ($key,$value)=split(/=/,$item,2);
 2512:                     $key = &unescape($key);
 2513:                     next if ($key =~ /^error: 2 /);
 2514:                     $ruleshash{$key}=&thaw_unescape($value);
 2515:                 }
 2516:                 my @esc_order = split(/\&/,$orderitems);
 2517:                 foreach my $item (@esc_order) {
 2518:                     push(@ruleorder,&unescape($item));
 2519:                 }
 2520:             }
 2521:         }
 2522:     }
 2523:     return (\%ruleshash,\@ruleorder);
 2524: }
 2525: 
 2526: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2527: 
 2528: sub get_domain_defaults {
 2529:     my ($domain,$ignore_cache) = @_;
 2530:     return if (($domain eq '') || ($domain eq 'public'));
 2531:     my $cachetime = 60*60*24;
 2532:     unless ($ignore_cache) {
 2533:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2534:         if (defined($cached)) {
 2535:             if (ref($result) eq 'HASH') {
 2536:                 return %{$result};
 2537:             }
 2538:         }
 2539:     }
 2540:     my %domdefaults;
 2541:     my %domconfig =
 2542:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2543:                                   'requestcourses','inststatus',
 2544:                                   'coursedefaults','usersessions',
 2545:                                   'requestauthor','selfenrollment',
 2546:                                   'coursecategories','ssl','autoenroll',
 2547:                                   'trust','helpsettings'],$domain);
 2548:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2549:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2550:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2551:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2552:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2553:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2554:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2555:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2556:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2557:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2558:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2559:     } else {
 2560:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2561:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2562:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2563:     }
 2564:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2565:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2566:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2567:         } else {
 2568:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2569:         }
 2570:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2571:         foreach my $item (@usertools) {
 2572:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2573:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2574:             }
 2575:         }
 2576:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2577:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2578:         }
 2579:     }
 2580:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2581:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2582:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2583:         }
 2584:     }
 2585:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2586:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2587:     }
 2588:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2589:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2590:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2591:         }
 2592:     }
 2593:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2594:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2595:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2596:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2597:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2598:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2599:         }
 2600:         foreach my $type (@coursetypes) {
 2601:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2602:                 unless ($type eq 'community') {
 2603:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2604:                 }
 2605:             }
 2606:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2607:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2608:             }
 2609:             if ($domdefaults{'postsubmit'} eq 'on') {
 2610:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2611:                     $domdefaults{$type.'postsubtimeout'} = 
 2612:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2613:                 }
 2614:             }
 2615:         }
 2616:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2617:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2618:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2619:                 if (@clonecodes) {
 2620:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2621:                 }
 2622:             }
 2623:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2624:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2625:         }
 2626:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2627:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2628:         } 
 2629:     }
 2630:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2631:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2632:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2633:         }
 2634:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2635:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2636:         }
 2637:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2638:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2639:         }
 2640:     }
 2641:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2642:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2643:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2644:                             'approval','limit');
 2645:             foreach my $type (@coursetypes) {
 2646:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2647:                     my @mgrdc = ();
 2648:                     foreach my $item (@settings) {
 2649:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2650:                             push(@mgrdc,$item);
 2651:                         }
 2652:                     }
 2653:                     if (@mgrdc) {
 2654:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2655:                     }
 2656:                 }
 2657:             }
 2658:         }
 2659:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2660:             foreach my $type (@coursetypes) {
 2661:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2662:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2663:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2664:                     }
 2665:                 }
 2666:             }
 2667:         }
 2668:     }
 2669:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2670:         $domdefaults{'catauth'} = 'std';
 2671:         $domdefaults{'catunauth'} = 'std';
 2672:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2673:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2674:         }
 2675:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2676:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2677:         }
 2678:     }
 2679:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2680:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2681:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2682:         }
 2683:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2684:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2685:         }
 2686:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2687:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2688:         }
 2689:     }
 2690:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2691:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2692:         foreach my $prefix (@prefixes) {
 2693:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2694:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2695:             }
 2696:         }
 2697:     }
 2698:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2699:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2700:     }
 2701:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2702:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2703:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2704:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2705:         }
 2706:     }
 2707:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2708:     return %domdefaults;
 2709: }
 2710: 
 2711: sub course_portal_url {
 2712:     my ($cnum,$cdom) = @_;
 2713:     my $chome = &homeserver($cnum,$cdom);
 2714:     my $hostname = &hostname($chome);
 2715:     my $protocol = $protocol{$chome};
 2716:     $protocol = 'http' if ($protocol ne 'https');
 2717:     my %domdefaults = &get_domain_defaults($cdom);
 2718:     my $firsturl;
 2719:     if ($domdefaults{'portal_def'}) {
 2720:         $firsturl = $domdefaults{'portal_def'};
 2721:     } else {
 2722:         $firsturl = $protocol.'://'.$hostname;
 2723:     }
 2724:     return $firsturl;
 2725: }
 2726: 
 2727: # --------------------------------------------- Get domain config for passwords
 2728: 
 2729: sub get_passwdconf {
 2730:     my ($dom) = @_;
 2731:     my (%passwdconf,$gotconf,$lookup);
 2732:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2733:     if (defined($cached)) {
 2734:         if (ref($result) eq 'HASH') {
 2735:             %passwdconf = %{$result};
 2736:             $gotconf = 1;
 2737:         }
 2738:     }
 2739:     unless ($gotconf) {
 2740:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2741:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2742:             %passwdconf = %{$domconfig{'passwords'}};
 2743:         }
 2744:         my $cachetime = 24*60*60;
 2745:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2746:     }
 2747:     return %passwdconf;
 2748: }
 2749: 
 2750: # --------------------------------------------------- Assign a key to a student
 2751: 
 2752: sub assign_access_key {
 2753: #
 2754: # a valid key looks like uname:udom#comments
 2755: # comments are being appended
 2756: #
 2757:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2758:     $kdom=
 2759:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2760:     $knum=
 2761:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2762:     $cdom=
 2763:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2764:     $cnum=
 2765:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2766:     $udom=$env{'user.name'} unless (defined($udom));
 2767:     $uname=$env{'user.domain'} unless (defined($uname));
 2768:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2769:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2770:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2771:                                                   # assigned to this person
 2772:                                                   # - this should not happen,
 2773:                                                   # unless something went wrong
 2774:                                                   # the first time around
 2775: # ready to assign
 2776:         $logentry=$1.'; '.$logentry;
 2777:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2778:                                                  $kdom,$knum) eq 'ok') {
 2779: # key now belongs to user
 2780: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2781:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2782:                 &appenv({'environment.'.$envkey => $ckey});
 2783:                 return 'ok';
 2784:             } else {
 2785:                 return 
 2786:   'error: Count not permanently assign key, will need to be re-entered later.';
 2787: 	    }
 2788:         } else {
 2789:             return 'error: Could not assign key, try again later.';
 2790:         }
 2791:     } elsif (!$existing{$ckey}) {
 2792: # the key does not exist
 2793: 	return 'error: The key does not exist';
 2794:     } else {
 2795: # the key is somebody else's
 2796: 	return 'error: The key is already in use';
 2797:     }
 2798: }
 2799: 
 2800: # ------------------------------------------ put an additional comment on a key
 2801: 
 2802: sub comment_access_key {
 2803: #
 2804: # a valid key looks like uname:udom#comments
 2805: # comments are being appended
 2806: #
 2807:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2808:     $cdom=
 2809:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2810:     $cnum=
 2811:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2812:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2813:     if ($existing{$ckey}) {
 2814:         $existing{$ckey}.='; '.$logentry;
 2815: # ready to assign
 2816:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2817:                                                  $cdom,$cnum) eq 'ok') {
 2818: 	    return 'ok';
 2819:         } else {
 2820: 	    return 'error: Count not store comment.';
 2821:         }
 2822:     } else {
 2823: # the key does not exist
 2824: 	return 'error: The key does not exist';
 2825:     }
 2826: }
 2827: 
 2828: # ------------------------------------------------------ Generate a set of keys
 2829: 
 2830: sub generate_access_keys {
 2831:     my ($number,$cdom,$cnum,$logentry)=@_;
 2832:     $cdom=
 2833:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2834:     $cnum=
 2835:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2836:     unless (&allowed('mky',$cdom)) { return 0; }
 2837:     unless (($cdom) && ($cnum)) { return 0; }
 2838:     if ($number>10000) { return 0; }
 2839:     sleep(2); # make sure don't get same seed twice
 2840:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2841:     my $total=0;
 2842:     for (my $i=1;$i<=$number;$i++) {
 2843:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2844:                   sprintf("%lx",int(100000*rand)).'-'.
 2845:                   sprintf("%lx",int(100000*rand));
 2846:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2847:        $newkey=~s/0/h/g; # and also 0 and O
 2848:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2849:        if ($existing{$newkey}) {
 2850:            $i--;
 2851:        } else {
 2852: 	  if (&put('accesskeys',
 2853:               { $newkey => '# generated '.localtime().
 2854:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2855:                            '; '.$logentry },
 2856: 		   $cdom,$cnum) eq 'ok') {
 2857:               $total++;
 2858: 	  }
 2859:        }
 2860:     }
 2861:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2862:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2863:     return $total;
 2864: }
 2865: 
 2866: # ------------------------------------------------------- Validate an accesskey
 2867: 
 2868: sub validate_access_key {
 2869:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2870:     $cdom=
 2871:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2872:     $cnum=
 2873:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2874:     $udom=$env{'user.domain'} unless (defined($udom));
 2875:     $uname=$env{'user.name'} unless (defined($uname));
 2876:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2877:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2878: }
 2879: 
 2880: # ------------------------------------- Find the section of student in a course
 2881: sub devalidate_getsection_cache {
 2882:     my ($udom,$unam,$courseid)=@_;
 2883:     my $hashid="$udom:$unam:$courseid";
 2884:     &devalidate_cache_new('getsection',$hashid);
 2885: }
 2886: 
 2887: sub courseid_to_courseurl {
 2888:     my ($courseid) = @_;
 2889:     #already url style courseid
 2890:     return $courseid if ($courseid =~ m{^/});
 2891: 
 2892:     if (exists($env{'course.'.$courseid.'.num'})) {
 2893: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2894: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2895: 	return "/$cdom/$cnum";
 2896:     }
 2897: 
 2898:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2899:     if (exists($courseinfo{'num'})) {
 2900: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2901:     }
 2902: 
 2903:     return undef;
 2904: }
 2905: 
 2906: sub getsection {
 2907:     my ($udom,$unam,$courseid)=@_;
 2908:     my $cachetime=1800;
 2909: 
 2910:     my $hashid="$udom:$unam:$courseid";
 2911:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2912:     if (defined($cached)) { return $result; }
 2913: 
 2914:     my %Pending; 
 2915:     my %Expired;
 2916:     #
 2917:     # Each role can either have not started yet (pending), be active, 
 2918:     #    or have expired.
 2919:     #
 2920:     # If there is an active role, we are done.
 2921:     #
 2922:     # If there is more than one role which has not started yet, 
 2923:     #     choose the one which will start sooner
 2924:     # If there is one role which has not started yet, return it.
 2925:     #
 2926:     # If there is more than one expired role, choose the one which ended last.
 2927:     # If there is a role which has expired, return it.
 2928:     #
 2929:     $courseid = &courseid_to_courseurl($courseid);
 2930:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2931:     foreach my $key (keys(%roleshash)) {
 2932:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2933:         my $section=$1;
 2934:         if ($key eq $courseid.'_st') { $section=''; }
 2935:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2936:         my $now=time;
 2937:         if (defined($end) && $end && ($now > $end)) {
 2938:             $Expired{$end}=$section;
 2939:             next;
 2940:         }
 2941:         if (defined($start) && $start && ($now < $start)) {
 2942:             $Pending{$start}=$section;
 2943:             next;
 2944:         }
 2945:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2946:     }
 2947:     #
 2948:     # Presumedly there will be few matching roles from the above
 2949:     # loop and the sorting time will be negligible.
 2950:     if (scalar(keys(%Pending))) {
 2951:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2952:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2953:     } 
 2954:     if (scalar(keys(%Expired))) {
 2955:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2956:         my $time = pop(@sorted);
 2957:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2958:     }
 2959:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2960: }
 2961: 
 2962: sub save_cache {
 2963:     &purge_remembered();
 2964:     #&Apache::loncommon::validate_page();
 2965:     undef(%env);
 2966:     undef($env_loaded);
 2967: }
 2968: 
 2969: my $to_remember=-1;
 2970: my %remembered;
 2971: my %accessed;
 2972: my $kicks=0;
 2973: my $hits=0;
 2974: sub make_key {
 2975:     my ($name,$id) = @_;
 2976:     if (length($id) > 65 
 2977: 	&& length(&escape($id)) > 200) {
 2978: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2979:     }
 2980:     return &escape($name.':'.$id);
 2981: }
 2982: 
 2983: sub devalidate_cache_new {
 2984:     my ($name,$id,$debug) = @_;
 2985:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2986:     my $remembered_id=$name.':'.$id;
 2987:     $id=&make_key($name,$id);
 2988:     $memcache->delete($id);
 2989:     delete($remembered{$remembered_id});
 2990:     delete($accessed{$remembered_id});
 2991: }
 2992: 
 2993: sub is_cached_new {
 2994:     my ($name,$id,$debug) = @_;
 2995:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2996:     if (exists($remembered{$remembered_id})) {
 2997: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2998: 	$accessed{$remembered_id}=[&gettimeofday()];
 2999: 	$hits++;
 3000: 	return ($remembered{$remembered_id},1);
 3001:     }
 3002:     $id=&make_key($name,$id);
 3003:     my $value = $memcache->get($id);
 3004:     if (!(defined($value))) {
 3005: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3006: 	return (undef,undef);
 3007:     }
 3008:     if ($value eq '__undef__') {
 3009: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3010: 	$value=undef;
 3011:     }
 3012:     &make_room($remembered_id,$value,$debug);
 3013:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3014:     return ($value,1);
 3015: }
 3016: 
 3017: sub do_cache_new {
 3018:     my ($name,$id,$value,$time,$debug) = @_;
 3019:     my $remembered_id=$name.':'.$id;
 3020:     $id=&make_key($name,$id);
 3021:     my $setvalue=$value;
 3022:     if (!defined($setvalue)) {
 3023: 	$setvalue='__undef__';
 3024:     }
 3025:     if (!defined($time) ) {
 3026: 	$time=600;
 3027:     }
 3028:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3029:     my $result = $memcache->set($id,$setvalue,$time);
 3030:     if (! $result) {
 3031: 	&logthis("caching of id -> $id  failed");
 3032: 	$memcache->disconnect_all();
 3033:     }
 3034:     # need to make a copy of $value
 3035:     &make_room($remembered_id,$value,$debug);
 3036:     return $value;
 3037: }
 3038: 
 3039: sub make_room {
 3040:     my ($remembered_id,$value,$debug)=@_;
 3041: 
 3042:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3043:                                     : $value;
 3044:     if ($to_remember<0) { return; }
 3045:     $accessed{$remembered_id}=[&gettimeofday()];
 3046:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3047:     my $to_kick;
 3048:     my $max_time=0;
 3049:     foreach my $other (keys(%accessed)) {
 3050: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3051: 	    $to_kick=$other;
 3052: 	    $max_time=&tv_interval($accessed{$other});
 3053: 	}
 3054:     }
 3055:     delete($remembered{$to_kick});
 3056:     delete($accessed{$to_kick});
 3057:     $kicks++;
 3058:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3059:     return;
 3060: }
 3061: 
 3062: sub purge_remembered {
 3063:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3064:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3065:     undef(%remembered);
 3066:     undef(%accessed);
 3067: }
 3068: # ------------------------------------- Read an entry from a user's environment
 3069: 
 3070: sub userenvironment {
 3071:     my ($udom,$unam,@what)=@_;
 3072:     my $items;
 3073:     foreach my $item (@what) {
 3074:         $items.=&escape($item).'&';
 3075:     }
 3076:     $items=~s/\&$//;
 3077:     my %returnhash=();
 3078:     my $uhome = &homeserver($unam,$udom);
 3079:     unless ($uhome eq 'no_host') {
 3080:         my @answer=split(/\&/, 
 3081:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3082:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3083:             return %returnhash;
 3084:         }
 3085:         my $i;
 3086:         for ($i=0;$i<=$#what;$i++) {
 3087: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3088:         }
 3089:     }
 3090:     return %returnhash;
 3091: }
 3092: 
 3093: # ---------------------------------------------------------- Get a studentphoto
 3094: sub studentphoto {
 3095:     my ($udom,$unam,$ext) = @_;
 3096:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3097:     if (defined($env{'request.course.id'})) {
 3098:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3099:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3100:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3101:             } else {
 3102:                 my ($result,$perm_reqd)=
 3103: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3104:                 if ($result eq 'ok') {
 3105:                     if (!($perm_reqd eq 'yes')) {
 3106:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3107:                     }
 3108:                 }
 3109:             }
 3110:         }
 3111:     } else {
 3112:         my ($result,$perm_reqd) = 
 3113: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3114:         if ($result eq 'ok') {
 3115:             if (!($perm_reqd eq 'yes')) {
 3116:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3117:             }
 3118:         }
 3119:     }
 3120:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3121: }
 3122: 
 3123: sub retrievestudentphoto {
 3124:     my ($udom,$unam,$ext,$type) = @_;
 3125:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3126:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3127:     if ($ret eq 'ok') {
 3128:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3129:         if ($type eq 'thumbnail') {
 3130:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3131:         }
 3132:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3133:         return $tokenurl;
 3134:     } else {
 3135:         if ($type eq 'thumbnail') {
 3136:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3137:         } else { 
 3138:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3139:         }
 3140:     }
 3141: }
 3142: 
 3143: # -------------------------------------------------------------------- New chat
 3144: 
 3145: sub chatsend {
 3146:     my ($newentry,$anon,$group)=@_;
 3147:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3148:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3149:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3150:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3151: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3152: 		   &escape($newentry)).':'.$group,$chome);
 3153: }
 3154: 
 3155: # ------------------------------------------ Find current version of a resource
 3156: 
 3157: sub getversion {
 3158:     my $fname=&clutter(shift);
 3159:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3160:     return &currentversion(&filelocation('',$fname));
 3161: }
 3162: 
 3163: sub currentversion {
 3164:     my $fname=shift;
 3165:     my $author=$fname;
 3166:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3167:     my ($udom,$uname)=split(/\//,$author);
 3168:     my $home=&homeserver($uname,$udom);
 3169:     if ($home eq 'no_host') { 
 3170:         return -1; 
 3171:     }
 3172:     my $answer=&reply("currentversion:$fname",$home);
 3173:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3174: 	return -1;
 3175:     }
 3176:     return $answer;
 3177: }
 3178: 
 3179: #
 3180: # Return special version number of resource if set by override, empty otherwise
 3181: #
 3182: sub usedversion {
 3183:     my $fname=shift;
 3184:     unless ($fname) { $fname=$env{'request.uri'}; }
 3185:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3186:     if ($urlversion) { return $urlversion; }
 3187:     return '';
 3188: }
 3189: 
 3190: # ----------------------------- Subscribe to a resource, return URL if possible
 3191: 
 3192: sub subscribe {
 3193:     my $fname=shift;
 3194:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3195:     $fname=~s/[\n\r]//g;
 3196:     my $author=$fname;
 3197:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3198:     my ($udom,$uname)=split(/\//,$author);
 3199:     my $home=homeserver($uname,$udom);
 3200:     if ($home eq 'no_host') {
 3201:         return 'not_found';
 3202:     }
 3203:     my $answer=reply("sub:$fname",$home);
 3204:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3205: 	$answer.=' by '.$home;
 3206:     }
 3207:     return $answer;
 3208: }
 3209:     
 3210: # -------------------------------------------------------------- Replicate file
 3211: 
 3212: sub repcopy {
 3213:     my $filename=shift;
 3214:     $filename=~s/\/+/\//g;
 3215:     my $londocroot = $perlvar{'lonDocRoot'};
 3216:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3217:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3218:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3219: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3220: 	return &repcopy_userfile($filename);
 3221:     }
 3222:     $filename=~s/[\n\r]//g;
 3223:     my $transname="$filename.in.transfer";
 3224: # FIXME: this should flock
 3225:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3226:     my $remoteurl=subscribe($filename);
 3227:     if ($remoteurl =~ /^con_lost by/) {
 3228: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3229:            return 'unavailable';
 3230:     } elsif ($remoteurl eq 'not_found') {
 3231: 	   #&logthis("Subscribe returned not_found: $filename");
 3232: 	   return 'not_found';
 3233:     } elsif ($remoteurl =~ /^rejected by/) {
 3234: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3235:            return 'forbidden';
 3236:     } elsif ($remoteurl eq 'directory') {
 3237:            return 'ok';
 3238:     } else {
 3239:         my $author=$filename;
 3240:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3241:         my ($udom,$uname)=split(/\//,$author);
 3242:         my $home=homeserver($uname,$udom);
 3243:         unless ($home eq $perlvar{'lonHostID'}) {
 3244:            my @parts=split(/\//,$filename);
 3245:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3246:            if ($path ne "$londocroot/res") {
 3247:                &logthis("Malconfiguration for replication: $filename");
 3248: 	       return 'bad_request';
 3249:            }
 3250:            my $count;
 3251:            for ($count=5;$count<$#parts;$count++) {
 3252:                $path.="/$parts[$count]";
 3253:                if ((-e $path)!=1) {
 3254: 		   mkdir($path,0777);
 3255:                }
 3256:            }
 3257:            my $request=new HTTP::Request('GET',"$remoteurl");
 3258:            my $response;
 3259:            if ($remoteurl =~ m{/raw/}) {
 3260:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3261:            } else {
 3262:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3263:            }
 3264:            if ($response->is_error()) {
 3265: 	       unlink($transname);
 3266:                my $message=$response->status_line;
 3267:                &logthis("<font color=\"blue\">WARNING:"
 3268:                        ." LWP get: $message: $filename</font>");
 3269:                return 'unavailable';
 3270:            } else {
 3271: 	       if ($remoteurl!~/\.meta$/) {
 3272:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3273:                   my $mresponse;
 3274:                   if ($remoteurl =~ m{/raw/}) {
 3275:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3276:                   } else {
 3277:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3278:                   }
 3279:                   if ($mresponse->is_error()) {
 3280: 		      unlink($filename.'.meta');
 3281:                       &logthis(
 3282:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3283:                   }
 3284: 	       }
 3285:                rename($transname,$filename);
 3286:                return 'ok';
 3287:            }
 3288:        }
 3289:     }
 3290: }
 3291: 
 3292: # ------------------------------------------------ Get server side include body
 3293: sub ssi_body {
 3294:     my ($filelink,%form)=@_;
 3295:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3296:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3297:     }
 3298:     my $output='';
 3299:     my $response;
 3300:     if ($filelink=~/^https?\:/) {
 3301:        ($output,$response)=&externalssi($filelink);
 3302:     } else {
 3303:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3304:        $filelink .= 'inhibitmenu=yes';
 3305:        ($output,$response)=&ssi($filelink,%form);
 3306:     }
 3307:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3308:     $output=~s/^.*?\<body[^\>]*\>//si;
 3309:     $output=~s/\<\/body\s*\>.*?$//si;
 3310:     if (wantarray) {
 3311:         return ($output, $response);
 3312:     } else {
 3313:         return $output;
 3314:     }
 3315: }
 3316: 
 3317: # --------------------------------------------------------- Server Side Include
 3318: 
 3319: sub absolute_url {
 3320:     my ($host_name) = @_;
 3321:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3322:     if ($host_name eq '') {
 3323: 	$host_name = $ENV{'SERVER_NAME'};
 3324:     }
 3325:     return $protocol.$host_name;
 3326: }
 3327: 
 3328: #
 3329: #   Server side include.
 3330: # Parameters:
 3331: #  fn     Possibly encrypted resource name/id.
 3332: #  form   Hash that describes how the rendering should be done
 3333: #         and other things.
 3334: # Returns:
 3335: #   Scalar context: The content of the response.
 3336: #   Array context:  2 element list of the content and the full response object.
 3337: #     
 3338: sub ssi {
 3339: 
 3340:     my ($fn,%form)=@_;
 3341:     my $request;
 3342: 
 3343:     $form{'no_update_last_known'}=1;
 3344:     &Apache::lonenc::check_encrypt(\$fn);
 3345:     if (%form) {
 3346:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3347:       $request->content(join('&',map { 
 3348:             my $name = escape($_);
 3349:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3350:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3351:             : &escape($form{$_}) );    
 3352:         } keys(%form)));
 3353:     } else {
 3354:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3355:     }
 3356: 
 3357:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3358:     my $lonhost = $perlvar{'lonHostID'};
 3359:     my $islocal;
 3360:     if (($env{'request.course.id'}) &&
 3361:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3362:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3363:         ($form{'grade_symb'} ne '') &&
 3364:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3365:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3366:         $islocal = 1;
 3367:     }
 3368:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3369:                                                 '','','',$islocal);
 3370: 
 3371:     if (wantarray) {
 3372: 	return ($response->content, $response);
 3373:     } else {
 3374: 	return $response->content;
 3375:     }
 3376: }
 3377: 
 3378: sub externalssi {
 3379:     my ($url)=@_;
 3380:     my $request=new HTTP::Request('GET',$url);
 3381:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3382:     if (wantarray) {
 3383:         return ($response->content, $response);
 3384:     } else {
 3385:         return $response->content;
 3386:     }
 3387: }
 3388: 
 3389: 
 3390: # If the local copy of a replicated resource is outdated, trigger a  
 3391: # connection from the homeserver to flush the delayed queue. If no update 
 3392: # happens, remove local copies of outdated resource (and corresponding
 3393: # metadata file).
 3394: 
 3395: sub remove_stale_resfile {
 3396:     my ($url) = @_;
 3397:     my $removed;
 3398:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3399:         my $audom = $1;
 3400:         my $auname = $2;
 3401:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3402:             my $homeserver = &homeserver($auname,$audom);
 3403:             unless (($homeserver eq 'no_host') ||
 3404:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3405:                 my $fname = &filelocation('',$url);
 3406:                 if (-e $fname) {
 3407:                     my $hostname = &hostname($homeserver);
 3408:                     if ($hostname) {
 3409:                         my $protocol = $protocol{$homeserver};
 3410:                         $protocol = 'http' if ($protocol ne 'https');
 3411:                         my $uri = &declutter($url);
 3412:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3413:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3414:                         if ($response->is_success()) {
 3415:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3416:                             my $locmodtime = (stat($fname))[9];
 3417:                             if ($locmodtime < $remmodtime) {
 3418:                                 my $stale;
 3419:                                 my $answer = &reply('pong',$homeserver);
 3420:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3421:                                     sleep(0.2);
 3422:                                     $locmodtime = (stat($fname))[9];
 3423:                                     if ($locmodtime < $remmodtime) {
 3424:                                         my $posstransfer = $fname.'.in.transfer';
 3425:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3426:                                             $removed = 1;
 3427:                                         } else {
 3428:                                             $stale = 1;
 3429:                                         }
 3430:                                     } else {
 3431:                                         $removed = 1;
 3432:                                     }
 3433:                                 } else {
 3434:                                     $stale = 1;
 3435:                                 }
 3436:                                 if ($stale) {
 3437:                                     unlink($fname);
 3438:                                     if ($uri!~/\.meta$/) {
 3439:                                         unlink($fname.'.meta');
 3440:                                     }
 3441:                                     &reply("unsub:$fname",$homeserver);
 3442:                                     $removed = 1;
 3443:                                 }
 3444:                             }
 3445:                         }
 3446:                     }
 3447:                 }
 3448:             }
 3449:         }
 3450:     }
 3451:     return $removed;
 3452: }
 3453: 
 3454: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3455: 
 3456: sub allowuploaded {
 3457:     my ($srcurl,$url)=@_;
 3458:     $url=&clutter(&declutter($url));
 3459:     my $dir=$url;
 3460:     $dir=~s/\/[^\/]+$//;
 3461:     my %httpref=();
 3462:     my $httpurl=&hreflocation('',$url);
 3463:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3464:     &Apache::lonnet::appenv(\%httpref);
 3465: }
 3466: 
 3467: #
 3468: # Determine if the current user should be able to edit a particular resource,
 3469: # when viewing in course context.
 3470: # (a) When viewing resource used to determine if "Edit" item is included in 
 3471: #     Functions.
 3472: # (b) When displaying folder contents in course editor, used to determine if
 3473: #     "Edit" link will be displayed alongside resource.
 3474: #
 3475: #  input: six args -- filename (decluttered), course number, course domain,
 3476: #                   url, symb (if registered) and group (if this is a group
 3477: #                   item -- e.g., bulletin board, group page etc.).
 3478: #  output: array of five scalars -- 
 3479: #          $cfile -- url for file editing if editable on current server
 3480: #          $home -- homeserver of resource (i.e., for author if published,
 3481: #                                           or course if uploaded.).
 3482: #          $switchserver --  1 if server switch will be needed.
 3483: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3484: #          $forceview -- 1 if icon/link should be to go to view mode
 3485: #
 3486: 
 3487: sub can_edit_resource {
 3488:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3489:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3490: #
 3491: # For aboutme pages user can only edit his/her own.
 3492: #
 3493:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3494:         my ($sdom,$sname) = ($1,$2);
 3495:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3496:             $home = $env{'user.home'};
 3497:             $cfile = $resurl;
 3498:             if ($env{'form.forceedit'}) {
 3499:                 $forceview = 1;
 3500:             } else {
 3501:                 $forceedit = 1;
 3502:             }
 3503:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3504:         } else {
 3505:             return;
 3506:         }
 3507:     }
 3508: 
 3509:     if ($env{'request.course.id'}) {
 3510:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3511:         if ($group ne '') {
 3512: # if this is a group homepage or group bulletin board, check group privs
 3513:             my $allowed = 0;
 3514:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3515:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3516:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3517:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3518:                     $allowed = 1;
 3519:                 }
 3520:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3521:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3522:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3523:                     $allowed = 1;
 3524:                 }
 3525:             }
 3526:             if ($allowed) {
 3527:                 $home=&homeserver($cnum,$cdom);
 3528:                 if ($env{'form.forceedit'}) {
 3529:                     $forceview = 1;
 3530:                 } else {
 3531:                     $forceedit = 1;
 3532:                 }
 3533:                 $cfile = $resurl;
 3534:             } else {
 3535:                 return;
 3536:             }
 3537:         } else {
 3538:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3539:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3540:                     return;
 3541:                 }
 3542:             } elsif (!$crsedit) {
 3543: #
 3544: # No edit allowed where CC has switched to student role.
 3545: #
 3546:                 return;
 3547:             }
 3548:         }
 3549:     }
 3550: 
 3551:     if ($file ne '') {
 3552:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3553:             if (&is_course_upload($file,$cnum,$cdom)) {
 3554:                 $uploaded = 1;
 3555:                 $incourse = 1;
 3556:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3557:                     $cfile = &hreflocation('',$file);
 3558:                     if ($env{'form.forceedit'}) {
 3559:                         $forceview = 1;
 3560:                     } else {
 3561:                         $forceedit = 1;
 3562:                     }
 3563:                 }
 3564:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3565:                 $incourse = 1;
 3566:                 if ($env{'form.forceedit'}) {
 3567:                     $forceview = 1;
 3568:                 } else {
 3569:                     $forceedit = 1;
 3570:                 }
 3571:                 $cfile = $resurl;
 3572:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3573:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3574:                     $incourse = 1;
 3575:                     if ($env{'form.forceedit'}) {
 3576:                         $forceview = 1;
 3577:                     } else {
 3578:                         $forceedit = 1;
 3579:                     }
 3580:                     $cfile = $resurl;
 3581:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3582:                     $incourse = 1;
 3583:                     $cfile = $resurl.'/smpedit';
 3584:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3585:                     $incourse = 1;
 3586:                     if ($env{'form.forceedit'}) {
 3587:                         $forceview = 1;
 3588:                     } else {
 3589:                         $forceedit = 1;
 3590:                     }
 3591:                     $cfile = $resurl;
 3592:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3593:                     $incourse = 1;
 3594:                     if ($env{'form.forceedit'}) {
 3595:                         $forceview = 1;
 3596:                     } else {
 3597:                         $forceedit = 1;
 3598:                     }
 3599:                     $cfile = $resurl;
 3600:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3601:                     $incourse = 1;
 3602:                     if ($env{'form.forceedit'}) {
 3603:                         $forceview = 1;
 3604:                     } else {
 3605:                         $forceedit = 1;
 3606:                     }
 3607:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3608:                 }
 3609:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3610:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3611:                 if (&is_on_map($template)) { 
 3612:                     $incourse = 1;
 3613:                     $forceview = 1;
 3614:                     $cfile = $template;
 3615:                 }
 3616:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3617:                     $incourse = 1;
 3618:                     if ($env{'form.forceedit'}) {
 3619:                         $forceview = 1;
 3620:                     } else {
 3621:                         $forceedit = 1;
 3622:                     }
 3623:                     $cfile = $resurl;
 3624:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3625:                 $incourse = 1;
 3626:                 if ($env{'form.forceedit'}) {
 3627:                     $forceview = 1;
 3628:                 } else {
 3629:                     $forceedit = 1;
 3630:                 }
 3631:                 $cfile = $resurl;
 3632:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3633:                 $incourse = 1;
 3634:                 $forceview = 1;
 3635:                 if ($symb) {
 3636:                     my ($map,$id,$res)=&decode_symb($symb);
 3637:                     $env{'request.symb'} = $symb;
 3638:                     $cfile = &clutter($res);
 3639:                 } else {
 3640:                     $cfile = $env{'form.suppurl'};
 3641:                     my $escfile = &unescape($cfile);
 3642:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3643:                         $cfile = '/adm/wrapper'.$escfile;
 3644:                     } else {
 3645:                         $escfile =~ s{^http://}{};
 3646:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3647:                     }
 3648:                 }
 3649:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3650:                 if ($env{'form.forceedit'}) {
 3651:                     $forceview = 1;
 3652:                 } else {
 3653:                     $forceedit = 1;
 3654:                 }
 3655:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3656:             }
 3657:         }
 3658:         if ($uploaded || $incourse) {
 3659:             $home=&homeserver($cnum,$cdom);
 3660:         } elsif ($file !~ m{/$}) {
 3661:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3662:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3663:             # Check that the user has permission to edit this resource
 3664:             my $setpriv = 1;
 3665:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3666:             if (defined($cfudom)) {
 3667:                 $home=&homeserver($cfuname,$cfudom);
 3668:                 $cfile=$file;
 3669:             }
 3670:         }
 3671:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3672:             (($home ne '') && ($home ne 'no_host'))) {
 3673:             my @ids=&current_machine_ids();
 3674:             unless (grep(/^\Q$home\E$/,@ids)) {
 3675:                 $switchserver=1;
 3676:             }
 3677:         }
 3678:     }
 3679:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3680: }
 3681: 
 3682: sub is_course_upload {
 3683:     my ($file,$cnum,$cdom) = @_;
 3684:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3685:     $uploadpath =~ s{^\/}{};
 3686:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3687:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3688:         return 1;
 3689:     }
 3690:     return;
 3691: }
 3692: 
 3693: sub in_course {
 3694:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3695:     if ($hideprivileged) {
 3696:         my $skipuser;
 3697:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3698:         my @possdoms = ($cdom);  
 3699:         if ($coursehash{'checkforpriv'}) { 
 3700:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3701:         }
 3702:         if (&privileged($uname,$udom,\@possdoms)) {
 3703:             $skipuser = 1;
 3704:             if ($coursehash{'nothideprivileged'}) {
 3705:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3706:                     my $user;
 3707:                     if ($item =~ /:/) {
 3708:                         $user = $item;
 3709:                     } else {
 3710:                         $user = join(':',split(/[\@]/,$item));
 3711:                     }
 3712:                     if ($user eq $uname.':'.$udom) {
 3713:                         undef($skipuser);
 3714:                         last;
 3715:                     }
 3716:                 }
 3717:             }
 3718:             if ($skipuser) {
 3719:                 return 0;
 3720:             }
 3721:         }
 3722:     }
 3723:     $type ||= 'any';
 3724:     if (!defined($cdom) || !defined($cnum)) {
 3725:         my $cid  = $env{'request.course.id'};
 3726:         $cdom = $env{'course.'.$cid.'.domain'};
 3727:         $cnum = $env{'course.'.$cid.'.num'};
 3728:     }
 3729:     my $typesref;
 3730:     if (($type eq 'any') || ($type eq 'all')) {
 3731:         $typesref = ['active','previous','future'];
 3732:     } elsif ($type eq 'previous' || $type eq 'future') {
 3733:         $typesref = [$type];
 3734:     }
 3735:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3736:                               $typesref,undef,[$cdom]);
 3737:     my ($tmp) = keys(%roles);
 3738:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3739:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3740:     if (@course_roles > 0) {
 3741:         return 1;
 3742:     }
 3743:     return 0;
 3744: }
 3745: 
 3746: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3747: # input: action, courseID, current domain, intended
 3748: #        path to file, source of file, instruction to parse file for objects,
 3749: #        ref to hash for embedded objects,
 3750: #        ref to hash for codebase of java objects.
 3751: #        reference to scalar to accommodate mime type determined
 3752: #          from File::MMagic if $parser = parse.
 3753: #
 3754: # output: url to file (if action was uploaddoc), 
 3755: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3756: #
 3757: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3758: # course.
 3759: #
 3760: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3761: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3762: #          course's home server.
 3763: #
 3764: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3765: #          be copied from $source (current location) to 
 3766: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3767: #         and will then be copied to
 3768: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3769: #         course's home server.
 3770: #
 3771: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3772: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3773: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3774: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3775: #         in course's home server.
 3776: #
 3777: 
 3778: sub process_coursefile {
 3779:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3780:         $mimetype)=@_;
 3781:     my $fetchresult;
 3782:     my $home=&homeserver($docuname,$docudom);
 3783:     if ($action eq 'propagate') {
 3784:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3785: 			     $home);
 3786:     } else {
 3787:         my $fpath = '';
 3788:         my $fname = $file;
 3789:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3790:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3791:         my $filepath = &build_filepath($fpath);
 3792:         if ($action eq 'copy') {
 3793:             if ($source eq '') {
 3794:                 $fetchresult = 'no source file';
 3795:                 return $fetchresult;
 3796:             } else {
 3797:                 my $destination = $filepath.'/'.$fname;
 3798:                 rename($source,$destination);
 3799:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3800:                                  $home);
 3801:             }
 3802:         } elsif ($action eq 'uploaddoc') {
 3803:             open(my $fh,'>',$filepath.'/'.$fname);
 3804:             print $fh $env{'form.'.$source};
 3805:             close($fh);
 3806:             if ($parser eq 'parse') {
 3807:                 my $mm = new File::MMagic;
 3808:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3809:                 if ($type eq 'text/html') {
 3810:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3811:                     unless ($parse_result eq 'ok') {
 3812:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3813:                     }
 3814:                 }
 3815:                 if (ref($mimetype)) {
 3816:                     $$mimetype = $type;
 3817:                 } 
 3818:             }
 3819:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3820:                                  $home);
 3821:             if ($fetchresult eq 'ok') {
 3822:                 return '/uploaded/'.$fpath.'/'.$fname;
 3823:             } else {
 3824:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3825:                         ' to host '.$home.': '.$fetchresult);
 3826:                 return '/adm/notfound.html';
 3827:             }
 3828:         }
 3829:     }
 3830:     unless ( $fetchresult eq 'ok') {
 3831:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3832:              ' to host '.$home.': '.$fetchresult);
 3833:     }
 3834:     return $fetchresult;
 3835: }
 3836: 
 3837: sub build_filepath {
 3838:     my ($fpath) = @_;
 3839:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3840:     unless ($fpath eq '') {
 3841:         my @parts=split('/',$fpath);
 3842:         foreach my $part (@parts) {
 3843:             $filepath.= '/'.$part;
 3844:             if ((-e $filepath)!=1) {
 3845:                 mkdir($filepath,0777);
 3846:             }
 3847:         }
 3848:     }
 3849:     return $filepath;
 3850: }
 3851: 
 3852: sub store_edited_file {
 3853:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3854:     my $file = $primary_url;
 3855:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3856:     my $fpath = '';
 3857:     my $fname = $file;
 3858:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3859:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3860:     my $filepath = &build_filepath($fpath);
 3861:     open(my $fh,'>',$filepath.'/'.$fname);
 3862:     print $fh $content;
 3863:     close($fh);
 3864:     my $home=&homeserver($docuname,$docudom);
 3865:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3866: 			  $home);
 3867:     if ($$fetchresult eq 'ok') {
 3868:         return '/uploaded/'.$fpath.'/'.$fname;
 3869:     } else {
 3870:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3871: 		 ' to host '.$home.': '.$$fetchresult);
 3872:         return '/adm/notfound.html';
 3873:     }
 3874: }
 3875: 
 3876: sub clean_filename {
 3877:     my ($fname,$args)=@_;
 3878: # Replace Windows backslashes by forward slashes
 3879:     $fname=~s/\\/\//g;
 3880:     if (!$args->{'keep_path'}) {
 3881:         # Get rid of everything but the actual filename
 3882: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3883:     }
 3884: # Replace spaces by underscores
 3885:     $fname=~s/\s+/\_/g;
 3886: # Transliterate non-ascii text to ascii
 3887:     my $lang = &Apache::lonlocal::current_language();
 3888:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3889: # Replace all other weird characters by nothing
 3890:     $fname=~s{[^/\w\.\-]}{}g;
 3891: # Replace all .\d. sequences with _\d. so they no longer look like version
 3892: # numbers
 3893:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3894:     return $fname;
 3895: }
 3896: 
 3897: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3898: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3899: # image with the same aspect ratio as the original, but with dimensions which do 
 3900: # not exceed $resizewidth and $resizeheight.
 3901:  
 3902: sub resizeImage {
 3903:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3904:     my $ima = Image::Magick->new;
 3905:     my $resized;
 3906:     if (-e $img_path) {
 3907:         $ima->Read($img_path);
 3908:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3909:             my $width = $ima->Get('width');
 3910:             my $height = $ima->Get('height');
 3911:             if ($width > $resizewidth) {
 3912: 	        my $factor = $width/$resizewidth;
 3913:                 my $newheight = $height/$factor;
 3914:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3915:                 $resized = 1;
 3916:             }
 3917:         }
 3918:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3919:             my $width = $ima->Get('width');
 3920:             my $height = $ima->Get('height');
 3921:             if ($height > $resizeheight) {
 3922:                 my $factor = $height/$resizeheight;
 3923:                 my $newwidth = $width/$factor;
 3924:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3925:                 $resized = 1;
 3926:             }
 3927:         }
 3928:         if ($resized) {
 3929:             $ima->Write($img_path);
 3930:         }
 3931:     }
 3932:     return;
 3933: }
 3934: 
 3935: # --------------- Take an uploaded file and put it into the userfiles directory
 3936: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3937: #                    the desired filename is in $env{"form.$formname.filename"}
 3938: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3939: #                                    canceloverwrite, scantron or ''.
 3940: #                   if 'coursedoc': upload to the current course
 3941: #                   if 'existingfile': write file to tmp/overwrites directory 
 3942: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3943: #                   $context is passed as argument to &finishuserfileupload
 3944: #        $subdir - directory in userfile to store the file into
 3945: #        $parser - instruction to parse file for objects ($parser = parse) or
 3946: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3947: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 3948: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3949: #        $allfiles - reference to hash for embedded objects
 3950: #        $codebase - reference to hash for codebase of java objects
 3951: #        $desuname - username for permanent storage of uploaded file
 3952: #        $dsetudom - domain for permanaent storage of uploaded file
 3953: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3954: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3955: #        $resizewidth - width (pixels) to which to resize uploaded image
 3956: #        $resizeheight - height (pixels) to which to resize uploaded image
 3957: #        $mimetype - reference to scalar to accommodate mime type determined
 3958: #                    from File::MMagic.
 3959: # 
 3960: # output: url of file in userspace, or error: <message> 
 3961: #             or /adm/notfound.html if failure to upload occurse
 3962: 
 3963: sub userfileupload {
 3964:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3965:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3966:     if (!defined($subdir)) { $subdir='unknown'; }
 3967:     my $fname=$env{'form.'.$formname.'.filename'};
 3968:     $fname=&clean_filename($fname);
 3969:     # See if there is anything left
 3970:     unless ($fname) { return 'error: no uploaded file'; }
 3971:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3972:     if ($fname =~ /^\./) {
 3973:         my ($s,$usec) = &gettimeofday();
 3974:         while (length($usec) < 6) {
 3975:             $usec = '0'.$usec;
 3976:         }
 3977:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3978:     }
 3979:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3980:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3981:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3982:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3983:         my $now = time;
 3984:         my $filepath;
 3985:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3986:              $filepath = 'tmp/helprequests/'.$now;
 3987:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3988:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3989:                          '_'.$env{'user.domain'}.'/pending';
 3990:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3991:             my ($docuname,$docudom);
 3992:             if ($destudom =~ /^$match_domain$/) {
 3993:                 $docudom = $destudom;
 3994:             } else {
 3995:                 $docudom = $env{'user.domain'};
 3996:             }
 3997:             if ($destuname =~ /^$match_username$/) {
 3998:                 $docuname = $destuname;
 3999:             } else {
 4000:                 $docuname = $env{'user.name'};
 4001:             }
 4002:             if (exists($env{'form.group'})) {
 4003:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4004:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4005:             }
 4006:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4007:             if ($context eq 'canceloverwrite') {
 4008:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4009:                 if (-e  $tempfile) {
 4010:                     my @info = stat($tempfile);
 4011:                     if ($info[9] eq $env{'form.timestamp'}) {
 4012:                         unlink($tempfile);
 4013:                     }
 4014:                 }
 4015:                 return;
 4016:             }
 4017:         }
 4018:         # Create the directory if not present
 4019:         my @parts=split(/\//,$filepath);
 4020:         my $fullpath = $perlvar{'lonDaemons'};
 4021:         for (my $i=0;$i<@parts;$i++) {
 4022:             $fullpath .= '/'.$parts[$i];
 4023:             if ((-e $fullpath)!=1) {
 4024:                 mkdir($fullpath,0777);
 4025:             }
 4026:         }
 4027:         open(my $fh,'>',$fullpath.'/'.$fname);
 4028:         print $fh $env{'form.'.$formname};
 4029:         close($fh);
 4030:         if ($context eq 'existingfile') {
 4031:             my @info = stat($fullpath.'/'.$fname);
 4032:             return ($fullpath.'/'.$fname,$info[9]);
 4033:         } else {
 4034:             return $fullpath.'/'.$fname;
 4035:         }
 4036:     }
 4037:     if ($subdir eq 'scantron') {
 4038:         $fname = 'scantron_orig_'.$fname;
 4039:     } else {
 4040:         $fname="$subdir/$fname";
 4041:     }
 4042:     if ($context eq 'coursedoc') {
 4043: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4044: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4045:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4046:             return &finishuserfileupload($docuname,$docudom,
 4047: 					 $formname,$fname,$parser,$allfiles,
 4048: 					 $codebase,$thumbwidth,$thumbheight,
 4049:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4050:         } else {
 4051:             if ($env{'form.folder'}) {
 4052:                 $fname=$env{'form.folder'}.'/'.$fname;
 4053:             }
 4054:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4055: 				       $fname,$formname,$parser,
 4056: 				       $allfiles,$codebase,$mimetype);
 4057:         }
 4058:     } elsif (defined($destuname)) {
 4059:         my $docuname=$destuname;
 4060:         my $docudom=$destudom;
 4061: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4062: 				     $parser,$allfiles,$codebase,
 4063:                                      $thumbwidth,$thumbheight,
 4064:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4065:     } else {
 4066:         my $docuname=$env{'user.name'};
 4067:         my $docudom=$env{'user.domain'};
 4068:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4069:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4070:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4071:         }
 4072: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4073: 				     $parser,$allfiles,$codebase,
 4074:                                      $thumbwidth,$thumbheight,
 4075:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4076:     }
 4077: }
 4078: 
 4079: sub finishuserfileupload {
 4080:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4081:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4082:     my $path=$docudom.'/'.$docuname.'/';
 4083:     my $filepath=$perlvar{'lonDocRoot'};
 4084:   
 4085:     my ($fnamepath,$file,$fetchthumb);
 4086:     $file=$fname;
 4087:     if ($fname=~m|/|) {
 4088:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4089: 	$path.=$fnamepath.'/';
 4090:     }
 4091:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4092:     my $count;
 4093:     for ($count=4;$count<=$#parts;$count++) {
 4094:         $filepath.="/$parts[$count]";
 4095:         if ((-e $filepath)!=1) {
 4096: 	    mkdir($filepath,0777);
 4097:         }
 4098:     }
 4099: 
 4100: # Save the file
 4101:     {
 4102: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4103: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4104: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4105: 	    return '/adm/notfound.html';
 4106: 	}
 4107:         if ($context eq 'overwrite') {
 4108:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4109:             my $target = $filepath.'/'.$file;
 4110:             if (-e $source) {
 4111:                 my @info = stat($source);
 4112:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4113:                     unless (&File::Copy::move($source,$target)) {
 4114:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4115:                         return "Moving from $source failed";
 4116:                     }
 4117:                 } else {
 4118:                     return "Temporary file: $source had unexpected date/time for last modification";
 4119:                 }
 4120:             } else {
 4121:                 return "Temporary file: $source missing";
 4122:             }
 4123:         } elsif (!print FH ($env{'form.'.$formname})) {
 4124: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4125: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4126: 	    return '/adm/notfound.html';
 4127: 	}
 4128: 	close(FH);
 4129:         if ($resizewidth && $resizeheight) {
 4130:             my $mm = new File::MMagic;
 4131:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4132:             if ($mime_type =~ m{^image/}) {
 4133: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4134:             }  
 4135: 	}
 4136:     }
 4137:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4138:         if (ref($mimetype)) {
 4139:             if ($$mimetype eq '') {
 4140:                 my $mm = new File::MMagic;
 4141:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4142:                 $$mimetype = $type;
 4143:             }
 4144:         }
 4145:     }
 4146:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4147:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4148:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4149:                                                        $allfiles,$codebase);
 4150:             unless ($parse_result eq 'ok') {
 4151:                 &logthis('Failed to parse '.$filepath.$file.
 4152: 	   	         ' for embedded media: '.$parse_result); 
 4153:             }
 4154:         }
 4155:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4156:         my $format = $env{'form.scantron_format'};
 4157:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4158:     }
 4159:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4160:         my $input = $filepath.'/'.$file;
 4161:         my $output = $filepath.'/'.'tn-'.$file;
 4162:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4163:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4164:         system({$args[0]} @args);
 4165:         if (-e $filepath.'/'.'tn-'.$file) {
 4166:             $fetchthumb  = 1; 
 4167:         }
 4168:     }
 4169:  
 4170: # Notify homeserver to grep it
 4171: #
 4172:     my $docuhome=&homeserver($docuname,$docudom);	
 4173:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4174:     if ($fetchresult eq 'ok') {
 4175:         if ($fetchthumb) {
 4176:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4177:             if ($thumbresult ne 'ok') {
 4178:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4179:                          $docuhome.': '.$thumbresult);
 4180:             }
 4181:         }
 4182: #
 4183: # Return the URL to it
 4184:         return '/uploaded/'.$path.$file;
 4185:     } else {
 4186:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4187: 		 ': '.$fetchresult);
 4188:         return '/adm/notfound.html';
 4189:     }
 4190: }
 4191: 
 4192: sub extract_embedded_items {
 4193:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4194:     my @state = ();
 4195:     my (%lastids,%related,%shockwave,%flashvars);
 4196:     my %javafiles = (
 4197:                       codebase => '',
 4198:                       code => '',
 4199:                       archive => ''
 4200:                     );
 4201:     my %mediafiles = (
 4202:                       src => '',
 4203:                       movie => '',
 4204:                      );
 4205:     my $p;
 4206:     if ($content) {
 4207:         $p = HTML::LCParser->new($content);
 4208:     } else {
 4209:         $p = HTML::LCParser->new($fullpath);
 4210:     }
 4211:     while (my $t=$p->get_token()) {
 4212: 	if ($t->[0] eq 'S') {
 4213: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4214: 	    push(@state, $tagname);
 4215:             if (lc($tagname) eq 'allow') {
 4216:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4217:             }
 4218: 	    if (lc($tagname) eq 'img') {
 4219: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4220: 	    }
 4221: 	    if (lc($tagname) eq 'a') {
 4222:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4223:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4224:                 }
 4225: 	    }
 4226:             if (lc($tagname) eq 'script') {
 4227:                 my $src;
 4228:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4229:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4230:                 } else {
 4231:                     if ($attr->{'src'} ne '') {
 4232:                         $src = $attr->{'src'};
 4233:                         &add_filetype($allfiles,$src,'src');
 4234:                     }
 4235:                 }
 4236:                 my $text = $p->get_trimmed_text();
 4237:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4238:                     my @swfargs = split(/,/,$1);
 4239:                     foreach my $item (@swfargs) {
 4240:                         $item =~ s/["']//g;
 4241:                         $item =~ s/^\s+//;
 4242:                         $item =~ s/\s+$//;
 4243:                     }
 4244:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4245:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4246:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4247:                         } else {
 4248:                             $related{$swfargs[0]} = [$swfargs[2]];
 4249:                         }
 4250:                     }
 4251:                 }
 4252:             }
 4253:             if (lc($tagname) eq 'link') {
 4254:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4255:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4256:                 }
 4257:             }
 4258: 	    if (lc($tagname) eq 'object' ||
 4259: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4260: 		foreach my $item (keys(%javafiles)) {
 4261: 		    $javafiles{$item} = '';
 4262: 		}
 4263:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4264:                     $lastids{lc($tagname)} = $attr->{'id'};
 4265:                 }
 4266: 	    }
 4267: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4268: 		my $name = lc($attr->{'name'});
 4269: 		foreach my $item (keys(%javafiles)) {
 4270: 		    if ($name eq $item) {
 4271: 			$javafiles{$item} = $attr->{'value'};
 4272: 			last;
 4273: 		    }
 4274: 		}
 4275:                 my $pathfrom;
 4276: 		foreach my $item (keys(%mediafiles)) {
 4277: 		    if ($name eq $item) {
 4278:                         $pathfrom = $attr->{'value'};
 4279:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4280: 			&add_filetype($allfiles,$pathfrom,$name);
 4281: 			last;
 4282: 		    }
 4283: 		}
 4284:                 if ($name eq 'flashvars') {
 4285:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4286:                 }
 4287:                 if ($pathfrom ne '') {
 4288:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4289:                                          $pathfrom);
 4290:                 }
 4291: 	    }
 4292: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4293: 		foreach my $item (keys(%javafiles)) {
 4294: 		    if ($attr->{$item}) {
 4295: 			$javafiles{$item} = $attr->{$item};
 4296: 			last;
 4297: 		    }
 4298: 		}
 4299: 		foreach my $item (keys(%mediafiles)) {
 4300: 		    if ($attr->{$item}) {
 4301: 			&add_filetype($allfiles,$attr->{$item},$item);
 4302: 			last;
 4303: 		    }
 4304: 		}
 4305:                 if (lc($tagname) eq 'embed') {
 4306:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4307:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4308:                                              $attr->{'src'});
 4309:                     }
 4310:                 }
 4311: 	    }
 4312:             if (lc($tagname) eq 'iframe') {
 4313:                 my $src = $attr->{'src'} ;
 4314:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4315:                     &add_filetype($allfiles,$src,'src');
 4316:                 } elsif ($src =~ m{^/}) {
 4317:                     if ($env{'request.course.id'}) {
 4318:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4319:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4320:                         my $url = &hreflocation('',$fullpath);
 4321:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4322:                             my $relpath = $1;
 4323:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4324:                                 &add_filetype($allfiles,$1,'src');
 4325:                             }
 4326:                         }
 4327:                     }
 4328:                 }
 4329:             }
 4330:             if ($t->[4] =~ m{/>$}) {
 4331:                 pop(@state);
 4332:             }
 4333: 	} elsif ($t->[0] eq 'E') {
 4334: 	    my ($tagname) = ($t->[1]);
 4335: 	    if ($javafiles{'codebase'} ne '') {
 4336: 		$javafiles{'codebase'} .= '/';
 4337: 	    }  
 4338: 	    if (lc($tagname) eq 'applet' ||
 4339: 		lc($tagname) eq 'object' ||
 4340: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4341: 		) {
 4342: 		foreach my $item (keys(%javafiles)) {
 4343: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4344: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4345: 			&add_filetype($allfiles,$file,$item);
 4346: 		    }
 4347: 		}
 4348: 	    } 
 4349: 	    pop @state;
 4350: 	}
 4351:     }
 4352:     foreach my $id (sort(keys(%flashvars))) {
 4353:         if ($shockwave{$id} ne '') {
 4354:             my @pairs = split(/\&/,$flashvars{$id});
 4355:             foreach my $pair (@pairs) {
 4356:                 my ($key,$value) = split(/\=/,$pair);
 4357:                 if ($key eq 'thumb') {
 4358:                     &add_filetype($allfiles,$value,$key);
 4359:                 } elsif ($key eq 'content') {
 4360:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4361:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4362:                     if ($ext ne '') {
 4363:                         &add_filetype($allfiles,$path.$value,$ext);
 4364:                     }
 4365:                 }
 4366:             }
 4367:         }
 4368:     }
 4369:     return 'ok';
 4370: }
 4371: 
 4372: sub add_filetype {
 4373:     my ($allfiles,$file,$type)=@_;
 4374:     if (exists($allfiles->{$file})) {
 4375: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4376: 	    push(@{$allfiles->{$file}}, &escape($type));
 4377: 	}
 4378:     } else {
 4379: 	@{$allfiles->{$file}} = (&escape($type));
 4380:     }
 4381: }
 4382: 
 4383: sub embedded_dependency {
 4384:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4385:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4386:         if (($identifier ne '') &&
 4387:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4388:             ($pathfrom ne '')) {
 4389:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4390:             foreach my $dep (@{$related->{$identifier}}) {
 4391:                 &add_filetype($allfiles,$path.$dep,'object');
 4392:             }
 4393:         }
 4394:     }
 4395:     return;
 4396: }
 4397: 
 4398: sub bubblesheet_converter {
 4399:     my ($cdom,$fullpath,$config,$format) = @_;
 4400:     if ((&domain($cdom) ne '') &&
 4401:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4402:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4403:         my (%csvcols,%csvoptions);
 4404:         if (ref($config->{'fields'}) eq 'HASH') {  
 4405:             %csvcols = %{$config->{'fields'}};
 4406:         }
 4407:         if (ref($config->{'options'}) eq 'HASH') {
 4408:             %csvoptions = %{$config->{'options'}};
 4409:         }
 4410:         my %csvbynum = reverse(%csvcols);
 4411:         my %scantronconf = &get_scantron_config($format,$cdom);
 4412:         if (keys(%scantronconf)) {
 4413:             my %bynum = (
 4414:                           $scantronconf{CODEstart} => 'CODEstart',
 4415:                           $scantronconf{IDstart}   => 'IDstart',
 4416:                           $scantronconf{PaperID}   => 'PaperID',
 4417:                           $scantronconf{FirstName} => 'FirstName',
 4418:                           $scantronconf{LastName}  => 'LastName',
 4419:                           $scantronconf{Qstart}    => 'Qstart',
 4420:                         );
 4421:             my @ordered;
 4422:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4423:                 push(@ordered,$bynum{$item});
 4424:             }
 4425:             my %mapstart = (
 4426:                               CODEstart => 'CODE',
 4427:                               IDstart   => 'ID',
 4428:                               PaperID   => 'PaperID',
 4429:                               FirstName => 'FirstName',
 4430:                               LastName  => 'LastName',
 4431:                               Qstart    => 'FirstQuestion',
 4432:                            );
 4433:             my %maplength = (
 4434:                               CODEstart => 'CODElength',
 4435:                               IDstart   => 'IDlength',
 4436:                               PaperID   => 'PaperIDlength',
 4437:                               FirstName => 'FirstNamelength',
 4438:                               LastName  => 'LastNamelength',
 4439:             );
 4440:             if (open(my $fh,'<',$fullpath)) {
 4441:                 my $output;
 4442:                 my %lettdig = &letter_to_digits();
 4443:                 my %diglett = reverse(%lettdig);
 4444:                 my $numletts = scalar(keys(%lettdig));
 4445:                 my $num = 0;
 4446:                 while (my $line=<$fh>) {
 4447:                     $num ++;
 4448:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4449:                     $line =~ s{[\r\n]+$}{};
 4450:                     my %found;
 4451:                     my @values = split(/,/,$line);
 4452:                     my ($qstart,$record);
 4453:                     for (my $i=0; $i<@values; $i++) {
 4454:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4455:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4456:                             if ($values[$i] eq '') {
 4457:                                 $values[$i] = $scantronconf{'Qoff'};
 4458:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4459:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4460:                                     $values[$i] = $lettdig{uc($values[$i])};
 4461:                                 }
 4462:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4463:                                 if ($values[$i] =~ /^[0-9]$/) {
 4464:                                     $values[$i] = $diglett{$values[$i]};
 4465:                                 }
 4466:                             } else {
 4467:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4468:                                     my $digit;
 4469:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4470:                                         $digit = $lettdig{uc($values[$i])}-1;
 4471:                                         if ($values[$i] eq 'J') {
 4472:                                             $digit += $numletts;
 4473:                                         }
 4474:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4475:                                         $digit = $values[$i]-1;
 4476:                                         if ($values[$i] eq '0') {
 4477:                                             $digit += $numletts;
 4478:                                         }
 4479:                                     }
 4480:                                     my $qval='';
 4481:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4482:                                         if ($j == $digit) {
 4483:                                             $qval .= $scantronconf{'Qon'};
 4484:                                         } else {
 4485:                                             $qval .= $scantronconf{'Qoff'};
 4486:                                         }
 4487:                                     }
 4488:                                     $values[$i] = $qval;
 4489:                                 }
 4490:                             }
 4491:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4492:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4493:                             }
 4494:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4495:                             if ($numblank > 0) {
 4496:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4497:                             }
 4498:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4499:                                 $qstart = $i;
 4500:                                 $found{$csvbynum{$i}} = $values[$i];
 4501:                             } else {
 4502:                                 $found{'FirstQuestion'} .= $values[$i];
 4503:                             }
 4504:                         } elsif (exists($csvbynum{$i})) {
 4505:                             if ($csvoptions{'rem'}) {
 4506:                                 $values[$i] =~ s/^\s+//;
 4507:                             }
 4508:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4509:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4510:                                     $values[$i] = '0'.$values[$i];
 4511:                                 }
 4512:                             }
 4513:                             $found{$csvbynum{$i}} = $values[$i];
 4514:                         }
 4515:                     }
 4516:                     foreach my $item (@ordered) {
 4517:                         my $currlength = 1+length($record);
 4518:                         my $numspaces = $scantronconf{$item} - $currlength;
 4519:                         if ($numspaces > 0) {
 4520:                             $record .= (' ' x $numspaces);
 4521:                         }
 4522:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4523:                             unless ($item eq 'Qstart') {
 4524:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4525:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4526:                                 }
 4527:                             }
 4528:                             $record .= $found{$mapstart{$item}};
 4529:                         }
 4530:                     }
 4531:                     $output .= "$record\n";
 4532:                 }
 4533:                 close($fh);
 4534:                 if ($output) {
 4535:                     if (open(my $fh,'>',$fullpath)) {
 4536:                         print $fh $output;
 4537:                         close($fh);
 4538:                     }
 4539:                 }
 4540:             }
 4541:         }
 4542:         return;
 4543:     }
 4544: }
 4545: 
 4546: sub letter_to_digits {
 4547:     my %lettdig = (
 4548:                     A => 1,
 4549:                     B => 2,
 4550:                     C => 3,
 4551:                     D => 4,
 4552:                     E => 5,
 4553:                     F => 6,
 4554:                     G => 7,
 4555:                     H => 8,
 4556:                     I => 9,
 4557:                     J => 0,
 4558:                   );
 4559:     return %lettdig;
 4560: }
 4561: 
 4562: sub get_scantron_config {
 4563:     my ($which,$cdom) = @_;
 4564:     my @lines = &get_scantronformat_file($cdom);
 4565:     my %config;
 4566:     #FIXME probably should move to XML it has already gotten a bit much now
 4567:     foreach my $line (@lines) {
 4568:         my ($name,$descrip)=split(/:/,$line);
 4569:         if ($name ne $which ) { next; }
 4570:         chomp($line);
 4571:         my @config=split(/:/,$line);
 4572:         $config{'name'}=$config[0];
 4573:         $config{'description'}=$config[1];
 4574:         $config{'CODElocation'}=$config[2];
 4575:         $config{'CODEstart'}=$config[3];
 4576:         $config{'CODElength'}=$config[4];
 4577:         $config{'IDstart'}=$config[5];
 4578:         $config{'IDlength'}=$config[6];
 4579:         $config{'Qstart'}=$config[7];
 4580:         $config{'Qlength'}=$config[8];
 4581:         $config{'Qoff'}=$config[9];
 4582:         $config{'Qon'}=$config[10];
 4583:         $config{'PaperID'}=$config[11];
 4584:         $config{'PaperIDlength'}=$config[12];
 4585:         $config{'FirstName'}=$config[13];
 4586:         $config{'FirstNamelength'}=$config[14];
 4587:         $config{'LastName'}=$config[15];
 4588:         $config{'LastNamelength'}=$config[16];
 4589:         $config{'BubblesPerRow'}=$config[17];
 4590:         last;
 4591:     }
 4592:     return %config;
 4593: }
 4594: 
 4595: sub get_scantronformat_file {
 4596:     my ($cdom) = @_;
 4597:     if ($cdom eq '') {
 4598:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4599:     }
 4600:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4601:     my $gottab = 0;
 4602:     my @lines;
 4603:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4604:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4605:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4606:             if ($formatfile ne '-1') {
 4607:                 @lines = split("\n",$formatfile,-1);
 4608:                 $gottab = 1;
 4609:             }
 4610:         }
 4611:     }
 4612:     if (!$gottab) {
 4613:         my $confname = $cdom.'-domainconfig';
 4614:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4615:         my $formatfile = &getfile($default);
 4616:         if ($formatfile ne '-1') {
 4617:             @lines = split("\n",$formatfile,-1);
 4618:             $gottab = 1;
 4619:         }
 4620:     }
 4621:     if (!$gottab) {
 4622:         my @domains = &current_machine_domains();
 4623:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4624:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4625:                 @lines = <$fh>;
 4626:                 close($fh);
 4627:             }
 4628:         } else {
 4629:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4630:                 @lines = <$fh>;
 4631:                 close($fh);
 4632:             }
 4633:         }
 4634:     }
 4635:     return @lines;
 4636: }
 4637: 
 4638: sub removeuploadedurl {
 4639:     my ($url)=@_;	
 4640:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4641:     return &removeuserfile($uname,$udom,$fname);
 4642: }
 4643: 
 4644: sub removeuserfile {
 4645:     my ($docuname,$docudom,$fname)=@_;
 4646:     my $home=&homeserver($docuname,$docudom);    
 4647:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4648:     if ($result eq 'ok') {	
 4649:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4650:             my $metafile = $fname.'.meta';
 4651:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4652: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4653:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4654:             my $sqlresult = 
 4655:                 &update_portfolio_table($docuname,$docudom,$file,
 4656:                                         'portfolio_metadata',$group,
 4657:                                         'delete');
 4658:         }
 4659:     }
 4660:     return $result;
 4661: }
 4662: 
 4663: sub mkdiruserfile {
 4664:     my ($docuname,$docudom,$dir)=@_;
 4665:     my $home=&homeserver($docuname,$docudom);
 4666:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4667: }
 4668: 
 4669: sub renameuserfile {
 4670:     my ($docuname,$docudom,$old,$new)=@_;
 4671:     my $home=&homeserver($docuname,$docudom);
 4672:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4673:                         &escape("$old").':'.&escape("$new"),$home);
 4674:     if ($result eq 'ok') {
 4675:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4676:             my $oldmeta = $old.'.meta';
 4677:             my $newmeta = $new.'.meta';
 4678:             my $metaresult = 
 4679:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4680: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4681:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4682:             my $sqlresult = 
 4683:                 &update_portfolio_table($docuname,$docudom,$file,
 4684:                                         'portfolio_metadata',$group,
 4685:                                         'delete');
 4686:         }
 4687:     }
 4688:     return $result;
 4689: }
 4690: 
 4691: # ------------------------------------------------------------------------- Log
 4692: 
 4693: sub log {
 4694:     my ($dom,$nam,$hom,$what)=@_;
 4695:     return critical("log:$dom:$nam:$what",$hom);
 4696: }
 4697: 
 4698: # ------------------------------------------------------------------ Course Log
 4699: #
 4700: # This routine flushes several buffers of non-mission-critical nature
 4701: #
 4702: 
 4703: sub flushcourselogs {
 4704:     &logthis('Flushing log buffers');
 4705: #
 4706: # course logs
 4707: # This is a log of all transactions in a course, which can be used
 4708: # for data mining purposes
 4709: #
 4710: # It also collects the courseid database, which lists last transaction
 4711: # times and course titles for all courseids
 4712: #
 4713:     my %courseidbuffer=();
 4714:     foreach my $crsid (keys(%courselogs)) {
 4715:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4716: 		          &escape($courselogs{$crsid}),
 4717: 		          $coursehombuf{$crsid}) eq 'ok') {
 4718: 	    delete $courselogs{$crsid};
 4719:         } else {
 4720:             &logthis('Failed to flush log buffer for '.$crsid);
 4721:             if (length($courselogs{$crsid})>40000) {
 4722:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4723:                         " exceeded maximum size, deleting.</font>");
 4724:                delete $courselogs{$crsid};
 4725:             }
 4726:         }
 4727:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4728:             'description' => $coursedescrbuf{$crsid},
 4729:             'inst_code'    => $courseinstcodebuf{$crsid},
 4730:             'type'        => $coursetypebuf{$crsid},
 4731:             'owner'       => $courseownerbuf{$crsid},
 4732:         };
 4733:     }
 4734: #
 4735: # Write course id database (reverse lookup) to homeserver of courses 
 4736: # Is used in pickcourse
 4737: #
 4738:     foreach my $crs_home (keys(%courseidbuffer)) {
 4739:         my $response = &courseidput(&host_domain($crs_home),
 4740:                                     $courseidbuffer{$crs_home},
 4741:                                     $crs_home,'timeonly');
 4742:     }
 4743: #
 4744: # File accesses
 4745: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4746: #
 4747:     foreach my $entry (keys(%accesshash)) {
 4748:         if ($entry =~ /___count$/) {
 4749:             my ($dom,$name);
 4750:             ($dom,$name,undef)=
 4751: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4752:             if (! defined($dom) || $dom eq '' || 
 4753:                 ! defined($name) || $name eq '') {
 4754:                 my $cid = $env{'request.course.id'};
 4755:                 $dom  = $env{'request.'.$cid.'.domain'};
 4756:                 $name = $env{'request.'.$cid.'.num'};
 4757:             }
 4758:             my $value = $accesshash{$entry};
 4759:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4760:             my %temphash=($url => $value);
 4761:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4762:             if ($result eq 'ok') {
 4763:                 delete $accesshash{$entry};
 4764:             }
 4765:         } else {
 4766:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4767:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4768:             my %temphash=($entry => $accesshash{$entry});
 4769:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4770:                 delete $accesshash{$entry};
 4771:             }
 4772:         }
 4773:     }
 4774: #
 4775: # Roles
 4776: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4777: #
 4778:     foreach my $entry (keys(%userrolehash)) {
 4779:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4780: 	    split(/\:/,$entry);
 4781:         if (&Apache::lonnet::put('nohist_userroles',
 4782:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4783:                 $rudom,$runame) eq 'ok') {
 4784: 	    delete $userrolehash{$entry};
 4785:         }
 4786:     }
 4787: #
 4788: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4789: #
 4790:     my %domrolebuffer = ();
 4791:     foreach my $entry (keys(%domainrolehash)) {
 4792:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4793:         if ($domrolebuffer{$rudom}) {
 4794:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4795:                       '='.&escape($domainrolehash{$entry});
 4796:         } else {
 4797:             $domrolebuffer{$rudom}.=&escape($entry).
 4798:                       '='.&escape($domainrolehash{$entry});
 4799:         }
 4800:         delete $domainrolehash{$entry};
 4801:     }
 4802:     foreach my $dom (keys(%domrolebuffer)) {
 4803: 	my %servers;
 4804: 	if (defined(&domain($dom,'primary'))) {
 4805: 	    my $primary=&domain($dom,'primary');
 4806: 	    my $hostname=&hostname($primary);
 4807: 	    $servers{$primary} = $hostname;
 4808: 	} else { 
 4809: 	    %servers = &get_servers($dom,'library');
 4810: 	}
 4811: 	foreach my $tryserver (keys(%servers)) {
 4812: 	    if (&reply('domroleput:'.$dom.':'.
 4813: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4814: 		last;
 4815: 	    } else {  
 4816: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4817: 	    }
 4818:         }
 4819:     }
 4820:     $dumpcount++;
 4821: }
 4822: 
 4823: sub courselog {
 4824:     my $what=shift;
 4825:     $what=time.':'.$what;
 4826:     unless ($env{'request.course.id'}) { return ''; }
 4827:     $coursedombuf{$env{'request.course.id'}}=
 4828:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4829:     $coursenumbuf{$env{'request.course.id'}}=
 4830:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4831:     $coursehombuf{$env{'request.course.id'}}=
 4832:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4833:     $coursedescrbuf{$env{'request.course.id'}}=
 4834:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4835:     $courseinstcodebuf{$env{'request.course.id'}}=
 4836:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4837:     $courseownerbuf{$env{'request.course.id'}}=
 4838:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4839:     $coursetypebuf{$env{'request.course.id'}}=
 4840:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4841:     if (defined $courselogs{$env{'request.course.id'}}) {
 4842: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4843:     } else {
 4844: 	$courselogs{$env{'request.course.id'}}.=$what;
 4845:     }
 4846:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4847: 	&flushcourselogs();
 4848:     }
 4849: }
 4850: 
 4851: sub courseacclog {
 4852:     my $fnsymb=shift;
 4853:     unless ($env{'request.course.id'}) { return ''; }
 4854:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4855:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4856:         $what.=':POST';
 4857:         # FIXME: Probably ought to escape things....
 4858: 	foreach my $key (keys(%env)) {
 4859:             if ($key=~/^form\.(.*)/) {
 4860:                 my $formitem = $1;
 4861:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4862:                     $what.=':'.$formitem.'='.$env{$key};
 4863:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4864:                     $what.=':'.$formitem.'='.$env{$key};
 4865:                 }
 4866:             }
 4867:         }
 4868:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4869:         # FIXME: We should not be depending on a form parameter that someone
 4870:         # editing lonsearchcat.pm might change in the future.
 4871:         if ($env{'form.phase'} eq 'course_search') {
 4872:             $what.= ':POST';
 4873:             # FIXME: Probably ought to escape things....
 4874:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4875:                                  'crsdiscuss') {
 4876:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4877:             }
 4878:         }
 4879:     }
 4880:     &courselog($what);
 4881: }
 4882: 
 4883: sub countacc {
 4884:     my $url=&declutter(shift);
 4885:     return if (! defined($url) || $url eq '');
 4886:     unless ($env{'request.course.id'}) { return ''; }
 4887: #
 4888: # Mark that this url was used in this course
 4889: #
 4890:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4891: #
 4892: # Increase the access count for this resource in this child process
 4893: #
 4894:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4895:     $accesshash{$key}++;
 4896: }
 4897: 
 4898: sub linklog {
 4899:     my ($from,$to)=@_;
 4900:     $from=&declutter($from);
 4901:     $to=&declutter($to);
 4902:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4903:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4904: }
 4905: 
 4906: sub statslog {
 4907:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4908:     if ($users<2) { return; }
 4909:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4910:             'course'       => $env{'request.course.id'},
 4911:             'sections'     => '"all"',
 4912:             'num_students' => $users,
 4913:             'part'         => $part,
 4914:             'symb'         => $symb,
 4915:             'mean_tries'   => $av_attempts,
 4916:             'deg_of_diff'  => $degdiff});
 4917:     foreach my $key (keys(%dynstore)) {
 4918:         $accesshash{$key}=$dynstore{$key};
 4919:     }
 4920: }
 4921:   
 4922: sub userrolelog {
 4923:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4924:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4925:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4926:        $userrolehash
 4927:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4928:                     =$tend.':'.$tstart;
 4929:     }
 4930:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4931:        $userrolehash
 4932:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4933:                     =$tend.':'.$tstart;
 4934:     }
 4935:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4936:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4937:        $domainrolehash
 4938:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4939:                     = $tend.':'.$tstart;
 4940:     }
 4941: }
 4942: 
 4943: sub courserolelog {
 4944:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4945:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4946:         my $cdom = $1;
 4947:         my $cnum = $2;
 4948:         my $sec = $3;
 4949:         my $namespace = 'rolelog';
 4950:         my %storehash = (
 4951:                            role    => $trole,
 4952:                            start   => $tstart,
 4953:                            end     => $tend,
 4954:                            selfenroll => $selfenroll,
 4955:                            context    => $context,
 4956:                         );
 4957:         if ($trole eq 'gr') {
 4958:             $namespace = 'groupslog';
 4959:             $storehash{'group'} = $sec;
 4960:         } else {
 4961:             $storehash{'section'} = $sec;
 4962:         }
 4963:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4964:                    $domain,$cnum,$cdom);
 4965:         if (($trole ne 'st') || ($sec ne '')) {
 4966:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4967:         }
 4968:     }
 4969:     return;
 4970: }
 4971: 
 4972: sub domainrolelog {
 4973:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4974:     if ($area =~ m{^/($match_domain)/$}) {
 4975:         my $cdom = $1;
 4976:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4977:         my $namespace = 'rolelog';
 4978:         my %storehash = (
 4979:                            role    => $trole,
 4980:                            start   => $tstart,
 4981:                            end     => $tend,
 4982:                            context => $context,
 4983:                         );
 4984:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4985:                    $domain,$domconfiguser,$cdom);
 4986:     }
 4987:     return;
 4988: 
 4989: }
 4990: 
 4991: sub coauthorrolelog {
 4992:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4993:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4994:         my $audom = $1;
 4995:         my $auname = $2;
 4996:         my $namespace = 'rolelog';
 4997:         my %storehash = (
 4998:                            role    => $trole,
 4999:                            start   => $tstart,
 5000:                            end     => $tend,
 5001:                            context => $context,
 5002:                         );
 5003:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5004:                    $domain,$auname,$audom);
 5005:     }
 5006:     return;
 5007: }
 5008: 
 5009: sub get_course_adv_roles {
 5010:     my ($cid,$codes) = @_;
 5011:     $cid=$env{'request.course.id'} unless (defined($cid));
 5012:     my %coursehash=&coursedescription($cid);
 5013:     my $crstype = &Apache::loncommon::course_type($cid);
 5014:     my %nothide=();
 5015:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5016:         if ($user !~ /:/) {
 5017: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5018:         } else {
 5019:             $nothide{$user}=1;
 5020:         }
 5021:     }
 5022:     my @possdoms = ($coursehash{'domain'});
 5023:     if ($coursehash{'checkforpriv'}) {
 5024:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5025:     }
 5026:     my %returnhash=();
 5027:     my %dumphash=
 5028:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5029:     my $now=time;
 5030:     my %privileged;
 5031:     foreach my $entry (keys(%dumphash)) {
 5032: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5033:         if (($tstart) && ($tstart<0)) { next; }
 5034:         if (($tend) && ($tend<$now)) { next; }
 5035:         if (($tstart) && ($now<$tstart)) { next; }
 5036:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5037: 	if ($username eq '' || $domain eq '') { next; }
 5038:         if ((&privileged($username,$domain,\@possdoms)) &&
 5039:             (!$nothide{$username.':'.$domain})) { next; }
 5040: 	if ($role eq 'cr') { next; }
 5041:         if ($codes) {
 5042:             if ($section) { $role .= ':'.$section; }
 5043:             if ($returnhash{$role}) {
 5044:                 $returnhash{$role}.=','.$username.':'.$domain;
 5045:             } else {
 5046:                 $returnhash{$role}=$username.':'.$domain;
 5047:             }
 5048:         } else {
 5049:             my $key=&plaintext($role,$crstype);
 5050:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5051:             if ($returnhash{$key}) {
 5052: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5053:             } else {
 5054:                 $returnhash{$key}=$username.':'.$domain;
 5055:             }
 5056:         }
 5057:     }
 5058:     return %returnhash;
 5059: }
 5060: 
 5061: sub get_my_roles {
 5062:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5063:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5064:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5065:     my (%dumphash,%nothide);
 5066:     if ($context eq 'userroles') {
 5067:         %dumphash = &dump('roles',$udom,$uname);
 5068:     } else {
 5069:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5070:         if ($hidepriv) {
 5071:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5072:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5073:                 if ($user !~ /:/) {
 5074:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5075:                 } else {
 5076:                     $nothide{$user} = 1;
 5077:                 }
 5078:             }
 5079:         }
 5080:     }
 5081:     my %returnhash=();
 5082:     my $now=time;
 5083:     my %privileged;
 5084:     foreach my $entry (keys(%dumphash)) {
 5085:         my ($role,$tend,$tstart);
 5086:         if ($context eq 'userroles') {
 5087:             next if ($entry =~ /^rolesdef/);
 5088: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5089:         } else {
 5090:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5091:         }
 5092:         if (($tstart) && ($tstart<0)) { next; }
 5093:         my $status = 'active';
 5094:         if (($tend) && ($tend<=$now)) {
 5095:             $status = 'previous';
 5096:         } 
 5097:         if (($tstart) && ($now<$tstart)) {
 5098:             $status = 'future';
 5099:         }
 5100:         if (ref($types) eq 'ARRAY') {
 5101:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5102:                 next;
 5103:             } 
 5104:         } else {
 5105:             if ($status ne 'active') {
 5106:                 next;
 5107:             }
 5108:         }
 5109:         my ($rolecode,$username,$domain,$section,$area);
 5110:         if ($context eq 'userroles') {
 5111:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5112:             (undef,$domain,$username,$section) = split(/\//,$area);
 5113:         } else {
 5114:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5115:         }
 5116:         if (ref($roledoms) eq 'ARRAY') {
 5117:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5118:                 next;
 5119:             }
 5120:         }
 5121:         if (ref($roles) eq 'ARRAY') {
 5122:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5123:                 if ($role =~ /^cr\//) {
 5124:                     if (!grep(/^cr$/,@{$roles})) {
 5125:                         next;
 5126:                     }
 5127:                 } elsif ($role =~ /^gr\//) {
 5128:                     if (!grep(/^gr$/,@{$roles})) {
 5129:                         next;
 5130:                     }
 5131:                 } else {
 5132:                     next;
 5133:                 }
 5134:             }
 5135:         }
 5136:         if ($hidepriv) {
 5137:             my @privroles = ('dc','su');
 5138:             if ($context eq 'userroles') {
 5139:                 next if (grep(/^\Q$role\E$/,@privroles));
 5140:             } else {
 5141:                 my $possdoms = [$domain];
 5142:                 if (ref($roledoms) eq 'ARRAY') {
 5143:                    push(@{$possdoms},@{$roledoms}); 
 5144:                 }
 5145:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5146:                     if (!$nothide{$username.':'.$domain}) {
 5147:                         next;
 5148:                     }
 5149:                 }
 5150:             }
 5151:         }
 5152:         if ($withsec) {
 5153:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5154:                 $tstart.':'.$tend;
 5155:         } else {
 5156:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5157:         }
 5158:     }
 5159:     return %returnhash;
 5160: }
 5161: 
 5162: sub get_all_adhocroles {
 5163:     my ($dom) = @_;
 5164:     my @roles_by_num = ();
 5165:     my %domdefaults = &get_domain_defaults($dom);
 5166:     my (%description,%access_in_dom,%access_info);
 5167:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5168:         my $count = 0;
 5169:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5170:         my %ordered;
 5171:         foreach my $role (sort(keys(%domcurrent))) {
 5172:             my ($order,$desc,$access_in_dom);
 5173:             if (ref($domcurrent{$role}) eq 'HASH') {
 5174:                 $order = $domcurrent{$role}{'order'};
 5175:                 $desc = $domcurrent{$role}{'desc'};
 5176:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5177:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5178:             }
 5179:             if ($order eq '') {
 5180:                 $order = $count;
 5181:             }
 5182:             $ordered{$order} = $role;
 5183:             if ($desc ne '') {
 5184:                 $description{$role} = $desc;
 5185:             } else {
 5186:                 $description{$role}= $role;
 5187:             }
 5188:             $count++;
 5189:         }
 5190:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5191:             push(@roles_by_num,$ordered{$item});
 5192:         }
 5193:     }
 5194:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5195: }
 5196: 
 5197: sub get_my_adhocroles {
 5198:     my ($cid,$checkreg) = @_;
 5199:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5200:     if ($env{'request.course.id'} eq $cid) {
 5201:         $cdom = $env{'course.'.$cid.'.domain'};
 5202:         $cnum = $env{'course.'.$cid.'.num'};
 5203:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5204:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5205:         $cdom = $1;
 5206:         $cnum = $2;
 5207:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5208:                                      $cdom,$cnum);
 5209:     }
 5210:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5211:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5212:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5213:         if ($rosterhash{$user} ne '') {
 5214:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5215:             return ([],{}) if ($type eq 'auto');
 5216:         }
 5217:     }
 5218:     if (($cdom ne '') && ($cnum ne ''))  {
 5219:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5220:             my $then=$env{'user.login.time'};
 5221:             my $update=$env{'user.update.time'};
 5222:             if (!$update) {
 5223:                 $update = $then;
 5224:             }
 5225:             my @liveroles;
 5226:             foreach my $role ('dh','da') {
 5227:                 if ($env{"user.role.$role./$cdom/"}) {
 5228:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5229:                     my $limit = $update;
 5230:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5231:                         $limit = $then;
 5232:                     }
 5233:                     my $activerole = 1;
 5234:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5235:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5236:                     if ($activerole) {
 5237:                         push(@liveroles,$role);
 5238:                     }
 5239:                 }
 5240:             }
 5241:             if (@liveroles) {
 5242:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5243:                     my ($accessref,$accessinfo,%access_in_dom);
 5244:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5245:                     if (ref($roles_by_num) eq 'ARRAY') {
 5246:                         if (@{$roles_by_num}) {
 5247:                             my %settings;
 5248:                             if ($env{'request.course.id'} eq $cid) {
 5249:                                 foreach my $envkey (keys(%env)) {
 5250:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5251:                                         $settings{$1} = $env{$envkey};
 5252:                                     }
 5253:                                 }
 5254:                             } else {
 5255:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5256:                             }
 5257:                             my %setincrs;
 5258:                             if ($settings{'internal.adhocaccess'}) {
 5259:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5260:                             }
 5261:                             my @statuses;
 5262:                             if ($env{'environment.inststatus'}) {
 5263:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5264:                             }
 5265:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5266:                             if (ref($accessref) eq 'HASH') {
 5267:                                 %access_in_dom = %{$accessref};
 5268:                             }
 5269:                             foreach my $role (@{$roles_by_num}) {
 5270:                                 my ($curraccess,@okstatus,@personnel);
 5271:                                 if ($setincrs{$role}) {
 5272:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5273:                                     if ($curraccess eq 'status') {
 5274:                                         @okstatus = split(/\&/,$rest);
 5275:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5276:                                         @personnel = split(/\&/,$rest);
 5277:                                     }
 5278:                                 } else {
 5279:                                     $curraccess = $access_in_dom{$role};
 5280:                                     if (ref($accessinfo) eq 'HASH') {
 5281:                                         if ($curraccess eq 'status') {
 5282:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5283:                                                 @okstatus = @{$accessinfo->{$role}};
 5284:                                             }
 5285:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5286:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5287:                                                 @personnel = @{$accessinfo->{$role}};
 5288:                                             }
 5289:                                         }
 5290:                                     }
 5291:                                 }
 5292:                                 if ($curraccess eq 'none') {
 5293:                                     next;
 5294:                                 } elsif ($curraccess eq 'all') {
 5295:                                     push(@possroles,$role);
 5296:                                 } elsif ($curraccess eq 'dh') {
 5297:                                     if (grep(/^dh$/,@liveroles)) {
 5298:                                         push(@possroles,$role);
 5299:                                     } else {
 5300:                                         next;
 5301:                                     }
 5302:                                 } elsif ($curraccess eq 'da') {
 5303:                                     if (grep(/^da$/,@liveroles)) {
 5304:                                         push(@possroles,$role);
 5305:                                     } else {
 5306:                                         next;
 5307:                                     }
 5308:                                 } elsif ($curraccess eq 'status') {
 5309:                                     if (@okstatus) {
 5310:                                         if (!@statuses) {
 5311:                                             if (grep(/^default$/,@okstatus)) {
 5312:                                                 push(@possroles,$role);
 5313:                                             }
 5314:                                         } else {
 5315:                                             foreach my $status (@okstatus) {
 5316:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5317:                                                     push(@possroles,$role);
 5318:                                                     last;
 5319:                                                 }
 5320:                                             }
 5321:                                         }
 5322:                                     }
 5323:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5324:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5325:                                         if ($curraccess eq 'exc') {
 5326:                                             push(@possroles,$role);
 5327:                                         }
 5328:                                     } elsif ($curraccess eq 'inc') {
 5329:                                         push(@possroles,$role);
 5330:                                     }
 5331:                                 }
 5332:                             }
 5333:                         }
 5334:                     }
 5335:                 }
 5336:             }
 5337:         }
 5338:     }
 5339:     unless (ref($description) eq 'HASH') {
 5340:         if (ref($roles_by_num) eq 'ARRAY') {
 5341:             my %desc;
 5342:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5343:             $description = \%desc;
 5344:         } else {
 5345:             $description = {};
 5346:         }
 5347:     }
 5348:     return (\@possroles,$description);
 5349: }
 5350: 
 5351: # ----------------------------------------------------- Frontpage Announcements
 5352: #
 5353: #
 5354: 
 5355: sub postannounce {
 5356:     my ($server,$text)=@_;
 5357:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5358:     unless ($text=~/\w/) { $text=''; }
 5359:     return &reply('setannounce:'.&escape($text),$server);
 5360: }
 5361: 
 5362: sub getannounce {
 5363: 
 5364:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5365: 	my $announcement='';
 5366: 	while (my $line = <$fh>) { $announcement .= $line; }
 5367: 	close($fh);
 5368: 	if ($announcement=~/\w/) { 
 5369: 	    return 
 5370:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5371:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5372: 	} else {
 5373: 	    return '';
 5374: 	}
 5375:     } else {
 5376: 	return '';
 5377:     }
 5378: }
 5379: 
 5380: # ---------------------------------------------------------- Course ID routines
 5381: # Deal with domain's nohist_courseid.db files
 5382: #
 5383: 
 5384: sub courseidput {
 5385:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5386:     return unless (ref($storehash) eq 'HASH');
 5387:     my $outcome;
 5388:     if ($caller eq 'timeonly') {
 5389:         my $cids = '';
 5390:         foreach my $item (keys(%$storehash)) {
 5391:             $cids.=&escape($item).'&';
 5392:         }
 5393:         $cids=~s/\&$//;
 5394:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5395:                           $coursehome);       
 5396:     } else {
 5397:         my $items = '';
 5398:         foreach my $item (keys(%$storehash)) {
 5399:             $items.= &escape($item).'='.
 5400:                      &freeze_escape($$storehash{$item}).'&';
 5401:         }
 5402:         $items=~s/\&$//;
 5403:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5404:                           $coursehome);
 5405:     }
 5406:     if ($outcome eq 'unknown_cmd') {
 5407:         my $what;
 5408:         foreach my $cid (keys(%$storehash)) {
 5409:             $what .= &escape($cid).'=';
 5410:             foreach my $item ('description','inst_code','owner','type') {
 5411:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5412:             }
 5413:             $what =~ s/\:$/&/;
 5414:         }
 5415:         $what =~ s/\&$//;  
 5416:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5417:     } else {
 5418:         return $outcome;
 5419:     }
 5420: }
 5421: 
 5422: sub courseiddump {
 5423:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5424:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5425:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5426:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5427:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5428:     my $as_hash = 1;
 5429:     my %returnhash;
 5430:     if (!$domfilter) { $domfilter=''; }
 5431:     my %libserv = &all_library();
 5432:     foreach my $tryserver (keys(%libserv)) {
 5433:         if ( (  $hostidflag == 1 
 5434: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5435: 	     || (!defined($hostidflag)) ) {
 5436: 
 5437: 	    if (($domfilter eq '') ||
 5438: 		(&host_domain($tryserver) eq $domfilter)) {
 5439:                 my $rep;
 5440:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5441:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5442:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5443:                                 &escape($descfilter), &escape($instcodefilter), 
 5444:                                 &escape($ownerfilter), &escape($coursefilter),
 5445:                                 &escape($typefilter), &escape($regexp_ok), 
 5446:                                 $as_hash, &escape($selfenrollonly), 
 5447:                                 &escape($catfilter), $showhidden, $caller, 
 5448:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5449:                                 &escape($createdbefore), &escape($createdafter), 
 5450:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5451:                                 $reqcrsdom,&escape($reqinstcode))));
 5452:                 } else {
 5453:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5454:                              $sincefilter.':'.&escape($descfilter).':'.
 5455:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5456:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5457:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5458:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5459:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5460:                              &escape($cc_clone).':'.$cloneonly.':'.
 5461:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5462:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5463:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5464:                 }
 5465:                      
 5466:                 my @pairs=split(/\&/,$rep);
 5467:                 foreach my $item (@pairs) {
 5468:                     my ($key,$value)=split(/\=/,$item,2);
 5469:                     $key = &unescape($key);
 5470:                     next if ($key =~ /^error: 2 /);
 5471:                     my $result = &thaw_unescape($value);
 5472:                     if (ref($result) eq 'HASH') {
 5473:                         $returnhash{$key}=$result;
 5474:                     } else {
 5475:                         my @responses = split(/:/,$value);
 5476:                         my @items = ('description','inst_code','owner','type');
 5477:                         for (my $i=0; $i<@responses; $i++) {
 5478:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5479:                         }
 5480:                     }
 5481:                 }
 5482:             }
 5483:         }
 5484:     }
 5485:     return %returnhash;
 5486: }
 5487: 
 5488: sub courselastaccess {
 5489:     my ($cdom,$cnum,$hostidref) = @_;
 5490:     my %returnhash;
 5491:     if ($cdom && $cnum) {
 5492:         my $chome = &homeserver($cnum,$cdom);
 5493:         if ($chome ne 'no_host') {
 5494:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5495:             &extract_lastaccess(\%returnhash,$rep);
 5496:         }
 5497:     } else {
 5498:         if (!$cdom) { $cdom=''; }
 5499:         my %libserv = &all_library();
 5500:         foreach my $tryserver (keys(%libserv)) {
 5501:             if (ref($hostidref) eq 'ARRAY') {
 5502:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5503:             } 
 5504:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5505:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5506:                 &extract_lastaccess(\%returnhash,$rep);
 5507:             }
 5508:         }
 5509:     }
 5510:     return %returnhash;
 5511: }
 5512: 
 5513: sub extract_lastaccess {
 5514:     my ($returnhash,$rep) = @_;
 5515:     if (ref($returnhash) eq 'HASH') {
 5516:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5517:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5518:                  $rep eq '') {
 5519:             my @pairs=split(/\&/,$rep);
 5520:             foreach my $item (@pairs) {
 5521:                 my ($key,$value)=split(/\=/,$item,2);
 5522:                 $key = &unescape($key);
 5523:                 next if ($key =~ /^error: 2 /);
 5524:                 $returnhash->{$key} = &thaw_unescape($value);
 5525:             }
 5526:         }
 5527:     }
 5528:     return;
 5529: }
 5530: 
 5531: # ---------------------------------------------------------- DC e-mail
 5532: 
 5533: sub dcmailput {
 5534:     my ($domain,$msgid,$message,$server)=@_;
 5535:     my $status = &Apache::lonnet::critical(
 5536:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5537:        &escape($message),$server);
 5538:     return $status;
 5539: }
 5540: 
 5541: sub dcmaildump {
 5542:     my ($dom,$startdate,$enddate,$senders) = @_;
 5543:     my %returnhash=();
 5544: 
 5545:     if (defined(&domain($dom,'primary'))) {
 5546:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5547:                                                          &escape($enddate).':';
 5548: 	my @esc_senders=map { &escape($_)} @$senders;
 5549: 	$cmd.=&escape(join('&',@esc_senders));
 5550: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5551:             my ($key,$value) = split(/\=/,$line,2);
 5552:             if (($key) && ($value)) {
 5553:                 $returnhash{&unescape($key)} = &unescape($value);
 5554:             }
 5555:         }
 5556:     }
 5557:     return %returnhash;
 5558: }
 5559: # ---------------------------------------------------------- Domain roles
 5560: 
 5561: sub get_domain_roles {
 5562:     my ($dom,$roles,$startdate,$enddate)=@_;
 5563:     if ((!defined($startdate)) || ($startdate eq '')) {
 5564:         $startdate = '.';
 5565:     }
 5566:     if ((!defined($enddate)) || ($enddate eq '')) {
 5567:         $enddate = '.';
 5568:     }
 5569:     my $rolelist;
 5570:     if (ref($roles) eq 'ARRAY') {
 5571:         $rolelist = join('&',@{$roles});
 5572:     }
 5573:     my %personnel = ();
 5574: 
 5575:     my %servers = &get_servers($dom,'library');
 5576:     foreach my $tryserver (keys(%servers)) {
 5577: 	%{$personnel{$tryserver}}=();
 5578: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5579: 					    &escape($startdate).':'.
 5580: 					    &escape($enddate).':'.
 5581: 					    &escape($rolelist), $tryserver))) {
 5582: 	    my ($key,$value) = split(/\=/,$line,2);
 5583: 	    if (($key) && ($value)) {
 5584: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5585: 	    }
 5586: 	}
 5587:     }
 5588:     return %personnel;
 5589: }
 5590: 
 5591: sub get_active_domroles {
 5592:     my ($dom,$roles) = @_;
 5593:     return () unless (ref($roles) eq 'ARRAY');
 5594:     my $now = time;
 5595:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5596:     my %domroles;
 5597:     foreach my $server (keys(%dompersonnel)) {
 5598:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5599:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5600:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5601:         }
 5602:     }
 5603:     return %domroles;
 5604: }
 5605: 
 5606: # ----------------------------------------------------------- Interval timing 
 5607: 
 5608: {
 5609: # Caches needed for speedup of navmaps
 5610: # We don't want to cache this for very long at all (5 seconds at most)
 5611: # 
 5612: # The user for whom we cache
 5613: my $cachedkey='';
 5614: # The cached times for this user
 5615: my %cachedtimes=();
 5616: # When this was last done
 5617: my $cachedtime='';
 5618: 
 5619: sub load_all_first_access {
 5620:     my ($uname,$udom,$ignorecache)=@_;
 5621:     if (($cachedkey eq $uname.':'.$udom) &&
 5622:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5623:         (!$ignorecache)) {
 5624:         return;
 5625:     }
 5626:     $cachedtime=time;
 5627:     $cachedkey=$uname.':'.$udom;
 5628:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5629: }
 5630: 
 5631: sub get_first_access {
 5632:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5633:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5634:     if ($argsymb) { $symb=$argsymb; }
 5635:     my ($map,$id,$res)=&decode_symb($symb);
 5636:     if ($argmap) { $map = $argmap; }
 5637:     if ($type eq 'course') {
 5638: 	$res='course';
 5639:     } elsif ($type eq 'map') {
 5640: 	$res=&symbread($map);
 5641:     } else {
 5642: 	$res=$symb;
 5643:     }
 5644:     &load_all_first_access($uname,$udom,$ignorecache);
 5645:     return $cachedtimes{"$courseid\0$res"};
 5646: }
 5647: 
 5648: sub set_first_access {
 5649:     my ($type,$interval)=@_;
 5650:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5651:     my ($map,$id,$res)=&decode_symb($symb);
 5652:     if ($type eq 'course') {
 5653: 	$res='course';
 5654:     } elsif ($type eq 'map') {
 5655: 	$res=&symbread($map);
 5656:     } else {
 5657: 	$res=$symb;
 5658:     }
 5659:     $cachedkey='';
 5660:     my $firstaccess=&get_first_access($type,$symb,$map);
 5661:     if ($firstaccess) {
 5662:         &logthis("First access time already set ($firstaccess) when attempting ".
 5663:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5664:                  "in $courseid");
 5665:         return 'already_set';
 5666:     } else {
 5667:         my $start = time;
 5668: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5669:                           $udom,$uname);
 5670:         if ($putres eq 'ok') {
 5671:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5672:                  $udom,$uname); 
 5673:             &appenv(
 5674:                      {
 5675:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5676:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5677:                      }
 5678:                   );
 5679:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5680:                 $cachedtimes{"$courseid\0$res"} = $start;
 5681:             }
 5682:         } elsif ($putres ne 'refused') {
 5683:             &logthis("Result: $putres when attempting to set first access time ".
 5684:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5685:         }
 5686:         return $putres;
 5687:     }
 5688:     return 'already_set';
 5689: }
 5690: }
 5691: 
 5692: # --------------------------------------------- Set Expire Date for Spreadsheet
 5693: 
 5694: sub expirespread {
 5695:     my ($uname,$udom,$stype,$usymb)=@_;
 5696:     my $cid=$env{'request.course.id'}; 
 5697:     if ($cid) {
 5698:        my $now=time;
 5699:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5700:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5701:                             $env{'course.'.$cid.'.num'}.
 5702: 	        	    ':nohist_expirationdates:'.
 5703:                             &escape($key).'='.$now,
 5704:                             $env{'course.'.$cid.'.home'})
 5705:     }
 5706:     return 'ok';
 5707: }
 5708: 
 5709: # ----------------------------------------------------- Devalidate Spreadsheets
 5710: 
 5711: sub devalidate {
 5712:     my ($symb,$uname,$udom)=@_;
 5713:     my $cid=$env{'request.course.id'}; 
 5714:     if ($cid) {
 5715:         # delete the stored spreadsheets for
 5716:         # - the student level sheet of this user in course's homespace
 5717:         # - the assessment level sheet for this resource 
 5718:         #   for this user in user's homespace
 5719: 	# - current conditional state info
 5720: 	my $key=$uname.':'.$udom.':';
 5721:         my $status=
 5722: 	    &del('nohist_calculatedsheets',
 5723: 		 [$key.'studentcalc:'],
 5724: 		 $env{'course.'.$cid.'.domain'},
 5725: 		 $env{'course.'.$cid.'.num'})
 5726: 		.' '.
 5727: 	    &del('nohist_calculatedsheets_'.$cid,
 5728: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5729:         unless ($status eq 'ok ok') {
 5730:            &logthis('Could not devalidate spreadsheet '.
 5731:                     $uname.' at '.$udom.' for '.
 5732: 		    $symb.': '.$status);
 5733:         }
 5734: 	&delenv('user.state.'.$cid);
 5735:     }
 5736: }
 5737: 
 5738: sub get_scalar {
 5739:     my ($string,$end) = @_;
 5740:     my $value;
 5741:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5742: 	$value = $1;
 5743:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5744: 	$value = $1;
 5745:     }
 5746:     return &unescape($value);
 5747: }
 5748: 
 5749: sub array2str {
 5750:   my (@array) = @_;
 5751:   my $result=&arrayref2str(\@array);
 5752:   $result=~s/^__ARRAY_REF__//;
 5753:   $result=~s/__END_ARRAY_REF__$//;
 5754:   return $result;
 5755: }
 5756: 
 5757: sub arrayref2str {
 5758:   my ($arrayref) = @_;
 5759:   my $result='__ARRAY_REF__';
 5760:   foreach my $elem (@$arrayref) {
 5761:     if(ref($elem) eq 'ARRAY') {
 5762:       $result.=&arrayref2str($elem).'&';
 5763:     } elsif(ref($elem) eq 'HASH') {
 5764:       $result.=&hashref2str($elem).'&';
 5765:     } elsif(ref($elem)) {
 5766:       #print("Got a ref of ".(ref($elem))." skipping.");
 5767:     } else {
 5768:       $result.=&escape($elem).'&';
 5769:     }
 5770:   }
 5771:   $result=~s/\&$//;
 5772:   $result .= '__END_ARRAY_REF__';
 5773:   return $result;
 5774: }
 5775: 
 5776: sub hash2str {
 5777:   my (%hash) = @_;
 5778:   my $result=&hashref2str(\%hash);
 5779:   $result=~s/^__HASH_REF__//;
 5780:   $result=~s/__END_HASH_REF__$//;
 5781:   return $result;
 5782: }
 5783: 
 5784: sub hashref2str {
 5785:   my ($hashref)=@_;
 5786:   my $result='__HASH_REF__';
 5787:   foreach my $key (sort(keys(%$hashref))) {
 5788:     if (ref($key) eq 'ARRAY') {
 5789:       $result.=&arrayref2str($key).'=';
 5790:     } elsif (ref($key) eq 'HASH') {
 5791:       $result.=&hashref2str($key).'=';
 5792:     } elsif (ref($key)) {
 5793:       $result.='=';
 5794:       #print("Got a ref of ".(ref($key))." skipping.");
 5795:     } else {
 5796: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5797:     }
 5798: 
 5799:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5800:       $result.=&arrayref2str($hashref->{$key}).'&';
 5801:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5802:       $result.=&hashref2str($hashref->{$key}).'&';
 5803:     } elsif(ref($hashref->{$key})) {
 5804:        $result.='&';
 5805:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5806:     } else {
 5807:       $result.=&escape($hashref->{$key}).'&';
 5808:     }
 5809:   }
 5810:   $result=~s/\&$//;
 5811:   $result .= '__END_HASH_REF__';
 5812:   return $result;
 5813: }
 5814: 
 5815: sub str2hash {
 5816:     my ($string)=@_;
 5817:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5818:     return %$hash;
 5819: }
 5820: 
 5821: sub str2hashref {
 5822:   my ($string) = @_;
 5823: 
 5824:   my %hash;
 5825: 
 5826:   if($string !~ /^__HASH_REF__/) {
 5827:       if (! ($string eq '' || !defined($string))) {
 5828: 	  $hash{'error'}='Not hash reference';
 5829:       }
 5830:       return (\%hash, $string);
 5831:   }
 5832: 
 5833:   $string =~ s/^__HASH_REF__//;
 5834: 
 5835:   while($string !~ /^__END_HASH_REF__/) {
 5836:       #key
 5837:       my $key='';
 5838:       if($string =~ /^__HASH_REF__/) {
 5839:           ($key, $string)=&str2hashref($string);
 5840:           if(defined($key->{'error'})) {
 5841:               $hash{'error'}='Bad data';
 5842:               return (\%hash, $string);
 5843:           }
 5844:       } elsif($string =~ /^__ARRAY_REF__/) {
 5845:           ($key, $string)=&str2arrayref($string);
 5846:           if($key->[0] eq 'Array reference error') {
 5847:               $hash{'error'}='Bad data';
 5848:               return (\%hash, $string);
 5849:           }
 5850:       } else {
 5851:           $string =~ s/^(.*?)=//;
 5852: 	  $key=&unescape($1);
 5853:       }
 5854:       $string =~ s/^=//;
 5855: 
 5856:       #value
 5857:       my $value='';
 5858:       if($string =~ /^__HASH_REF__/) {
 5859:           ($value, $string)=&str2hashref($string);
 5860:           if(defined($value->{'error'})) {
 5861:               $hash{'error'}='Bad data';
 5862:               return (\%hash, $string);
 5863:           }
 5864:       } elsif($string =~ /^__ARRAY_REF__/) {
 5865:           ($value, $string)=&str2arrayref($string);
 5866:           if($value->[0] eq 'Array reference error') {
 5867:               $hash{'error'}='Bad data';
 5868:               return (\%hash, $string);
 5869:           }
 5870:       } else {
 5871: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5872:       }
 5873:       $string =~ s/^&//;
 5874: 
 5875:       $hash{$key}=$value;
 5876:   }
 5877: 
 5878:   $string =~ s/^__END_HASH_REF__//;
 5879: 
 5880:   return (\%hash, $string);
 5881: }
 5882: 
 5883: sub str2array {
 5884:     my ($string)=@_;
 5885:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5886:     return @$array;
 5887: }
 5888: 
 5889: sub str2arrayref {
 5890:   my ($string) = @_;
 5891:   my @array;
 5892: 
 5893:   if($string !~ /^__ARRAY_REF__/) {
 5894:       if (! ($string eq '' || !defined($string))) {
 5895: 	  $array[0]='Array reference error';
 5896:       }
 5897:       return (\@array, $string);
 5898:   }
 5899: 
 5900:   $string =~ s/^__ARRAY_REF__//;
 5901: 
 5902:   while($string !~ /^__END_ARRAY_REF__/) {
 5903:       my $value='';
 5904:       if($string =~ /^__HASH_REF__/) {
 5905:           ($value, $string)=&str2hashref($string);
 5906:           if(defined($value->{'error'})) {
 5907:               $array[0] ='Array reference error';
 5908:               return (\@array, $string);
 5909:           }
 5910:       } elsif($string =~ /^__ARRAY_REF__/) {
 5911:           ($value, $string)=&str2arrayref($string);
 5912:           if($value->[0] eq 'Array reference error') {
 5913:               $array[0] ='Array reference error';
 5914:               return (\@array, $string);
 5915:           }
 5916:       } else {
 5917: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5918:       }
 5919:       $string =~ s/^&//;
 5920: 
 5921:       push(@array, $value);
 5922:   }
 5923: 
 5924:   $string =~ s/^__END_ARRAY_REF__//;
 5925: 
 5926:   return (\@array, $string);
 5927: }
 5928: 
 5929: # -------------------------------------------------------------------Temp Store
 5930: 
 5931: sub tmpreset {
 5932:   my ($symb,$namespace,$domain,$stuname) = @_;
 5933:   if (!$symb) {
 5934:     $symb=&symbread();
 5935:     if (!$symb) { $symb= $env{'request.url'}; }
 5936:   }
 5937:   $symb=escape($symb);
 5938: 
 5939:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5940:   $namespace=~s/\//\_/g;
 5941:   $namespace=~s/\W//g;
 5942: 
 5943:   if (!$domain) { $domain=$env{'user.domain'}; }
 5944:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5945:   if ($domain eq 'public' && $stuname eq 'public') {
 5946:       $stuname=$ENV{'REMOTE_ADDR'};
 5947:   }
 5948:   my $path=LONCAPA::tempdir();
 5949:   my %hash;
 5950:   if (tie(%hash,'GDBM_File',
 5951: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5952: 	  &GDBM_WRCREAT(),0640)) {
 5953:     foreach my $key (keys(%hash)) {
 5954:       if ($key=~ /:$symb/) {
 5955: 	delete($hash{$key});
 5956:       }
 5957:     }
 5958:   }
 5959: }
 5960: 
 5961: sub tmpstore {
 5962:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5963: 
 5964:   if (!$symb) {
 5965:     $symb=&symbread();
 5966:     if (!$symb) { $symb= $env{'request.url'}; }
 5967:   }
 5968:   $symb=escape($symb);
 5969: 
 5970:   if (!$namespace) {
 5971:     # I don't think we would ever want to store this for a course.
 5972:     # it seems this will only be used if we don't have a course.
 5973:     #$namespace=$env{'request.course.id'};
 5974:     #if (!$namespace) {
 5975:       $namespace=$env{'request.state'};
 5976:     #}
 5977:   }
 5978:   $namespace=~s/\//\_/g;
 5979:   $namespace=~s/\W//g;
 5980:   if (!$domain) { $domain=$env{'user.domain'}; }
 5981:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5982:   if ($domain eq 'public' && $stuname eq 'public') {
 5983:       $stuname=$ENV{'REMOTE_ADDR'};
 5984:   }
 5985:   my $now=time;
 5986:   my %hash;
 5987:   my $path=LONCAPA::tempdir();
 5988:   if (tie(%hash,'GDBM_File',
 5989: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5990: 	  &GDBM_WRCREAT(),0640)) {
 5991:     $hash{"version:$symb"}++;
 5992:     my $version=$hash{"version:$symb"};
 5993:     my $allkeys=''; 
 5994:     foreach my $key (keys(%$storehash)) {
 5995:       $allkeys.=$key.':';
 5996:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5997:     }
 5998:     $hash{"$version:$symb:timestamp"}=$now;
 5999:     $allkeys.='timestamp';
 6000:     $hash{"$version:keys:$symb"}=$allkeys;
 6001:     if (untie(%hash)) {
 6002:       return 'ok';
 6003:     } else {
 6004:       return "error:$!";
 6005:     }
 6006:   } else {
 6007:     return "error:$!";
 6008:   }
 6009: }
 6010: 
 6011: # -----------------------------------------------------------------Temp Restore
 6012: 
 6013: sub tmprestore {
 6014:   my ($symb,$namespace,$domain,$stuname) = @_;
 6015: 
 6016:   if (!$symb) {
 6017:     $symb=&symbread();
 6018:     if (!$symb) { $symb= $env{'request.url'}; }
 6019:   }
 6020:   $symb=escape($symb);
 6021: 
 6022:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6023: 
 6024:   if (!$domain) { $domain=$env{'user.domain'}; }
 6025:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6026:   if ($domain eq 'public' && $stuname eq 'public') {
 6027:       $stuname=$ENV{'REMOTE_ADDR'};
 6028:   }
 6029:   my %returnhash;
 6030:   $namespace=~s/\//\_/g;
 6031:   $namespace=~s/\W//g;
 6032:   my %hash;
 6033:   my $path=LONCAPA::tempdir();
 6034:   if (tie(%hash,'GDBM_File',
 6035: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6036: 	  &GDBM_READER(),0640)) {
 6037:     my $version=$hash{"version:$symb"};
 6038:     $returnhash{'version'}=$version;
 6039:     my $scope;
 6040:     for ($scope=1;$scope<=$version;$scope++) {
 6041:       my $vkeys=$hash{"$scope:keys:$symb"};
 6042:       my @keys=split(/:/,$vkeys);
 6043:       my $key;
 6044:       $returnhash{"$scope:keys"}=$vkeys;
 6045:       foreach $key (@keys) {
 6046: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6047: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6048:       }
 6049:     }
 6050:     if (!(untie(%hash))) {
 6051:       return "error:$!";
 6052:     }
 6053:   } else {
 6054:     return "error:$!";
 6055:   }
 6056:   return %returnhash;
 6057: }
 6058: 
 6059: # ----------------------------------------------------------------------- Store
 6060: 
 6061: sub store {
 6062:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6063:     my $home='';
 6064: 
 6065:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6066: 
 6067:     $symb=&symbclean($symb);
 6068:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6069: 
 6070:     if (!$domain) { $domain=$env{'user.domain'}; }
 6071:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6072: 
 6073:     &devalidate($symb,$stuname,$domain);
 6074: 
 6075:     $symb=escape($symb);
 6076:     if (!$namespace) { 
 6077:        unless ($namespace=$env{'request.course.id'}) { 
 6078:           return ''; 
 6079:        } 
 6080:     }
 6081:     if (!$home) { $home=$env{'user.home'}; }
 6082: 
 6083:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6084:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6085: 
 6086:     my $namevalue='';
 6087:     foreach my $key (keys(%$storehash)) {
 6088:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6089:     }
 6090:     $namevalue=~s/\&$//;
 6091:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6092:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6093: }
 6094: 
 6095: # -------------------------------------------------------------- Critical Store
 6096: 
 6097: sub cstore {
 6098:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6099:     my $home='';
 6100: 
 6101:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6102: 
 6103:     $symb=&symbclean($symb);
 6104:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6105: 
 6106:     if (!$domain) { $domain=$env{'user.domain'}; }
 6107:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6108: 
 6109:     &devalidate($symb,$stuname,$domain);
 6110: 
 6111:     $symb=escape($symb);
 6112:     if (!$namespace) { 
 6113:        unless ($namespace=$env{'request.course.id'}) { 
 6114:           return ''; 
 6115:        } 
 6116:     }
 6117:     if (!$home) { $home=$env{'user.home'}; }
 6118: 
 6119:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6120:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6121: 
 6122:     my $namevalue='';
 6123:     foreach my $key (keys(%$storehash)) {
 6124:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6125:     }
 6126:     $namevalue=~s/\&$//;
 6127:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6128:     return critical
 6129:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6130: }
 6131: 
 6132: # --------------------------------------------------------------------- Restore
 6133: 
 6134: sub restore {
 6135:     my ($symb,$namespace,$domain,$stuname) = @_;
 6136:     my $home='';
 6137: 
 6138:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6139: 
 6140:     if (!$symb) {
 6141:         return if ($namespace eq 'courserequests');
 6142:         unless ($symb=escape(&symbread())) { return ''; }
 6143:     } else {
 6144:         unless ($namespace eq 'courserequests') {
 6145:             $symb=&escape(&symbclean($symb));
 6146:         }
 6147:     }
 6148:     if (!$namespace) { 
 6149:        unless ($namespace=$env{'request.course.id'}) { 
 6150:           return ''; 
 6151:        } 
 6152:     }
 6153:     if (!$domain) { $domain=$env{'user.domain'}; }
 6154:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6155:     if (!$home) { $home=$env{'user.home'}; }
 6156:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6157: 
 6158:     my %returnhash=();
 6159:     foreach my $line (split(/\&/,$answer)) {
 6160: 	my ($name,$value)=split(/\=/,$line);
 6161:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6162:     }
 6163:     my $version;
 6164:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6165:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6166:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6167:        }
 6168:     }
 6169:     return %returnhash;
 6170: }
 6171: 
 6172: # ---------------------------------------------------------- Course Description
 6173: #
 6174: #  
 6175: 
 6176: sub coursedescription {
 6177:     my ($courseid,$args)=@_;
 6178:     $courseid=~s/^\///;
 6179:     $courseid=~s/\_/\//g;
 6180:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6181:     my $chome=&homeserver($cnum,$cdomain);
 6182:     my $normalid=$cdomain.'_'.$cnum;
 6183:     # need to always cache even if we get errors otherwise we keep 
 6184:     # trying and trying and trying to get the course description.
 6185:     my %envhash=();
 6186:     my %returnhash=();
 6187:     
 6188:     my $expiretime=600;
 6189:     if ($env{'request.course.id'} eq $normalid) {
 6190: 	$expiretime=120;
 6191:     }
 6192: 
 6193:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6194:     if (!$args->{'freshen_cache'}
 6195: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6196: 	foreach my $key (keys(%env)) {
 6197: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6198: 	    my ($setting) = $1;
 6199: 	    $returnhash{$setting} = $env{$key};
 6200: 	}
 6201: 	return %returnhash;
 6202:     }
 6203: 
 6204:     # get the data again
 6205: 
 6206:     if (!$args->{'one_time'}) {
 6207: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6208:     }
 6209: 
 6210:     if ($chome ne 'no_host') {
 6211:        %returnhash=&dump('environment',$cdomain,$cnum);
 6212:        if (!exists($returnhash{'con_lost'})) {
 6213: 	   my $username = $env{'user.name'}; # Defult username
 6214: 	   if(defined $args->{'user'}) {
 6215: 	       $username = $args->{'user'};
 6216: 	   }
 6217:            $returnhash{'home'}= $chome;
 6218: 	   $returnhash{'domain'} = $cdomain;
 6219: 	   $returnhash{'num'} = $cnum;
 6220:            if (!defined($returnhash{'type'})) {
 6221:                $returnhash{'type'} = 'Course';
 6222:            }
 6223:            while (my ($name,$value) = each %returnhash) {
 6224:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6225:            }
 6226:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6227:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6228: 	       $username.'_'.$cdomain.'_'.$cnum;
 6229:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6230:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6231:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6232:        }
 6233:     }
 6234:     if (!$args->{'one_time'}) {
 6235: 	&appenv(\%envhash);
 6236:     }
 6237:     return %returnhash;
 6238: }
 6239: 
 6240: sub update_released_required {
 6241:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6242:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6243:         $cid = $env{'request.course.id'};
 6244:         $cdom = $env{'course.'.$cid.'.domain'};
 6245:         $cnum = $env{'course.'.$cid.'.num'};
 6246:         $chome = $env{'course.'.$cid.'.home'};
 6247:     }
 6248:     if ($needsrelease) {
 6249:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6250:         my $needsupdate;
 6251:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6252:             $needsupdate = 1;
 6253:         } else {
 6254:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6255:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6256:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6257:                 $needsupdate = 1;
 6258:             }
 6259:         }
 6260:         if ($needsupdate) {
 6261:             my %needshash = (
 6262:                              'internal.releaserequired' => $needsrelease,
 6263:                             );
 6264:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6265:             if ($putresult eq 'ok') {
 6266:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6267:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6268:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6269:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6270:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6271:                 }
 6272:             }
 6273:         }
 6274:     }
 6275:     return;
 6276: }
 6277: 
 6278: # -------------------------------------------------See if a user is privileged
 6279: 
 6280: sub privileged {
 6281:     my ($username,$domain,$possdomains,$possroles)=@_;
 6282:     my $now = time;
 6283:     my $roles;
 6284:     if (ref($possroles) eq 'ARRAY') {
 6285:         $roles = $possroles; 
 6286:     } else {
 6287:         $roles = ['dc','su'];
 6288:     }
 6289:     if (ref($possdomains) eq 'ARRAY') {
 6290:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6291:         foreach my $dom (@{$possdomains}) {
 6292:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6293:                 (ref($privileged{$dom}) eq 'HASH')) {
 6294:                 foreach my $role (@{$roles}) {
 6295:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6296:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6297:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6298:                             return 1 unless (($end && $end < $now) ||
 6299:                                              ($start && $start > $now));
 6300:                         }
 6301:                     }
 6302:                 }
 6303:             }
 6304:         }
 6305:     } else {
 6306:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6307:         my $now = time;
 6308: 
 6309:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6310:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6311:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6312:                 return 1 unless ($tend && $tend < $now) 
 6313:                         or ($tstart && $tstart > $now);
 6314:             }
 6315:         }
 6316:     }
 6317:     return 0;
 6318: }
 6319: 
 6320: sub privileged_by_domain {
 6321:     my ($domains,$roles) = @_;
 6322:     my %privileged = ();
 6323:     my $cachetime = 60*60*24;
 6324:     my $now = time;
 6325:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6326:         return %privileged;
 6327:     }
 6328:     foreach my $dom (@{$domains}) {
 6329:         next if (ref($privileged{$dom}) eq 'HASH');
 6330:         my $needroles;
 6331:         foreach my $role (@{$roles}) {
 6332:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6333:             if (defined($cached)) {
 6334:                 if (ref($result) eq 'HASH') {
 6335:                     $privileged{$dom}{$role} = $result;
 6336:                 }
 6337:             } else {
 6338:                 $needroles = 1;
 6339:             }
 6340:         }
 6341:         if ($needroles) {
 6342:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6343:             $privileged{$dom} = {};
 6344:             foreach my $server (keys(%dompersonnel)) {
 6345:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6346:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6347:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6348:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6349:                         next if ($end && $end < $now);
 6350:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6351:                             $dompersonnel{$server}{$item};
 6352:                     }
 6353:                 }
 6354:             }
 6355:             if (ref($privileged{$dom}) eq 'HASH') {
 6356:                 foreach my $role (@{$roles}) {
 6357:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6358:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6359:                     } else {
 6360:                         my %hash = ();
 6361:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6362:                     }
 6363:                 }
 6364:             }
 6365:         }
 6366:     }
 6367:     return %privileged;
 6368: }
 6369: 
 6370: # -------------------------------------------------------- Get user privileges
 6371: 
 6372: sub rolesinit {
 6373:     my ($domain, $username) = @_;
 6374:     my %userroles = ('user.login.time' => time);
 6375:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6376: 
 6377:     # firstaccess and timerinterval are related to timed maps/resources. 
 6378:     # also, blocking can be triggered by an activating timer
 6379:     # it's saved in the user's %env.
 6380:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6381:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6382:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6383:         %timerintchk, %timerintenv);
 6384: 
 6385:     foreach my $key (keys(%firstaccess)) {
 6386:         my ($cid, $rest) = split(/\0/, $key);
 6387:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6388:     }
 6389: 
 6390:     foreach my $key (keys(%timerinterval)) {
 6391:         my ($cid,$rest) = split(/\0/,$key);
 6392:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6393:     }
 6394: 
 6395:     my %allroles=();
 6396:     my %allgroups=();
 6397: 
 6398:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6399:         my $role = $rolesdump{$area};
 6400:         $area =~ s/\_\w\w$//;
 6401: 
 6402:         my ($trole, $tend, $tstart, $group_privs);
 6403: 
 6404:         if ($role =~ /^cr/) {
 6405:         # Custom role, defined by a user 
 6406:         # e.g., user.role.cr/msu/smith/mynewrole
 6407:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6408:                 $trole = $1;
 6409:                 ($tend, $tstart) = split('_', $2);
 6410:             } else {
 6411:                 $trole = $role;
 6412:             }
 6413:         } elsif ($role =~ m|^gr/|) {
 6414:         # Role of member in a group, defined within a course/community
 6415:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6416:             ($trole, $tend, $tstart) = split(/_/, $role);
 6417:             next if $tstart eq '-1';
 6418:             ($trole, $group_privs) = split(/\//, $trole);
 6419:             $group_privs = &unescape($group_privs);
 6420:         } else {
 6421:         # Just a normal role, defined in roles.tab
 6422:             ($trole, $tend, $tstart) = split(/_/,$role);
 6423:         }
 6424: 
 6425:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6426:                  $username);
 6427:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6428: 
 6429:         # role expired or not available yet?
 6430:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6431:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6432: 
 6433:         next if $area eq '' or $trole eq '';
 6434: 
 6435:         my $spec = "$trole.$area";
 6436:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6437: 
 6438:         if ($trole =~ /^cr\//) {
 6439:         # Custom role, defined by a user
 6440:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6441:         } elsif ($trole eq 'gr') {
 6442:         # Role of a member in a group, defined within a course/community
 6443:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6444:             next;
 6445:         } else {
 6446:         # Normal role, defined in roles.tab
 6447:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6448:         }
 6449: 
 6450:         my $cid = $tdomain.'_'.$trest;
 6451:         unless ($firstaccchk{$cid}) {
 6452:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6453:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6454:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6455:                         $coursetimerstarts{$cid}{$item}; 
 6456:                 }
 6457:             }
 6458:             $firstaccchk{$cid} = 1;
 6459:         }
 6460:         unless ($timerintchk{$cid}) {
 6461:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6462:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6463:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6464:                        $coursetimerintervals{$cid}{$item};
 6465:                 }
 6466:             }
 6467:             $timerintchk{$cid} = 1;
 6468:         }
 6469:     }
 6470: 
 6471:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6472:                                                           \%allroles, \%allgroups);
 6473:     $env{'user.adv'} = $userroles{'user.adv'};
 6474:     $env{'user.rar'} = $userroles{'user.rar'};
 6475: 
 6476:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6477: }
 6478: 
 6479: sub set_arearole {
 6480:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6481:     unless ($nolog) {
 6482: # log the associated role with the area
 6483:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6484:     }
 6485:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6486: }
 6487: 
 6488: sub custom_roleprivs {
 6489:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6490:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6491:     my $homsvr = &homeserver($rauthor,$rdomain);
 6492:     if (&hostname($homsvr) ne '') {
 6493:         my ($rdummy,$roledef)=
 6494:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6495:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6496:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6497:             if (defined($syspriv)) {
 6498:                 if ($trest =~ /^$match_community$/) {
 6499:                     $syspriv =~ s/bre\&S//; 
 6500:                 }
 6501:                 $$allroles{'cm./'}.=':'.$syspriv;
 6502:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6503:             }
 6504:             if ($tdomain ne '') {
 6505:                 if (defined($dompriv)) {
 6506:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6507:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6508:                 }
 6509:                 if (($trest ne '') && (defined($coursepriv))) {
 6510:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6511:                         my $rolename = $1;
 6512:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6513:                     }
 6514:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6515:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6516:                 }
 6517:             }
 6518:         }
 6519:     }
 6520: }
 6521: 
 6522: sub course_adhocrole_privs {
 6523:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6524:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6525:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6526:         my (%currprivs,%storeprivs);
 6527:         foreach my $item (split(/:/,$coursepriv)) {
 6528:             my ($priv,$restrict) = split(/\&/,$item);
 6529:             $currprivs{$priv} = $restrict;
 6530:         }
 6531:         my (%possadd,%possremove,%full);
 6532:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6533:             my ($priv,$restrict)=split(/\&/,$item);
 6534:             $full{$priv} = $restrict;
 6535:         }
 6536:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6537:              next if ($item eq '');
 6538:              my ($rule,$rest) = split(/=/,$item);
 6539:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6540:              foreach my $priv (split(/:/,$rest)) {
 6541:                  if ($priv ne '') {
 6542:                      if ($rule eq 'off') {
 6543:                          $possremove{$priv} = 1;
 6544:                      } else {
 6545:                          $possadd{$priv} = 1;
 6546:                      }
 6547:                  }
 6548:              }
 6549:          }
 6550:          foreach my $priv (sort(keys(%full))) {
 6551:              if (exists($currprivs{$priv})) {
 6552:                  unless (exists($possremove{$priv})) {
 6553:                      $storeprivs{$priv} = $currprivs{$priv};
 6554:                  }
 6555:              } elsif (exists($possadd{$priv})) {
 6556:                  $storeprivs{$priv} = $full{$priv};
 6557:              }
 6558:          }
 6559:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6560:      }
 6561:      return $coursepriv;
 6562: }
 6563: 
 6564: sub group_roleprivs {
 6565:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6566:     my $access = 1;
 6567:     my $now = time;
 6568:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6569:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6570:     if ($access) {
 6571:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6572:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6573:     }
 6574: }
 6575: 
 6576: sub standard_roleprivs {
 6577:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6578:     if (defined($pr{$trole.':s'})) {
 6579:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6580:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6581:     }
 6582:     if ($tdomain ne '') {
 6583:         if (defined($pr{$trole.':d'})) {
 6584:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6585:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6586:         }
 6587:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6588:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6589:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6590:         }
 6591:     }
 6592: }
 6593: 
 6594: sub set_userprivs {
 6595:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6596:     my $author=0;
 6597:     my $adv=0;
 6598:     my $rar=0;
 6599:     my %grouproles = ();
 6600:     if (keys(%{$allgroups}) > 0) {
 6601:         my @groupkeys; 
 6602:         foreach my $role (keys(%{$allroles})) {
 6603:             push(@groupkeys,$role);
 6604:         }
 6605:         if (ref($groups_roles) eq 'HASH') {
 6606:             foreach my $key (keys(%{$groups_roles})) {
 6607:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6608:                     push(@groupkeys,$key);
 6609:                 }
 6610:             }
 6611:         }
 6612:         if (@groupkeys > 0) {
 6613:             foreach my $role (@groupkeys) {
 6614:                 my ($trole,$area,$sec,$extendedarea);
 6615:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6616:                     $trole = $1;
 6617:                     $area = $2;
 6618:                     $sec = $3;
 6619:                     $extendedarea = $area.$sec;
 6620:                     if (exists($$allgroups{$area})) {
 6621:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6622:                             my $spec = $trole.'.'.$extendedarea;
 6623:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6624:                                                 $$allgroups{$area}{$group};
 6625:                         }
 6626:                     }
 6627:                 }
 6628:             }
 6629:         }
 6630:     }
 6631:     foreach my $group (keys(%grouproles)) {
 6632:         $$allroles{$group} = $grouproles{$group};
 6633:     }
 6634:     foreach my $role (keys(%{$allroles})) {
 6635:         my %thesepriv;
 6636:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6637:         foreach my $item (split(/:/,$$allroles{$role})) {
 6638:             if ($item ne '') {
 6639:                 my ($privilege,$restrictions)=split(/&/,$item);
 6640:                 if ($restrictions eq '') {
 6641:                     $thesepriv{$privilege}='F';
 6642:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6643:                     $thesepriv{$privilege}.=$restrictions;
 6644:                 }
 6645:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6646:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6647:             }
 6648:         }
 6649:         my $thesestr='';
 6650:         foreach my $priv (sort(keys(%thesepriv))) {
 6651: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6652: 	}
 6653:         $userroles->{'user.priv.'.$role} = $thesestr;
 6654:     }
 6655:     return ($author,$adv,$rar);
 6656: }
 6657: 
 6658: sub role_status {
 6659:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6660:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6661:         my ($one,$two) = split(m{\./},$rolekey,2);
 6662:         (undef,undef,$$role) = split(/\./,$one,3);
 6663:         unless (!defined($$role) || $$role eq '') {
 6664:             $$where = '/'.$two;
 6665:             $$trolecode=$$role.'.'.$$where;
 6666:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6667:             $$tstatus='is';
 6668:             if ($$tstart && $$tstart>$update) {
 6669:                 $$tstatus='future';
 6670:                 if ($$tstart<$now) {
 6671:                     if ($$tstart && $$tstart>$refresh) {
 6672:                         if (($$where ne '') && ($$role ne '')) {
 6673:                             my (%allroles,%allgroups,$group_privs,
 6674:                                 %groups_roles,@rolecodes);
 6675:                             my %userroles = (
 6676:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6677:                             );
 6678:                             @rolecodes = ('cm'); 
 6679:                             my $spec=$$role.'.'.$$where;
 6680:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6681:                             if ($$role =~ /^cr\//) {
 6682:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6683:                                 push(@rolecodes,'cr');
 6684:                             } elsif ($$role eq 'gr') {
 6685:                                 push(@rolecodes,$$role);
 6686:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6687:                                                     $env{'user.name'});
 6688:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6689:                                 (undef,my $group_privs) = split(/\//,$trole);
 6690:                                 $group_privs = &unescape($group_privs);
 6691:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6692:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6693:                                 &get_groups_roles($tdomain,$trest,
 6694:                                                   \%course_roles,\@rolecodes,
 6695:                                                   \%groups_roles);
 6696:                             } else {
 6697:                                 push(@rolecodes,$$role);
 6698:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6699:                             }
 6700:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6701:                                                                    \%groups_roles);
 6702:                             &appenv(\%userroles,\@rolecodes);
 6703:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6704:                         }
 6705:                     }
 6706:                     $$tstatus = 'is';
 6707:                 }
 6708:             }
 6709:             if ($$tend) {
 6710:                 if ($$tend<$update) {
 6711:                     $$tstatus='expired';
 6712:                 } elsif ($$tend<$now) {
 6713:                     $$tstatus='will_not';
 6714:                 }
 6715:             }
 6716:         }
 6717:     }
 6718: }
 6719: 
 6720: sub get_groups_roles {
 6721:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6722:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6723:                   (ref($rolecodes) eq 'ARRAY') && 
 6724:                   (ref($groups_roles) eq 'HASH')); 
 6725:     if (keys(%{$cdom_courseroles}) > 0) {
 6726:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6727:         if ($cdom ne '' && $cnum ne '') {
 6728:             foreach my $key (keys(%{$cdom_courseroles})) {
 6729:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6730:                     my $crsrole = $1;
 6731:                     my $crssec = $2;
 6732:                     if ($crsrole =~ /^cr/) {
 6733:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6734:                             push(@{$rolecodes},'cr');
 6735:                         }
 6736:                     } else {
 6737:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6738:                             push(@{$rolecodes},$crsrole);
 6739:                         }
 6740:                     }
 6741:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6742:                     if ($crssec ne '') {
 6743:                         $rolekey .= "/$crssec";
 6744:                     }
 6745:                     $rolekey .= './';
 6746:                     $groups_roles->{$rolekey} = $rolecodes;
 6747:                 }
 6748:             }
 6749:         }
 6750:     }
 6751:     return;
 6752: }
 6753: 
 6754: sub delete_env_groupprivs {
 6755:     my ($where,$courseroles,$possroles) = @_;
 6756:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6757:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6758:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6759:         %{$courseroles->{$udom}} =
 6760:             &get_my_roles('','','userroles',['active'],
 6761:                           $possroles,[$udom],1);
 6762:     }
 6763:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6764:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6765:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6766:             my $area = '/'.$cdom.'/'.$cnum;
 6767:             my $privkey = "user.priv.$crsrole.$area";
 6768:             if ($crssec ne '') {
 6769:                 $privkey .= '/'.$crssec;
 6770:             }
 6771:             $privkey .= ".$area/$group";
 6772:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6773:         }
 6774:     }
 6775:     return;
 6776: }
 6777: 
 6778: sub check_adhoc_privs {
 6779:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6780:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6781:     if ($sec) {
 6782:         $cckey .= '/'.$sec;
 6783:     } 
 6784:     my $setprivs;
 6785:     if ($env{$cckey}) {
 6786:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6787:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6788:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6789:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6790:             $setprivs = 1;
 6791:         }
 6792:     } else {
 6793:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6794:         $setprivs = 1;
 6795:     }
 6796:     return $setprivs;
 6797: }
 6798: 
 6799: sub set_adhoc_privileges {
 6800: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6801:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6802:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6803:     if ($sec ne '') {
 6804:         $area .= '/'.$sec;
 6805:     }
 6806:     my $spec = $role.'.'.$area;
 6807:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6808:                                   $env{'user.name'},1);
 6809:     my %rolehash = ();
 6810:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6811:         my $rolename = $1;
 6812:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6813:         my %domdef = &get_domain_defaults($dcdom);
 6814:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6815:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6816:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6817:             }
 6818:         }
 6819:     } else {
 6820:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6821:     }
 6822:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6823:     &appenv(\%userroles,[$role,'cm']);
 6824:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6825:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6826:             ($caller eq 'tiny')) {
 6827:         &appenv( {'request.role'        => $spec,
 6828:                   'request.role.domain' => $dcdom,
 6829:                   'request.course.sec'  => $sec,
 6830:                  }
 6831:                );
 6832:         my $tadv=0;
 6833:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6834:         &appenv({'request.role.adv'    => $tadv});
 6835:     }
 6836: }
 6837: 
 6838: # --------------------------------------------------------------- get interface
 6839: 
 6840: sub get {
 6841:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6842:    my $items='';
 6843:    foreach my $item (@$storearr) {
 6844:        $items.=&escape($item).'&';
 6845:    }
 6846:    $items=~s/\&$//;
 6847:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6848:    if (!$uname) { $uname=$env{'user.name'}; }
 6849:    my $uhome=&homeserver($uname,$udomain);
 6850: 
 6851:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6852:    my @pairs=split(/\&/,$rep);
 6853:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6854:      return @pairs;
 6855:    }
 6856:    my %returnhash=();
 6857:    my $i=0;
 6858:    foreach my $item (@$storearr) {
 6859:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6860:       $i++;
 6861:    }
 6862:    return %returnhash;
 6863: }
 6864: 
 6865: # --------------------------------------------------------------- del interface
 6866: 
 6867: sub del {
 6868:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6869:    my $items='';
 6870:    foreach my $item (@$storearr) {
 6871:        $items.=&escape($item).'&';
 6872:    }
 6873: 
 6874:    $items=~s/\&$//;
 6875:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6876:    if (!$uname) { $uname=$env{'user.name'}; }
 6877:    my $uhome=&homeserver($uname,$udomain);
 6878:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6879: }
 6880: 
 6881: # -------------------------------------------------------------- dump interface
 6882: 
 6883: sub unserialize {
 6884:     my ($rep, $escapedkeys) = @_;
 6885: 
 6886:     return {} if $rep =~ /^error/;
 6887: 
 6888:     my %returnhash=();
 6889: 	foreach my $item (split(/\&/,$rep)) {
 6890: 	    my ($key, $value) = split(/=/, $item, 2);
 6891: 	    $key = unescape($key) unless $escapedkeys;
 6892: 	    next if $key =~ /^error: 2 /;
 6893: 	    $returnhash{$key} = &thaw_unescape($value);
 6894: 	}
 6895:     #return %returnhash;
 6896:     return \%returnhash;
 6897: }        
 6898: 
 6899: # see Lond::dump_with_regexp
 6900: # if $escapedkeys hash keys won't get unescaped.
 6901: sub dump {
 6902:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6903:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6904:     if (!$uname) { $uname=$env{'user.name'}; }
 6905:     my $uhome=&homeserver($uname,$udomain);
 6906: 
 6907:     if ($regexp) {
 6908:         $regexp=&escape($regexp);
 6909:     } else {
 6910:         $regexp='.';
 6911:     }
 6912:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6913:         # user is hosted on this machine
 6914:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6915:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6916:         return %{unserialize($reply, $escapedkeys)};
 6917:     }
 6918:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6919:     my @pairs=split(/\&/,$rep);
 6920:     my %returnhash=();
 6921:     if (!($rep =~ /^error/ )) {
 6922: 	foreach my $item (@pairs) {
 6923: 	    my ($key,$value)=split(/=/,$item,2);
 6924:         $key = unescape($key) unless $escapedkeys;
 6925:         #$key = &unescape($key);
 6926: 	    next if ($key =~ /^error: 2 /);
 6927: 	    $returnhash{$key}=&thaw_unescape($value);
 6928: 	}
 6929:     }
 6930:     return %returnhash;
 6931: }
 6932: 
 6933: 
 6934: # --------------------------------------------------------- dumpstore interface
 6935: 
 6936: sub dumpstore {
 6937:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6938:    # same as dump but keys must be escaped. They may contain colon separated
 6939:    # lists of values that may themself contain colons (e.g. symbs).
 6940:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6941: }
 6942: 
 6943: # -------------------------------------------------------------- keys interface
 6944: 
 6945: sub getkeys {
 6946:    my ($namespace,$udomain,$uname)=@_;
 6947:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6948:    if (!$uname) { $uname=$env{'user.name'}; }
 6949:    my $uhome=&homeserver($uname,$udomain);
 6950:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6951:    my @keyarray=();
 6952:    foreach my $key (split(/\&/,$rep)) {
 6953:       next if ($key =~ /^error: 2 /);
 6954:       push(@keyarray,&unescape($key));
 6955:    }
 6956:    return @keyarray;
 6957: }
 6958: 
 6959: # --------------------------------------------------------------- currentdump
 6960: sub currentdump {
 6961:    my ($courseid,$sdom,$sname)=@_;
 6962:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6963:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6964:    $sname    = $env{'user.name'}         if (! defined($sname));
 6965:    my $uhome = &homeserver($sname,$sdom);
 6966:    my $rep;
 6967: 
 6968:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6969:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6970:                    $courseid)));
 6971:    } else {
 6972:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6973:    }
 6974: 
 6975:    return if ($rep =~ /^(error:|no_such_host)/);
 6976:    #
 6977:    my %returnhash=();
 6978:    #
 6979:    if ($rep eq 'unknown_cmd') {
 6980:        # an old lond will not know currentdump
 6981:        # Do a dump and make it look like a currentdump
 6982:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6983:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6984:        my %hash = @tmp;
 6985:        @tmp=();
 6986:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6987:    } else {
 6988:        my @pairs=split(/\&/,$rep);
 6989:        foreach my $pair (@pairs) {
 6990:            my ($key,$value)=split(/=/,$pair,2);
 6991:            my ($symb,$param) = split(/:/,$key);
 6992:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6993:                                                         &thaw_unescape($value);
 6994:        }
 6995:    }
 6996:    return %returnhash;
 6997: }
 6998: 
 6999: sub convert_dump_to_currentdump{
 7000:     my %hash = %{shift()};
 7001:     my %returnhash;
 7002:     # Code ripped from lond, essentially.  The only difference
 7003:     # here is the unescaping done by lonnet::dump().  Conceivably
 7004:     # we might run in to problems with parameter names =~ /^v\./
 7005:     while (my ($key,$value) = each(%hash)) {
 7006:         my ($v,$symb,$param) = split(/:/,$key);
 7007: 	$symb  = &unescape($symb);
 7008: 	$param = &unescape($param);
 7009:         next if ($v eq 'version' || $symb eq 'keys');
 7010:         next if (exists($returnhash{$symb}) &&
 7011:                  exists($returnhash{$symb}->{$param}) &&
 7012:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7013:         $returnhash{$symb}->{$param}=$value;
 7014:         $returnhash{$symb}->{'v.'.$param}=$v;
 7015:     }
 7016:     #
 7017:     # Remove all of the keys in the hashes which keep track of
 7018:     # the version of the parameter.
 7019:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7020:         # use a foreach because we are going to delete from the hash.
 7021:         foreach my $key (keys(%$param_hash)) {
 7022:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7023:         }
 7024:     }
 7025:     return \%returnhash;
 7026: }
 7027: 
 7028: # ------------------------------------------------------ critical inc interface
 7029: 
 7030: sub cinc {
 7031:     return &inc(@_,'critical');
 7032: }
 7033: 
 7034: # --------------------------------------------------------------- inc interface
 7035: 
 7036: sub inc {
 7037:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7038:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7039:     if (!$uname) { $uname=$env{'user.name'}; }
 7040:     my $uhome=&homeserver($uname,$udomain);
 7041:     my $items='';
 7042:     if (! ref($store)) {
 7043:         # got a single value, so use that instead
 7044:         $items = &escape($store).'=&';
 7045:     } elsif (ref($store) eq 'SCALAR') {
 7046:         $items = &escape($$store).'=&';        
 7047:     } elsif (ref($store) eq 'ARRAY') {
 7048:         $items = join('=&',map {&escape($_);} @{$store});
 7049:     } elsif (ref($store) eq 'HASH') {
 7050:         while (my($key,$value) = each(%{$store})) {
 7051:             $items.= &escape($key).'='.&escape($value).'&';
 7052:         }
 7053:     }
 7054:     $items=~s/\&$//;
 7055:     if ($critical) {
 7056: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7057:     } else {
 7058: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7059:     }
 7060: }
 7061: 
 7062: # --------------------------------------------------------------- put interface
 7063: 
 7064: sub put {
 7065:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7067:    if (!$uname) { $uname=$env{'user.name'}; }
 7068:    my $uhome=&homeserver($uname,$udomain);
 7069:    my $items='';
 7070:    foreach my $item (keys(%$storehash)) {
 7071:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7072:    }
 7073:    $items=~s/\&$//;
 7074:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7075: }
 7076: 
 7077: # ------------------------------------------------------------ newput interface
 7078: 
 7079: sub newput {
 7080:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7081:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7082:    if (!$uname) { $uname=$env{'user.name'}; }
 7083:    my $uhome=&homeserver($uname,$udomain);
 7084:    my $items='';
 7085:    foreach my $key (keys(%$storehash)) {
 7086:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7087:    }
 7088:    $items=~s/\&$//;
 7089:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7090: }
 7091: 
 7092: # ---------------------------------------------------------  putstore interface
 7093: 
 7094: sub putstore {
 7095:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7096:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7097:    if (!$uname) { $uname=$env{'user.name'}; }
 7098:    my $uhome=&homeserver($uname,$udomain);
 7099:    my $items='';
 7100:    foreach my $key (keys(%$storehash)) {
 7101:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7102:    }
 7103:    $items=~s/\&$//;
 7104:    my $esc_symb=&escape($symb);
 7105:    my $esc_v=&escape($version);
 7106:    my $reply =
 7107:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7108: 	      $uhome);
 7109:    if (($tolog) && ($reply eq 'ok')) {
 7110:        my $namevalue='';
 7111:        foreach my $key (keys(%{$storehash})) {
 7112:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7113:        }
 7114:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7115:                      '&host='.&escape($perlvar{'lonHostID'}).
 7116:                      '&version='.$esc_v.
 7117:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7118:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7119:    }
 7120:    if ($reply eq 'unknown_cmd') {
 7121:        # gfall back to way things use to be done
 7122:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7123: 			    $uname);
 7124:    }
 7125:    return $reply;
 7126: }
 7127: 
 7128: sub old_putstore {
 7129:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7130:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7131:     if (!$uname) { $uname=$env{'user.name'}; }
 7132:     my $uhome=&homeserver($uname,$udomain);
 7133:     my %newstorehash;
 7134:     foreach my $item (keys(%$storehash)) {
 7135: 	my $key = $version.':'.&escape($symb).':'.$item;
 7136: 	$newstorehash{$key} = $storehash->{$item};
 7137:     }
 7138:     my $items='';
 7139:     my %allitems = ();
 7140:     foreach my $item (keys(%newstorehash)) {
 7141: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7142: 	    my $key = $1.':keys:'.$2;
 7143: 	    $allitems{$key} .= $3.':';
 7144: 	}
 7145: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7146:     }
 7147:     foreach my $item (keys(%allitems)) {
 7148: 	$allitems{$item} =~ s/\:$//;
 7149: 	$items.= $item.'='.$allitems{$item}.'&';
 7150:     }
 7151:     $items=~s/\&$//;
 7152:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7153: }
 7154: 
 7155: # ------------------------------------------------------ critical put interface
 7156: 
 7157: sub cput {
 7158:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7160:    if (!$uname) { $uname=$env{'user.name'}; }
 7161:    my $uhome=&homeserver($uname,$udomain);
 7162:    my $items='';
 7163:    foreach my $item (keys(%$storehash)) {
 7164:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7165:    }
 7166:    $items=~s/\&$//;
 7167:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7168: }
 7169: 
 7170: # -------------------------------------------------------------- eget interface
 7171: 
 7172: sub eget {
 7173:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7174:    my $items='';
 7175:    foreach my $item (@$storearr) {
 7176:        $items.=&escape($item).'&';
 7177:    }
 7178:    $items=~s/\&$//;
 7179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7180:    if (!$uname) { $uname=$env{'user.name'}; }
 7181:    my $uhome=&homeserver($uname,$udomain);
 7182:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7183:    my @pairs=split(/\&/,$rep);
 7184:    my %returnhash=();
 7185:    my $i=0;
 7186:    foreach my $item (@$storearr) {
 7187:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7188:       $i++;
 7189:    }
 7190:    return %returnhash;
 7191: }
 7192: 
 7193: # ------------------------------------------------------------ tmpput interface
 7194: sub tmpput {
 7195:     my ($storehash,$server,$context)=@_;
 7196:     my $items='';
 7197:     foreach my $item (keys(%$storehash)) {
 7198: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7199:     }
 7200:     $items=~s/\&$//;
 7201:     if (defined($context)) {
 7202:         $items .= ':'.&escape($context);
 7203:     }
 7204:     return &reply("tmpput:$items",$server);
 7205: }
 7206: 
 7207: # ------------------------------------------------------------ tmpget interface
 7208: sub tmpget {
 7209:     my ($token,$server)=@_;
 7210:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7211:     my $rep=&reply("tmpget:$token",$server);
 7212:     my %returnhash;
 7213:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7214:         return %returnhash;
 7215:     }
 7216:     foreach my $item (split(/\&/,$rep)) {
 7217: 	my ($key,$value)=split(/=/,$item);
 7218: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7219:     }
 7220:     return %returnhash;
 7221: }
 7222: 
 7223: # ------------------------------------------------------------ tmpdel interface
 7224: sub tmpdel {
 7225:     my ($token,$server)=@_;
 7226:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7227:     return &reply("tmpdel:$token",$server);
 7228: }
 7229: 
 7230: # ------------------------------------------------------------ get_timebased_id 
 7231: 
 7232: sub get_timebased_id {
 7233:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7234:         $maxtries) = @_;
 7235:     my ($newid,$error,$dellock);
 7236:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7237:         return ('','ok','invalid call to get suffix');
 7238:     }
 7239: 
 7240: # set defaults for any optional args for which values were not supplied
 7241:     if ($who eq '') {
 7242:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7243:     }
 7244:     if (!$locktries) {
 7245:         $locktries = 3;
 7246:     }
 7247:     if (!$maxtries) {
 7248:         $maxtries = 10;
 7249:     }
 7250:     
 7251:     if (($cdom eq '') || ($cnum eq '')) {
 7252:         if ($env{'request.course.id'}) {
 7253:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7254:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7255:         }
 7256:         if (($cdom eq '') || ($cnum eq '')) {
 7257:             return ('','ok','call to get suffix not in course context');
 7258:         }
 7259:     }
 7260: 
 7261: # construct locking item
 7262:     my $lockhash = {
 7263:                       $prefix."\0".'locked_'.$keyid => $who,
 7264:                    };
 7265:     my $tries = 0;
 7266: 
 7267: # attempt to get lock on nohist_$namespace file
 7268:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7269:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7270:         $tries ++;
 7271:         sleep 1;
 7272:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7273:     }
 7274: 
 7275: # attempt to get unique identifier, based on current timestamp
 7276:     if ($gotlock eq 'ok') {
 7277:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7278:         my $id = time;
 7279:         $newid = $id;
 7280:         if ($idtype eq 'addcode') {
 7281:             $newid .= &sixnum_code();
 7282:         }
 7283:         my $idtries = 0;
 7284:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7285:             if ($idtype eq 'concat') {
 7286:                 $newid = $id.$idtries;
 7287:             } elsif ($idtype eq 'addcode') {
 7288:                 $newid = $newid.&sixnum_code();
 7289:             } else {
 7290:                 $newid ++;
 7291:             }
 7292:             $idtries ++;
 7293:         }
 7294:         if (!exists($inuse{$prefix."\0".$newid})) {
 7295:             my %new_item =  (
 7296:                               $prefix."\0".$newid => $who,
 7297:                             );
 7298:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7299:                                                  $cdom,$cnum);
 7300:             if ($putresult ne 'ok') {
 7301:                 undef($newid);
 7302:                 $error = 'error saving new item: '.$putresult;
 7303:             }
 7304:         } else {
 7305:              undef($newid);
 7306:              $error = ('error: no unique suffix available for the new item ');
 7307:         }
 7308: #  remove lock
 7309:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7310:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7311:     } else {
 7312:         $error = "error: could not obtain lockfile\n";
 7313:         $dellock = 'ok';
 7314:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7315:             $dellock = 'nolock';
 7316:         }
 7317:     }
 7318:     return ($newid,$dellock,$error);
 7319: }
 7320: 
 7321: sub sixnum_code {
 7322:     my $code;
 7323:     for (0..6) {
 7324:         $code .= int( rand(9) );
 7325:     }
 7326:     return $code;
 7327: }
 7328: 
 7329: # -------------------------------------------------- portfolio access checking
 7330: 
 7331: sub portfolio_access {
 7332:     my ($requrl,$clientip) = @_;
 7333:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7334:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7335:     if ($result) {
 7336:         my %setters;
 7337:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7338:             my ($startblock,$endblock) =
 7339:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7340:             if ($startblock && $endblock) {
 7341:                 return 'B';
 7342:             }
 7343:         } else {
 7344:             my ($startblock,$endblock) =
 7345:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7346:             if ($startblock && $endblock) {
 7347:                 return 'B';
 7348:             }
 7349:         }
 7350:     }
 7351:     if ($result eq 'ok') {
 7352:        return 'F';
 7353:     } elsif ($result =~ /^[^:]+:guest_/) {
 7354:        return 'A';
 7355:     }
 7356:     return '';
 7357: }
 7358: 
 7359: sub get_portfolio_access {
 7360:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7361: 
 7362:     if (!ref($access_hash)) {
 7363: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7364: 	my %access_controls = &get_access_controls($current_perms,$group,
 7365: 						   $file_name);
 7366: 	$access_hash = $access_controls{$file_name};
 7367:     }
 7368: 
 7369:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7370:     my $now = time;
 7371:     if (ref($access_hash) eq 'HASH') {
 7372:         foreach my $key (keys(%{$access_hash})) {
 7373:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7374:             if ($start > $now) {
 7375:                 next;
 7376:             }
 7377:             if ($end && $end<$now) {
 7378:                 next;
 7379:             }
 7380:             if ($scope eq 'public') {
 7381:                 $public = $key;
 7382:                 last;
 7383:             } elsif ($scope eq 'guest') {
 7384:                 $guest = $key;
 7385:             } elsif ($scope eq 'domains') {
 7386:                 push(@domains,$key);
 7387:             } elsif ($scope eq 'users') {
 7388:                 push(@users,$key);
 7389:             } elsif ($scope eq 'course') {
 7390:                 push(@courses,$key);
 7391:             } elsif ($scope eq 'group') {
 7392:                 push(@groups,$key);
 7393:             } elsif ($scope eq 'ip') {
 7394:                 push(@ips,$key);
 7395:             }
 7396:         }
 7397:         if ($public) {
 7398:             return 'ok';
 7399:         } elsif (@ips > 0) {
 7400:             my $allowed;
 7401:             foreach my $ipkey (@ips) {
 7402:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7403:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7404:                         $allowed = 1;
 7405:                         last; 
 7406:                     }
 7407:                 }
 7408:             }
 7409:             if ($allowed) {
 7410:                 return 'ok';
 7411:             }
 7412:         }
 7413:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7414:             if ($guest) {
 7415:                 return $guest;
 7416:             }
 7417:         } else {
 7418:             if (@domains > 0) {
 7419:                 foreach my $domkey (@domains) {
 7420:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7421:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7422:                             return 'ok';
 7423:                         }
 7424:                     }
 7425:                 }
 7426:             }
 7427:             if (@users > 0) {
 7428:                 foreach my $userkey (@users) {
 7429:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7430:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7431:                             if (ref($item) eq 'HASH') {
 7432:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7433:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7434:                                     return 'ok';
 7435:                                 }
 7436:                             }
 7437:                         }
 7438:                     } 
 7439:                 }
 7440:             }
 7441:             my %roleshash;
 7442:             my @courses_and_groups = @courses;
 7443:             push(@courses_and_groups,@groups); 
 7444:             if (@courses_and_groups > 0) {
 7445:                 my (%allgroups,%allroles); 
 7446:                 my ($start,$end,$role,$sec,$group);
 7447:                 foreach my $envkey (%env) {
 7448:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7449:                         my $cid = $2.'_'.$3; 
 7450:                         if ($1 eq 'gr') {
 7451:                             $group = $4;
 7452:                             $allgroups{$cid}{$group} = $env{$envkey};
 7453:                         } else {
 7454:                             if ($4 eq '') {
 7455:                                 $sec = 'none';
 7456:                             } else {
 7457:                                 $sec = $4;
 7458:                             }
 7459:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7460:                         }
 7461:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7462:                         my $cid = $2.'_'.$3;
 7463:                         if ($4 eq '') {
 7464:                             $sec = 'none';
 7465:                         } else {
 7466:                             $sec = $4;
 7467:                         }
 7468:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7469:                     }
 7470:                 }
 7471:                 if (keys(%allroles) == 0) {
 7472:                     return;
 7473:                 }
 7474:                 foreach my $key (@courses_and_groups) {
 7475:                     my %content = %{$$access_hash{$key}};
 7476:                     my $cnum = $content{'number'};
 7477:                     my $cdom = $content{'domain'};
 7478:                     my $cid = $cdom.'_'.$cnum;
 7479:                     if (!exists($allroles{$cid})) {
 7480:                         next;
 7481:                     }    
 7482:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7483:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7484:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7485:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7486:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7487:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7488:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7489:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7490:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7491:                                         if (grep/^all$/,@sections) {
 7492:                                             return 'ok';
 7493:                                         } else {
 7494:                                             if (grep/^$sec$/,@sections) {
 7495:                                                 return 'ok';
 7496:                                             }
 7497:                                         }
 7498:                                     }
 7499:                                 }
 7500:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7501:                                     if (grep/^none$/,@groups) {
 7502:                                         return 'ok';
 7503:                                     }
 7504:                                 } else {
 7505:                                     if (grep/^all$/,@groups) {
 7506:                                         return 'ok';
 7507:                                     } 
 7508:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7509:                                         if (grep/^$group$/,@groups) {
 7510:                                             return 'ok';
 7511:                                         }
 7512:                                     }
 7513:                                 } 
 7514:                             }
 7515:                         }
 7516:                     }
 7517:                 }
 7518:             }
 7519:             if ($guest) {
 7520:                 return $guest;
 7521:             }
 7522:         }
 7523:     }
 7524:     return;
 7525: }
 7526: 
 7527: sub course_group_datechecker {
 7528:     my ($dates,$now,$status) = @_;
 7529:     my ($start,$end) = split(/\./,$dates);
 7530:     if (!$start && !$end) {
 7531:         return 'ok';
 7532:     }
 7533:     if (grep/^active$/,@{$status}) {
 7534:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7535:             return 'ok';
 7536:         }
 7537:     }
 7538:     if (grep/^previous$/,@{$status}) {
 7539:         if ($end > $now ) {
 7540:             return 'ok';
 7541:         }
 7542:     }
 7543:     if (grep/^future$/,@{$status}) {
 7544:         if ($start > $now) {
 7545:             return 'ok';
 7546:         }
 7547:     }
 7548:     return; 
 7549: }
 7550: 
 7551: sub parse_portfolio_url {
 7552:     my ($url) = @_;
 7553: 
 7554:     my ($type,$udom,$unum,$group,$file_name);
 7555:     
 7556:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7557: 	$type = 1;
 7558:         $udom = $1;
 7559:         $unum = $2;
 7560:         $file_name = $3;
 7561:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7562: 	$type = 2;
 7563:         $udom = $1;
 7564:         $unum = $2;
 7565:         $group = $3;
 7566:         $file_name = $3.'/'.$4;
 7567:     }
 7568:     if (wantarray) {
 7569: 	return ($type,$udom,$unum,$file_name,$group);
 7570:     }
 7571:     return $type;
 7572: }
 7573: 
 7574: sub is_portfolio_url {
 7575:     my ($url) = @_;
 7576:     return scalar(&parse_portfolio_url($url));
 7577: }
 7578: 
 7579: sub is_portfolio_file {
 7580:     my ($file) = @_;
 7581:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7582:         return 1;
 7583:     }
 7584:     return;
 7585: }
 7586: 
 7587: sub usertools_access {
 7588:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7589:     my ($access,%tools);
 7590:     if ($context eq '') {
 7591:         $context = 'tools';
 7592:     }
 7593:     if ($context eq 'requestcourses') {
 7594:         %tools = (
 7595:                       official   => 1,
 7596:                       unofficial => 1,
 7597:                       community  => 1,
 7598:                       textbook   => 1,
 7599:                       placement  => 1,
 7600:                       lti        => 1,
 7601:                  );
 7602:     } elsif ($context eq 'requestauthor') {
 7603:         %tools = (
 7604:                       requestauthor => 1,
 7605:                  );
 7606:     } else {
 7607:         %tools = (
 7608:                       aboutme   => 1,
 7609:                       blog      => 1,
 7610:                       webdav    => 1,
 7611:                       portfolio => 1,
 7612:                  );
 7613:     }
 7614:     return if (!defined($tools{$tool}));
 7615: 
 7616:     if (($udom eq '') || ($uname eq '')) {
 7617:         $udom = $env{'user.domain'};
 7618:         $uname = $env{'user.name'};
 7619:     }
 7620: 
 7621:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7622:         if ($action ne 'reload') {
 7623:             if ($context eq 'requestcourses') {
 7624:                 return $env{'environment.canrequest.'.$tool};
 7625:             } elsif ($context eq 'requestauthor') {
 7626:                 return $env{'environment.canrequest.author'};
 7627:             } else {
 7628:                 return $env{'environment.availabletools.'.$tool};
 7629:             }
 7630:         }
 7631:     }
 7632: 
 7633:     my ($toolstatus,$inststatus,$envkey);
 7634:     if ($context eq 'requestauthor') {
 7635:         $envkey = $context; 
 7636:     } else {
 7637:         $envkey = $context.'.'.$tool;
 7638:     }
 7639: 
 7640:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7641:          ($action ne 'reload')) {
 7642:         $toolstatus = $env{'environment.'.$envkey};
 7643:         $inststatus = $env{'environment.inststatus'};
 7644:     } else {
 7645:         if (ref($userenvref) eq 'HASH') {
 7646:             $toolstatus = $userenvref->{$envkey};
 7647:             $inststatus = $userenvref->{'inststatus'};
 7648:         } else {
 7649:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7650:             $toolstatus = $userenv{$envkey};
 7651:             $inststatus = $userenv{'inststatus'};
 7652:         }
 7653:     }
 7654: 
 7655:     if ($toolstatus ne '') {
 7656:         if ($toolstatus) {
 7657:             $access = 1;
 7658:         } else {
 7659:             $access = 0;
 7660:         }
 7661:         return $access;
 7662:     }
 7663: 
 7664:     my ($is_adv,%domdef);
 7665:     if (ref($is_advref) eq 'HASH') {
 7666:         $is_adv = $is_advref->{'is_adv'};
 7667:     } else {
 7668:         $is_adv = &is_advanced_user($udom,$uname);
 7669:     }
 7670:     if (ref($domdefref) eq 'HASH') {
 7671:         %domdef = %{$domdefref};
 7672:     } else {
 7673:         %domdef = &get_domain_defaults($udom);
 7674:     }
 7675:     if (ref($domdef{$tool}) eq 'HASH') {
 7676:         if ($is_adv) {
 7677:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7678:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7679:                     $access = 1;
 7680:                 } else {
 7681:                     $access = 0;
 7682:                 }
 7683:                 return $access;
 7684:             }
 7685:         }
 7686:         if ($inststatus ne '') {
 7687:             my ($hasaccess,$hasnoaccess);
 7688:             foreach my $affiliation (split(/:/,$inststatus)) {
 7689:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7690:                     if ($domdef{$tool}{$affiliation}) {
 7691:                         $hasaccess = 1;
 7692:                     } else {
 7693:                         $hasnoaccess = 1;
 7694:                     }
 7695:                 }
 7696:             }
 7697:             if ($hasaccess || $hasnoaccess) {
 7698:                 if ($hasaccess) {
 7699:                     $access = 1;
 7700:                 } elsif ($hasnoaccess) {
 7701:                     $access = 0; 
 7702:                 }
 7703:                 return $access;
 7704:             }
 7705:         } else {
 7706:             if ($domdef{$tool}{'default'} ne '') {
 7707:                 if ($domdef{$tool}{'default'}) {
 7708:                     $access = 1;
 7709:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7710:                     $access = 0;
 7711:                 }
 7712:                 return $access;
 7713:             }
 7714:         }
 7715:     } else {
 7716:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7717:             $access = 1;
 7718:         } else {
 7719:             $access = 0;
 7720:         }
 7721:         return $access;
 7722:     }
 7723: }
 7724: 
 7725: sub is_course_owner {
 7726:     my ($cdom,$cnum,$udom,$uname) = @_;
 7727:     if (($udom eq '') || ($uname eq '')) {
 7728:         $udom = $env{'user.domain'};
 7729:         $uname = $env{'user.name'};
 7730:     }
 7731:     unless (($udom eq '') || ($uname eq '')) {
 7732:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7733:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7734:                 return 1;
 7735:             } else {
 7736:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7737:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7738:                     return 1;
 7739:                 }
 7740:             }
 7741:         }
 7742:     }
 7743:     return;
 7744: }
 7745: 
 7746: sub is_advanced_user {
 7747:     my ($udom,$uname) = @_;
 7748:     if ($udom ne '' && $uname ne '') {
 7749:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7750:             if (wantarray) {
 7751:                 return ($env{'user.adv'},$env{'user.author'});
 7752:             } else {
 7753:                 return $env{'user.adv'};
 7754:             }
 7755:         }
 7756:     }
 7757:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7758:     my %allroles;
 7759:     my ($is_adv,$is_author);
 7760:     foreach my $role (keys(%roleshash)) {
 7761:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7762:         my $area = '/'.$tdomain.'/'.$trest;
 7763:         if ($sec ne '') {
 7764:             $area .= '/'.$sec;
 7765:         }
 7766:         if (($area ne '') && ($trole ne '')) {
 7767:             my $spec=$trole.'.'.$area;
 7768:             if ($trole =~ /^cr\//) {
 7769:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7770:             } elsif ($trole ne 'gr') {
 7771:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7772:             }
 7773:             if ($trole eq 'au') {
 7774:                 $is_author = 1;
 7775:             }
 7776:         }
 7777:     }
 7778:     foreach my $role (keys(%allroles)) {
 7779:         last if ($is_adv);
 7780:         foreach my $item (split(/:/,$allroles{$role})) {
 7781:             if ($item ne '') {
 7782:                 my ($privilege,$restrictions)=split(/&/,$item);
 7783:                 if ($privilege eq 'adv') {
 7784:                     $is_adv = 1;
 7785:                     last;
 7786:                 }
 7787:             }
 7788:         }
 7789:     }
 7790:     if (wantarray) {
 7791:         return ($is_adv,$is_author);
 7792:     }
 7793:     return $is_adv;
 7794: }
 7795: 
 7796: sub check_can_request {
 7797:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7798:     my $canreq = 0;
 7799:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7800:         $uname = $env{'user.name'};
 7801:         $udom = $env{'user.domain'};
 7802:     }
 7803:     my ($types,$typename) = &Apache::loncommon::course_types();
 7804:     my @options = ('approval','validate','autolimit');
 7805:     my $optregex = join('|',@options);
 7806:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7807:         foreach my $type (@{$types}) {
 7808:             if (&usertools_access($uname,$udom,$type,undef,
 7809:                                   'requestcourses')) {
 7810:                 $canreq ++;
 7811:                 if (ref($request_domains) eq 'HASH') {
 7812:                     push(@{$request_domains->{$type}},$udom);
 7813:                 }
 7814:                 if ($dom eq $udom) {
 7815:                     $can_request->{$type} = 1;
 7816:                 }
 7817:             }
 7818:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7819:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7820:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7821:                 if (@curr > 0) {
 7822:                     foreach my $item (@curr) {
 7823:                         if (ref($request_domains) eq 'HASH') {
 7824:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7825:                             if ($otherdom ne '') {
 7826:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7827:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7828:                                         push(@{$request_domains->{$type}},$otherdom);
 7829:                                     }
 7830:                                 } else {
 7831:                                     push(@{$request_domains->{$type}},$otherdom);
 7832:                                 }
 7833:                             }
 7834:                         }
 7835:                     }
 7836:                     unless ($dom eq $env{'user.domain'}) {
 7837:                         $canreq ++;
 7838:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7839:                             $can_request->{$type} = 1;
 7840:                         }
 7841:                     }
 7842:                 }
 7843:             }
 7844:         }
 7845:     }
 7846:     return $canreq;
 7847: }
 7848: 
 7849: # ---------------------------------------------- Custom access rule evaluation
 7850: 
 7851: sub customaccess {
 7852:     my ($priv,$uri)=@_;
 7853:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7854:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7855:     $udom = &LONCAPA::clean_domain($udom);
 7856:     $ucrs = &LONCAPA::clean_username($ucrs);
 7857:     my $access=0;
 7858:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7859: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7860: 	if ($type eq 'user') {
 7861: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7862: 		my ($tdom,$tuname)=split(m{/},$scope);
 7863: 		if ($tdom) {
 7864: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7865: 		}
 7866: 		if ($tuname) {
 7867: 		    if ($tuname ne $env{'user.name'}) { next; }
 7868: 		}
 7869: 		$access=($effect eq 'allow');
 7870: 		last;
 7871: 	    }
 7872: 	} else {
 7873: 	    if ($role) {
 7874: 		if ($role ne $urole) { next; }
 7875: 	    }
 7876: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7877: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7878: 		if ($tdom) {
 7879: 		    if ($tdom ne $udom) { next; }
 7880: 		}
 7881: 		if ($tcrs) {
 7882: 		    if ($tcrs ne $ucrs) { next; }
 7883: 		}
 7884: 		if ($tsec) {
 7885: 		    if ($tsec ne $usec) { next; }
 7886: 		}
 7887: 		$access=($effect eq 'allow');
 7888: 		last;
 7889: 	    }
 7890: 	    if ($realm eq '' && $role eq '') {
 7891: 		$access=($effect eq 'allow');
 7892: 	    }
 7893: 	}
 7894:     }
 7895:     return $access;
 7896: }
 7897: 
 7898: # ------------------------------------------------- Check for a user privilege
 7899: 
 7900: sub allowed {
 7901:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7902:     my $ver_orguri=$uri;
 7903:     $uri=&deversion($uri);
 7904:     my $orguri=$uri;
 7905:     $uri=&declutter($uri);
 7906: 
 7907:     if ($priv eq 'evb') {
 7908: # Evade communication block restrictions for specified role in a course
 7909:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7910:             return $1;
 7911:         } else {
 7912:             return;
 7913:         }
 7914:     }
 7915: 
 7916:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7917: # Free bre access to adm and meta resources
 7918:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7919: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7920: 	&& ($priv eq 'bre')) {
 7921: 	return 'F';
 7922:     }
 7923: 
 7924: # Free bre access to user's own portfolio contents
 7925:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7926:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7927: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7928:         my %setters;
 7929:         my ($startblock,$endblock) = 
 7930:             &Apache::loncommon::blockcheck(\%setters,'port');
 7931:         if ($startblock && $endblock) {
 7932:             return 'B';
 7933:         } else {
 7934:             return 'F';
 7935:         }
 7936:     }
 7937: 
 7938: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7939:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7940:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7941:         if (exists($env{'request.course.id'})) {
 7942:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7943:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7944:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7945:                 my $courseprivid=$env{'request.course.id'};
 7946:                 $courseprivid=~s/\_/\//;
 7947:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7948:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7949:                     return $1; 
 7950:                 } else {
 7951:                     if ($env{'request.course.sec'}) {
 7952:                         $courseprivid.='/'.$env{'request.course.sec'};
 7953:                     }
 7954:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7955:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7956:                         return $2;
 7957:                     }
 7958:                 }
 7959:             }
 7960:         }
 7961:     }
 7962: 
 7963: # Free bre to public access
 7964: 
 7965:     if ($priv eq 'bre') {
 7966:         my $copyright;
 7967:         unless ($uri =~ /ext\.tool/) {
 7968:             $copyright=&metadata($uri,'copyright');
 7969:         }
 7970: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7971:            return 'F'; 
 7972:         }
 7973:         if ($copyright eq 'priv') {
 7974:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7975: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7976: 		return '';
 7977:             }
 7978:         }
 7979:         if ($copyright eq 'domain') {
 7980:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7981: 	    unless (($env{'user.domain'} eq $1) ||
 7982:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7983: 		return '';
 7984:             }
 7985:         }
 7986:         if ($env{'request.role'}=~ /li\.\//) {
 7987:             # Library role, so allow browsing of resources in this domain.
 7988:             return 'F';
 7989:         }
 7990:         if ($copyright eq 'custom') {
 7991: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7992:         }
 7993:     }
 7994:     # Domain coordinator is trying to create a course
 7995:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7996:         # uri is the requested domain in this case.
 7997:         # comparison to 'request.role.domain' shows if the user has selected
 7998:         # a role of dc for the domain in question.
 7999:         return 'F' if ($uri eq $env{'request.role.domain'});
 8000:     }
 8001: 
 8002:     my $thisallowed='';
 8003:     my $statecond=0;
 8004:     my $courseprivid='';
 8005: 
 8006:     my $ownaccess;
 8007:     # Community Coordinator or Assistant Co-author browsing resource space.
 8008:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8009:         if ($uri eq '') {
 8010:             $ownaccess = 1;
 8011:         } else {
 8012:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8013:                 my $udom = $env{'user.domain'};
 8014:                 my $uname = $env{'user.name'};
 8015:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8016:                     $ownaccess = 1;
 8017:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8018:                     unless ($uri =~ m{\.\./}) {
 8019:                         $ownaccess = 1;
 8020:                     }
 8021:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8022:                     my $now = time;
 8023:                     if ($uri =~ m{^([^/]+)/?$}) {
 8024:                         my $adom = $1;
 8025:                         foreach my $key (keys(%env)) {
 8026:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8027:                                 my ($start,$end) = split('.',$env{$key});
 8028:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8029:                                     $ownaccess = 1;
 8030:                                     last;
 8031:                                 }
 8032:                             }
 8033:                         }
 8034:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8035:                         my $adom = $1;
 8036:                         my $aname = $2;
 8037:                         foreach my $role ('ca','aa') { 
 8038:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8039:                                 my ($start,$end) =
 8040:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8041:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8042:                                     $ownaccess = 1;
 8043:                                     last;
 8044:                                 }
 8045:                             }
 8046:                         }
 8047:                     }
 8048:                 }
 8049:             }
 8050:         }
 8051:     }
 8052: 
 8053: # Course
 8054: 
 8055:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8056:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8057:             $thisallowed.=$1;
 8058:         }
 8059:     }
 8060: 
 8061: # Domain
 8062: 
 8063:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8064:        =~/\Q$priv\E\&([^\:]*)/) {
 8065:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8066:             $thisallowed.=$1;
 8067:         }
 8068:     }
 8069: 
 8070: # User who is not author or co-author might still be able to edit
 8071: # resource of an author in the domain (e.g., if Domain Coordinator).
 8072:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8073:         (&allowed('mdc',$env{'request.course.id'}))) {
 8074:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8075:             $thisallowed.=$1;
 8076:         }
 8077:     }
 8078: 
 8079: # Course: uri itself is a course
 8080:     my $courseuri=$uri;
 8081:     $courseuri=~s/\_(\d)/\/$1/;
 8082:     $courseuri=~s/^([^\/])/\/$1/;
 8083: 
 8084:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8085:        =~/\Q$priv\E\&([^\:]*)/) {
 8086:         if ($priv eq 'mip') {
 8087:             my $rem = $1;
 8088:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8089:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8090:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8091:                 if ($cdom ne '') {
 8092:                     my %passwdconf = &get_passwdconf($cdom);
 8093:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8094:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8095:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8096:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8097:                                 unless (@inststatuses) {
 8098:                                     @inststatuses = ('default');
 8099:                                 }
 8100:                                 foreach my $status (@inststatuses) {
 8101:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8102:                                         $thisallowed.=$rem;
 8103:                                     }
 8104:                                 }
 8105:                             }
 8106:                         }
 8107:                     }
 8108:                 }
 8109:             }
 8110:         } else {
 8111:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8112:                 $thisallowed.=$1;
 8113:             }
 8114:         }
 8115:     }
 8116: 
 8117: # URI is an uploaded document for this course, default permissions don't matter
 8118: # not allowing 'edit' access (editupload) to uploaded course docs
 8119:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8120: 	$thisallowed='';
 8121:         my ($match)=&is_on_map($uri);
 8122:         if ($match) {
 8123:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8124:                   =~/\Q$priv\E\&([^\:]*)/) {
 8125:                 my $value = $1;
 8126:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8127:                 if ($deeplinkblock) {
 8128:                     $thisallowed='D';
 8129:                 } elsif ($noblockcheck) {
 8130:                     $thisallowed.=$value;
 8131:                 } else {
 8132:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8133:                     if (@blockers > 0) {
 8134:                         $thisallowed = 'B';
 8135:                     } else {
 8136:                         $thisallowed.=$value;
 8137:                     }
 8138:                 }
 8139:             }
 8140:         } else {
 8141:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8142:             if ($refuri) {
 8143:                 if ($refuri =~ m|^/adm/|) {
 8144:                     $thisallowed='F';
 8145:                 } else {
 8146:                     $refuri=&declutter($refuri);
 8147:                     my ($match) = &is_on_map($refuri);
 8148:                     if ($match) {
 8149:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8150:                         if ($deeplinkblock) {
 8151:                             $thisallowed='D';
 8152:                         } elsif ($noblockcheck) {
 8153:                             $thisallowed='F';
 8154:                         } else {
 8155:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8156:                             if (@blockers > 0) {
 8157:                                 $thisallowed = 'B';
 8158:                             } else {
 8159:                                 $thisallowed='F';
 8160:                             }
 8161:                         }
 8162:                     }
 8163:                 }
 8164:             }
 8165:         }
 8166:     }
 8167: 
 8168:     if ($priv eq 'bre'
 8169: 	&& $thisallowed ne 'F' 
 8170: 	&& $thisallowed ne '2'
 8171: 	&& &is_portfolio_url($uri)) {
 8172: 	$thisallowed = &portfolio_access($uri,$clientip);
 8173:     }
 8174: 
 8175: # Full access at system, domain or course-wide level? Exit.
 8176:     if ($thisallowed=~/F/) {
 8177: 	return 'F';
 8178:     }
 8179: 
 8180: # If this is generating or modifying users, exit with special codes
 8181: 
 8182:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8183: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8184: 	    my ($audom,$auname)=split('/',$uri);
 8185: # no author name given, so this just checks on the general right to make a co-author in this domain
 8186: 	    unless ($auname) { return $thisallowed; }
 8187: # an author name is given, so we are about to actually make a co-author for a certain account
 8188: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8189: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8190: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8191: 	}
 8192: 	return $thisallowed;
 8193:     }
 8194: #
 8195: # Gathered so far: system, domain and course wide privileges
 8196: #
 8197: # Course: See if uri or referer is an individual resource that is part of 
 8198: # the course
 8199: 
 8200:     if ($env{'request.course.id'}) {
 8201: 
 8202: # If this is modifying password (internal auth) domains must match for user and user's role.
 8203: 
 8204:         if ($priv eq 'mip') {
 8205:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8206:                 return $thisallowed;
 8207:             } else {
 8208:                 return '';
 8209:             }
 8210:         }
 8211: 
 8212:        $courseprivid=$env{'request.course.id'};
 8213:        if ($env{'request.course.sec'}) {
 8214:           $courseprivid.='/'.$env{'request.course.sec'};
 8215:        }
 8216:        $courseprivid=~s/\_/\//;
 8217:        my $checkreferer=1;
 8218:        my ($match,$cond)=&is_on_map($uri);
 8219:        if ($match) {
 8220:            $statecond=$cond;
 8221:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8222:                =~/\Q$priv\E\&([^\:]*)/) {
 8223:                my $value = $1;
 8224:                if ($priv eq 'bre') {
 8225:                    if ($noblockcheck) {
 8226:                        $thisallowed.=$value;
 8227:                    } else {
 8228:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8229:                        if (@blockers > 0) {
 8230:                            $thisallowed = 'B';
 8231:                        } else {
 8232:                            $thisallowed.=$value;
 8233:                        }
 8234:                    }
 8235:                } else {
 8236:                    $thisallowed.=$value;
 8237:                }
 8238:                $checkreferer=0;
 8239:            }
 8240:        }
 8241:        
 8242:        if ($checkreferer) {
 8243: 	  my $refuri=$env{'httpref.'.$orguri};
 8244:             unless ($refuri) {
 8245:                 foreach my $key (keys(%env)) {
 8246: 		    if ($key=~/^httpref\..*\*/) {
 8247: 			my $pattern=$key;
 8248:                         $pattern=~s/^httpref\.\/res\///;
 8249:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8250:                         $pattern=~s/\//\\\//g;
 8251:                         if ($orguri=~/$pattern/) {
 8252: 			    $refuri=$env{$key};
 8253:                         }
 8254:                     }
 8255:                 }
 8256:             }
 8257: 
 8258:          if ($refuri) { 
 8259: 	  $refuri=&declutter($refuri);
 8260:           my ($match,$cond)=&is_on_map($refuri);
 8261:             if ($match) {
 8262:               my $refstatecond=$cond;
 8263:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8264:                   =~/\Q$priv\E\&([^\:]*)/) {
 8265:                   my $value = $1;
 8266:                   if ($priv eq 'bre') {
 8267:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8268:                       if ($deeplinkblock) {
 8269:                           $thisallowed = 'D';
 8270:                       } elsif ($noblockcheck) {
 8271:                           $thisallowed.=$value;
 8272:                       } else {
 8273:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8274:                           if (@blockers > 0) {
 8275:                               $thisallowed = 'B';
 8276:                           } else {
 8277:                               $thisallowed.=$value;
 8278:                           }
 8279:                       }
 8280:                   } else {
 8281:                       $thisallowed.=$value;
 8282:                   }
 8283:                   $uri=$refuri;
 8284:                   $statecond=$refstatecond;
 8285:               }
 8286:           }
 8287:         }
 8288:        }
 8289:    }
 8290: 
 8291: #
 8292: # Gathered now: all privileges that could apply, and condition number
 8293: # 
 8294: #
 8295: # Full or no access?
 8296: #
 8297: 
 8298:     if ($thisallowed=~/F/) {
 8299: 	return 'F';
 8300:     }
 8301: 
 8302:     unless ($thisallowed) {
 8303:         return '';
 8304:     }
 8305: 
 8306: # Restrictions exist, deal with them
 8307: #
 8308: #   C:according to course preferences
 8309: #   R:according to resource settings
 8310: #   L:unless locked
 8311: #   X:according to user session state
 8312: #
 8313: 
 8314: # Possibly locked functionality, check all courses
 8315: # Locks might take effect only after 10 minutes cache expiration for other
 8316: # courses, and 2 minutes for current course
 8317: 
 8318:     my $envkey;
 8319:     if ($thisallowed=~/L/) {
 8320:         foreach $envkey (keys(%env)) {
 8321:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8322:                my $courseid=$2;
 8323:                my $roleid=$1.'.'.$2;
 8324:                $courseid=~s/^\///;
 8325:                my $expiretime=600;
 8326:                if ($env{'request.role'} eq $roleid) {
 8327: 		  $expiretime=120;
 8328:                }
 8329: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8330:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8331:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8332: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8333:                }
 8334:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8335:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8336: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8337:                        &log($env{'user.domain'},$env{'user.name'},
 8338:                             $env{'user.home'},
 8339:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8340:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8341:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8342: 		       return '';
 8343:                    }
 8344:                }
 8345:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8346:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8347: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8348:                        &log($env{'user.domain'},$env{'user.name'},
 8349:                             $env{'user.home'},
 8350:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8351:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8352:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8353: 		       return '';
 8354:                    }
 8355:                }
 8356: 	   }
 8357:        }
 8358:     }
 8359:    
 8360: #
 8361: # Rest of the restrictions depend on selected course
 8362: #
 8363: 
 8364:     unless ($env{'request.course.id'}) {
 8365: 	if ($thisallowed eq 'A') {
 8366: 	    return 'A';
 8367:         } elsif ($thisallowed eq 'B') {
 8368:             return 'B';
 8369: 	} else {
 8370: 	    return '1';
 8371: 	}
 8372:     }
 8373: 
 8374: #
 8375: # Now user is definitely in a course
 8376: #
 8377: 
 8378: 
 8379: # Course preferences
 8380: 
 8381:    if ($thisallowed=~/C/) {
 8382:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8383:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8384:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8385: 	   =~/\Q$rolecode\E/) {
 8386: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8387: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8388: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8389: 			$env{'request.course.id'});
 8390: 	   }
 8391:            return '';
 8392:        }
 8393: 
 8394:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8395: 	   =~/\Q$unamedom\E/) {
 8396: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8397: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8398: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8399: 			$env{'request.course.id'});
 8400: 	   }
 8401:            return '';
 8402:        }
 8403:    }
 8404: 
 8405: # Resource preferences
 8406: 
 8407:    if ($thisallowed=~/R/) {
 8408:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8409:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8410: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8411: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8412: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8413: 	   }
 8414: 	   return '';
 8415:        }
 8416:    }
 8417: 
 8418: # Restricted by state or randomout?
 8419: 
 8420:    if ($thisallowed=~/X/) {
 8421:       if ($env{'acc.randomout'}) {
 8422: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8423:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8424:             return ''; 
 8425:          }
 8426:       }
 8427:       if (&condval($statecond)) {
 8428: 	 return '2';
 8429:       } else {
 8430:          return '';
 8431:       }
 8432:    }
 8433: 
 8434:     if ($thisallowed eq 'A') {
 8435: 	return 'A';
 8436:     } elsif ($thisallowed eq 'B') {
 8437:         return 'B';
 8438:     } elsif ($thisallowed eq 'D') {
 8439:         return 'D';
 8440:     }
 8441:    return 'F';
 8442: }
 8443: 
 8444: # ------------------------------------------- Check construction space access
 8445: 
 8446: sub constructaccess {
 8447:     my ($url,$setpriv)=@_;
 8448: 
 8449: # We do not allow editing of previous versions of files
 8450:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8451: 
 8452: # Get username and domain from URL
 8453:     my ($ownername,$ownerdomain,$ownerhome);
 8454: 
 8455:     ($ownerdomain,$ownername) =
 8456:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8457: 
 8458: # The URL does not really point to any authorspace, forget it
 8459:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8460: 
 8461: # Now we need to see if the user has access to the authorspace of
 8462: # $ownername at $ownerdomain
 8463: 
 8464:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8465: # Real author for this?
 8466:        $ownerhome = $env{'user.home'};
 8467:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8468:           return ($ownername,$ownerdomain,$ownerhome);
 8469:        }
 8470:     } else {
 8471: # Co-author for this?
 8472:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8473:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8474:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8475:             return ($ownername,$ownerdomain,$ownerhome);
 8476:         }
 8477:         if ($env{'request.course.id'}) {
 8478:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8479:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8480:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8481:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8482:                     return ($ownername,$ownerdomain,$ownerhome);
 8483:                 }
 8484:             }
 8485:         }
 8486:     }
 8487: 
 8488: # We don't have any access right now. If we are not possibly going to do anything about this,
 8489: # we might as well leave
 8490:    unless ($setpriv) { return ''; }
 8491: 
 8492: # Backdoor access?
 8493:     my $allowed=&allowed('eco',$ownerdomain);
 8494: # Nope
 8495:     unless ($allowed) { return ''; }
 8496: # Looks like we may have access, but could be locked by the owner of the construction space
 8497:     if ($allowed eq 'U') {
 8498:         my %blocked=&get('environment',['domcoord.author'],
 8499:                          $ownerdomain,$ownername);
 8500: # Is blocked by owner
 8501:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8502:     }
 8503:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8504: # Grant temporary access
 8505:         my $then=$env{'user.login.time'};
 8506:         my $update=$env{'user.update.time'};
 8507:         if (!$update) { $update = $then; }
 8508:         my $refresh=$env{'user.refresh.time'};
 8509:         if (!$refresh) { $refresh = $update; }
 8510:         my $now = time;
 8511:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8512:                            $now,'ca','constructaccess');
 8513:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8514:         return($ownername,$ownerdomain,$ownerhome);
 8515:     }
 8516: # No business here
 8517:     return '';
 8518: }
 8519: 
 8520: # ----------------------------------------------------------- Content Blocking
 8521: 
 8522: {
 8523: # Caches for faster Course Contents display where content blocking
 8524: # is in operation (i.e., interval param set) for timed quiz.
 8525: #
 8526: # User for whom data are being temporarily cached.
 8527: my $cacheduser='';
 8528: # Cached blockers for this user (a hash of blocking items). 
 8529: my %cachedblockers=();
 8530: # When the data were last cached.
 8531: my $cachedlast='';
 8532: 
 8533: sub load_all_blockers {
 8534:     my ($uname,$udom,$blocks)=@_;
 8535:     if (($uname ne '') && ($udom ne '')) { 
 8536:         if (($cacheduser eq $uname.':'.$udom) &&
 8537:             (abs($cachedlast-time)<5)) {
 8538:             return;
 8539:         }
 8540:     }
 8541:     $cachedlast=time;
 8542:     $cacheduser=$uname.':'.$udom;
 8543:     %cachedblockers = &get_commblock_resources($blocks);
 8544: }
 8545: 
 8546: sub get_comm_blocks {
 8547:     my ($cdom,$cnum) = @_;
 8548:     if ($cdom eq '' || $cnum eq '') {
 8549:         return unless ($env{'request.course.id'});
 8550:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8551:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8552:     }
 8553:     my %commblocks;
 8554:     my $hashid=$cdom.'_'.$cnum;
 8555:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8556:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8557:         %commblocks = %{$blocksref};
 8558:     } else {
 8559:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8560:         my $cachetime = 600;
 8561:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8562:     }
 8563:     return %commblocks;
 8564: }
 8565: 
 8566: sub get_commblock_resources {
 8567:     my ($blocks) = @_;
 8568:     my %blockers = ();
 8569:     return %blockers unless ($env{'request.course.id'});
 8570:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8571:     my %commblocks;
 8572:     if (ref($blocks) eq 'HASH') {
 8573:         %commblocks = %{$blocks};
 8574:     } else {
 8575:         %commblocks = &get_comm_blocks();
 8576:     }
 8577:     return %blockers unless (keys(%commblocks) > 0); 
 8578:     my $navmap = Apache::lonnavmaps::navmap->new();
 8579:     return %blockers unless (ref($navmap));
 8580:     my $now = time;
 8581:     foreach my $block (keys(%commblocks)) {
 8582:         if ($block =~ /^(\d+)____(\d+)$/) {
 8583:             my ($start,$end) = ($1,$2);
 8584:             if ($start <= $now && $end >= $now) {
 8585:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8586:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8587:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8588:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8589:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8590:                             }
 8591:                         }
 8592:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8593:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8594:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8595:                             }
 8596:                         }
 8597:                     }
 8598:                 }
 8599:             }
 8600:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8601:             my $item = $1;
 8602:             my @to_test;
 8603:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8604:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8605:                     my @interval;
 8606:                     my $type = 'map';
 8607:                     if ($item eq 'course') {
 8608:                         $type = 'course';
 8609:                         @interval=&EXT("resource.0.interval");
 8610:                     } else {
 8611:                         if ($item =~ /___\d+___/) {
 8612:                             $type = 'resource';
 8613:                             @interval=&EXT("resource.0.interval",$item);
 8614:                             if (ref($navmap)) {                        
 8615:                                 my $res = $navmap->getBySymb($item); 
 8616:                                 push(@to_test,$res);
 8617:                             }
 8618:                         } else {
 8619:                             my $mapsymb = &symbread($item,1);
 8620:                             if ($mapsymb) {
 8621:                                 if (ref($navmap)) {
 8622:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8623:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8624:                                     foreach my $res (@to_test) {
 8625:                                         my $symb = $res->symb();
 8626:                                         next if ($symb eq $mapsymb);
 8627:                                         if ($symb ne '') {
 8628:                                             @interval=&EXT("resource.0.interval",$symb);
 8629:                                             if ($interval[1] eq 'map') {
 8630:                                                 last;
 8631:                                             }
 8632:                                         }
 8633:                                     }
 8634:                                 }
 8635:                             }
 8636:                         }
 8637:                     }
 8638:                     if ($interval[0] =~ /^(\d+)/) {
 8639:                         my $timelimit = $1; 
 8640:                         my $first_access;
 8641:                         if ($type eq 'resource') {
 8642:                             $first_access=&get_first_access($interval[1],$item);
 8643:                         } elsif ($type eq 'map') {
 8644:                             $first_access=&get_first_access($interval[1],undef,$item);
 8645:                         } else {
 8646:                             $first_access=&get_first_access($interval[1]);
 8647:                         }
 8648:                         if ($first_access) {
 8649:                             my $timesup = $first_access+$timelimit;
 8650:                             if ($timesup > $now) {
 8651:                                 my $activeblock;
 8652:                                 foreach my $res (@to_test) {
 8653:                                     if ($res->answerable()) {
 8654:                                         $activeblock = 1;
 8655:                                         last;
 8656:                                     }
 8657:                                 }
 8658:                                 if ($activeblock) {
 8659:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8660:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8661:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8662:                                          }
 8663:                                     }
 8664:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8665:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8666:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8667:                                         }
 8668:                                     }
 8669:                                 }
 8670:                             }
 8671:                         }
 8672:                     }
 8673:                 }
 8674:             }
 8675:         }
 8676:     }
 8677:     return %blockers;
 8678: }
 8679: 
 8680: sub has_comm_blocking {
 8681:     my ($priv,$symb,$uri,$blocks) = @_;
 8682:     my @blockers;
 8683:     return unless ($env{'request.course.id'});
 8684:     return unless ($priv eq 'bre');
 8685:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8686:     return if ($env{'request.state'} eq 'construct');
 8687:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8688:     return unless (keys(%cachedblockers) > 0);
 8689:     my (%possibles,@symbs);
 8690:     if (!$symb) {
 8691:         $symb = &symbread($uri,1,1,1,\%possibles);
 8692:     }
 8693:     if ($symb) {
 8694:         @symbs = ($symb);
 8695:     } elsif (keys(%possibles)) { 
 8696:         @symbs = keys(%possibles);
 8697:     }
 8698:     my $noblock;
 8699:     foreach my $symb (@symbs) {
 8700:         last if ($noblock);
 8701:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8702:         foreach my $block (keys(%cachedblockers)) {
 8703:             if ($block =~ /^firstaccess____(.+)$/) {
 8704:                 my $item = $1;
 8705:                 if (($item eq $map) || ($item eq $symb)) {
 8706:                     $noblock = 1;
 8707:                     last;
 8708:                 }
 8709:             }
 8710:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8711:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8712:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8713:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8714:                             push(@blockers,$block);
 8715:                         }
 8716:                     }
 8717:                 }
 8718:             }
 8719:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8720:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8721:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8722:                         push(@blockers,$block);
 8723:                     }
 8724:                 }
 8725:             }
 8726:         }
 8727:     }
 8728:     return if ($noblock);
 8729:     return @blockers;
 8730: }
 8731: }
 8732: 
 8733: sub deeplink_check {
 8734:     my ($priv,$symb,$uri) = @_;
 8735:     return unless ($env{'request.course.id'});
 8736:     return unless ($priv eq 'bre');
 8737:     return if ($env{'request.state'} eq 'construct');
 8738:     return if ($env{'request.role.adv'});
 8739:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8740:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8741:     my (%possibles,@symbs);
 8742:     if (!$symb) {
 8743:         $symb = &symbread($uri,1,1,1,\%possibles);
 8744:     }
 8745:     if ($symb) {
 8746:         @symbs = ($symb);
 8747:     } elsif (keys(%possibles)) {
 8748:         @symbs = keys(%possibles);
 8749:     }
 8750: 
 8751:     my ($login,$switchrole,$allow);
 8752:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8753:         my $key = $1;
 8754:         my $tinyurl;
 8755:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8756:         if (defined($cached)) {
 8757:              $tinyurl = $result;
 8758:         } else {
 8759:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8760:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8761:              if ($currtiny{$key} ne '') {
 8762:                  $tinyurl = $currtiny{$key};
 8763:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8764:              }
 8765:         }
 8766:         if ($tinyurl ne '') {
 8767:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8768:             if ($cnumreq eq $cnum) {
 8769:                 $login = $posslogin;
 8770:             } else {
 8771:                 $switchrole = 1;
 8772:             }
 8773:         }
 8774:     }
 8775:     foreach my $symb (@symbs) {
 8776:         last if ($allow);
 8777:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8778:         if ($deeplink eq '') {
 8779:             $allow = 1;
 8780:         } else {
 8781:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8782:             if ($access eq 'any') {
 8783:                 $allow = 1;
 8784:             } elsif ($login) {
 8785:                 if ($access eq 'only') {
 8786:                     if ($scope eq 'res') {
 8787:                         if ($symb eq $login) {
 8788:                             $allow = 1;
 8789:                         }
 8790:                     } elsif ($scope eq 'map') {
 8791: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8792:                     } elsif ($scope eq 'rec') {
 8793: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8794:                     }
 8795:                 } else {
 8796:                     my ($acctype,$item) = split(/:/,$access);
 8797:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8798:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8799:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8800:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8801:                                 $allow = 1;
 8802:                             }
 8803:                         }
 8804:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8805:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8806:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8807:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8808:                                 $allow = 1;
 8809:                             }
 8810:                         }
 8811:                     }
 8812:                 }
 8813:             }
 8814:         }
 8815:     }
 8816:     return if ($allow);
 8817:     return 1;
 8818: }
 8819: 
 8820: # -------------------------------- Deversion and split uri into path an filename   
 8821: 
 8822: #
 8823: #   Removes the version from a URI and
 8824: #   splits it in to its filename and path to the filename.
 8825: #   Seems like File::Basename could have done this more clearly.
 8826: #   Parameters:
 8827: #      $uri   - input URI
 8828: #   Returns:
 8829: #     Two element list consisting of 
 8830: #     $pathname  - the URI up to and excluding the trailing /
 8831: #     $filename  - The part of the URI following the last /
 8832: #  NOTE:
 8833: #    Another realization of this is simply:
 8834: #    use File::Basename;
 8835: #    ...
 8836: #    $uri = shift;
 8837: #    $filename = basename($uri);
 8838: #    $path     = dirname($uri);
 8839: #    return ($filename, $path);
 8840: #
 8841: #     The implementation below is probably faster however.
 8842: #
 8843: sub split_uri_for_cond {
 8844:     my $uri=&deversion(&declutter(shift));
 8845:     my @uriparts=split(/\//,$uri);
 8846:     my $filename=pop(@uriparts);
 8847:     my $pathname=join('/',@uriparts);
 8848:     return ($pathname,$filename);
 8849: }
 8850: # --------------------------------------------------- Is a resource on the map?
 8851: 
 8852: sub is_on_map {
 8853:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8854:     #Trying to find the conditional for the file
 8855:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8856: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8857:     if ($match) {
 8858: 	return (1,$1);
 8859:     } else {
 8860: 	return (0,0);
 8861:     }
 8862: }
 8863: 
 8864: # --------------------------------------------------------- Get symb from alias
 8865: 
 8866: sub get_symb_from_alias {
 8867:     my $symb=shift;
 8868:     my ($map,$resid,$url)=&decode_symb($symb);
 8869: # Already is a symb
 8870:     if ($url) { return $symb; }
 8871: # Must be an alias
 8872:     my $aliassymb='';
 8873:     my %bighash;
 8874:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8875:                             &GDBM_READER(),0640)) {
 8876:         my $rid=$bighash{'mapalias_'.$symb};
 8877: 	if ($rid) {
 8878: 	    my ($mapid,$resid)=split(/\./,$rid);
 8879: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8880: 				    $resid,$bighash{'src_'.$rid});
 8881: 	}
 8882:         untie %bighash;
 8883:     }
 8884:     return $aliassymb;
 8885: }
 8886: 
 8887: # ----------------------------------------------------------------- Define Role
 8888: 
 8889: sub definerole {
 8890:   if (allowed('mcr','/')) {
 8891:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8892:     foreach my $role (split(':',$sysrole)) {
 8893: 	my ($crole,$cqual)=split(/\&/,$role);
 8894:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8895:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8896: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8897:                return "refused:s:$crole&$cqual"; 
 8898:             }
 8899:         }
 8900:     }
 8901:     foreach my $role (split(':',$domrole)) {
 8902: 	my ($crole,$cqual)=split(/\&/,$role);
 8903:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8904:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8905: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8906:                return "refused:d:$crole&$cqual"; 
 8907:             }
 8908:         }
 8909:     }
 8910:     foreach my $role (split(':',$courole)) {
 8911: 	my ($crole,$cqual)=split(/\&/,$role);
 8912:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8913:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8914: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8915:                return "refused:c:$crole&$cqual"; 
 8916:             }
 8917:         }
 8918:     }
 8919:     my $uhome;
 8920:     if (($uname ne '') && ($udom ne '')) {
 8921:         $uhome = &homeserver($uname,$udom);
 8922:         return $uhome if ($uhome eq 'no_host');
 8923:     } else {
 8924:         $uname = $env{'user.name'};
 8925:         $udom = $env{'user.domain'};
 8926:         $uhome = $env{'user.home'};
 8927:     }
 8928:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8929:                 "$udom:$uname:rolesdef_$rolename=".
 8930:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8931:     return reply($command,$uhome);
 8932:   } else {
 8933:     return 'refused';
 8934:   }
 8935: }
 8936: 
 8937: # ---------------- Make a metadata query against the network of library servers
 8938: 
 8939: sub metadata_query {
 8940:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8941:     my %rhash;
 8942:     my %libserv = &all_library();
 8943:     my @server_list = (defined($server_array) ? @$server_array
 8944:                                               : keys(%libserv) );
 8945:     for my $server (@server_list) {
 8946:         my $domains = ''; 
 8947:         if (ref($domains_hash) eq 'HASH') {
 8948:             $domains = $domains_hash->{$server}; 
 8949:         }
 8950: 	unless ($custom or $customshow) {
 8951: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8952: 	    $rhash{$server}=$reply;
 8953: 	}
 8954: 	else {
 8955: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8956: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8957: 			     $server);
 8958: 	    $rhash{$server}=$reply;
 8959: 	}
 8960:     }
 8961:     return \%rhash;
 8962: }
 8963: 
 8964: # ----------------------------------------- Send log queries and wait for reply
 8965: 
 8966: sub log_query {
 8967:     my ($uname,$udom,$query,%filters)=@_;
 8968:     my $uhome=&homeserver($uname,$udom);
 8969:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8970:     my $uhost=&hostname($uhome);
 8971:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8972:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8973:                        $uhome);
 8974:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8975:     return get_query_reply($queryid);
 8976: }
 8977: 
 8978: # -------------------------- Update MySQL table for portfolio file
 8979: 
 8980: sub update_portfolio_table {
 8981:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8982:     if ($group ne '') {
 8983:         $file_name =~s /^\Q$group\E//;
 8984:     }
 8985:     my $homeserver = &homeserver($uname,$udom);
 8986:     my $queryid=
 8987:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8988:                ':'.&escape($file_name).':'.$action,$homeserver);
 8989:     my $reply = &get_query_reply($queryid);
 8990:     return $reply;
 8991: }
 8992: 
 8993: # -------------------------- Update MySQL allusers table
 8994: 
 8995: sub update_allusers_table {
 8996:     my ($uname,$udom,$names) = @_;
 8997:     my $homeserver = &homeserver($uname,$udom);
 8998:     my $queryid=
 8999:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9000:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9001:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9002:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9003:                'generation='.&escape($names->{'generation'}).'%%'.
 9004:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9005:                'id='.&escape($names->{'id'}),$homeserver);
 9006:     return;
 9007: }
 9008: 
 9009: # ------- Request retrieval of institutional classlists for course(s)
 9010: 
 9011: sub fetch_enrollment_query {
 9012:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9013:     my ($homeserver,$sleep,$loopmax);
 9014:     my $maxtries = 1;
 9015:     if ($context eq 'automated') {
 9016:         $homeserver = $perlvar{'lonHostID'};
 9017:         $sleep = 2;
 9018:         $loopmax = 100;
 9019:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9020:     } else {
 9021:         $homeserver = &homeserver($cnum,$dom);
 9022:     }
 9023:     my $host=&hostname($homeserver);
 9024:     my $cmd = '';
 9025:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9026:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9027:     }
 9028:     $cmd =~ s/%%$//;
 9029:     $cmd = &escape($cmd);
 9030:     my $query = 'fetchenrollment';
 9031:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9032:     unless ($queryid=~/^\Q$host\E\_/) { 
 9033:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9034:         return 'error: '.$queryid;
 9035:     }
 9036:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9037:     my $tries = 1;
 9038:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9039:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9040:         $tries ++;
 9041:     }
 9042:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9043:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9044:     } else {
 9045:         my @responses = split(/:/,$reply);
 9046:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9047:             foreach my $line (@responses) {
 9048:                 my ($key,$value) = split(/=/,$line,2);
 9049:                 $$replyref{$key} = $value;
 9050:             }
 9051:         } else {
 9052:             my $pathname = LONCAPA::tempdir();
 9053:             foreach my $line (@responses) {
 9054:                 my ($key,$value) = split(/=/,$line);
 9055:                 $$replyref{$key} = $value;
 9056:                 if ($value > 0) {
 9057:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9058:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9059:                         my $destname = $pathname.'/'.$filename;
 9060:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9061:                         if ($xml_classlist =~ /^error/) {
 9062:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9063:                         } else {
 9064:                             if ( open(FILE,">",$destname) ) {
 9065:                                 print FILE &unescape($xml_classlist);
 9066:                                 close(FILE);
 9067:                             } else {
 9068:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9069:                             }
 9070:                         }
 9071:                     }
 9072:                 }
 9073:             }
 9074:         }
 9075:         return 'ok';
 9076:     }
 9077:     return 'error';
 9078: }
 9079: 
 9080: sub get_query_reply {
 9081:     my ($queryid,$sleep,$loopmax) = @_;;
 9082:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9083:         $sleep = 0.2;
 9084:     }
 9085:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9086:         $loopmax = 100;
 9087:     }
 9088:     my $replyfile=LONCAPA::tempdir().$queryid;
 9089:     my $reply='';
 9090:     for (1..$loopmax) {
 9091: 	sleep($sleep);
 9092:         if (-e $replyfile.'.end') {
 9093: 	    if (open(my $fh,"<",$replyfile)) {
 9094: 		$reply = join('',<$fh>);
 9095: 		close($fh);
 9096: 	   } else { return 'error: reply_file_error'; }
 9097:            return &unescape($reply);
 9098: 	}
 9099:     }
 9100:     return 'timeout:'.$queryid;
 9101: }
 9102: 
 9103: sub courselog_query {
 9104: #
 9105: # possible filters:
 9106: # url: url or symb
 9107: # username
 9108: # domain
 9109: # action: view, submit, grade
 9110: # start: timestamp
 9111: # end: timestamp
 9112: #
 9113:     my (%filters)=@_;
 9114:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9115:     if ($filters{'url'}) {
 9116: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9117:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9118:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9119:     }
 9120:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9122:     return &log_query($cname,$cdom,'courselog',%filters);
 9123: }
 9124: 
 9125: sub userlog_query {
 9126: #
 9127: # possible filters:
 9128: # action: log check role
 9129: # start: timestamp
 9130: # end: timestamp
 9131: #
 9132:     my ($uname,$udom,%filters)=@_;
 9133:     return &log_query($uname,$udom,'userlog',%filters);
 9134: }
 9135: 
 9136: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9137: 
 9138: sub auto_run {
 9139:     my ($cnum,$cdom) = @_;
 9140:     my $response = 0;
 9141:     my $settings;
 9142:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9143:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9144:         $settings = $domconfig{'autoenroll'};
 9145:         if ($settings->{'run'} eq '1') {
 9146:             $response = 1;
 9147:         }
 9148:     } else {
 9149:         my $homeserver;
 9150:         if (&is_course($cdom,$cnum)) {
 9151:             $homeserver = &homeserver($cnum,$cdom);
 9152:         } else {
 9153:             $homeserver = &domain($cdom,'primary');
 9154:         }
 9155:         if ($homeserver ne 'no_host') {
 9156:             $response = &reply('autorun:'.$cdom,$homeserver);
 9157:         }
 9158:     }
 9159:     return $response;
 9160: }
 9161: 
 9162: sub auto_get_sections {
 9163:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9164:     my $homeserver;
 9165:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9166:         $homeserver = &homeserver($cnum,$cdom);
 9167:     }
 9168:     if (!defined($homeserver)) { 
 9169:         if ($cdom =~ /^$match_domain$/) {
 9170:             $homeserver = &domain($cdom,'primary');
 9171:         }
 9172:     }
 9173:     my @secs;
 9174:     if (defined($homeserver)) {
 9175:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9176:         unless ($response eq 'refused') {
 9177:             @secs = split(/:/,$response);
 9178:         }
 9179:     }
 9180:     return @secs;
 9181: }
 9182: 
 9183: sub auto_new_course {
 9184:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9185:     my $homeserver = &homeserver($cnum,$cdom);
 9186:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9187:     return $response;
 9188: }
 9189: 
 9190: sub auto_validate_courseID {
 9191:     my ($cnum,$cdom,$inst_course_id) = @_;
 9192:     my $homeserver = &homeserver($cnum,$cdom);
 9193:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9194:     return $response;
 9195: }
 9196: 
 9197: sub auto_validate_instcode {
 9198:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9199:     my ($homeserver,$response);
 9200:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9201:         $homeserver = &homeserver($cnum,$cdom);
 9202:     }
 9203:     if (!defined($homeserver)) {
 9204:         if ($cdom =~ /^$match_domain$/) {
 9205:             $homeserver = &domain($cdom,'primary');
 9206:         }
 9207:     }
 9208:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9209:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9210:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9211:     return ($outcome,$description,$defaultcredits);
 9212: }
 9213: 
 9214: sub auto_create_password {
 9215:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9216:     my ($homeserver,$response);
 9217:     my $create_passwd = 0;
 9218:     my $authchk = '';
 9219:     if ($udom =~ /^$match_domain$/) {
 9220:         $homeserver = &domain($udom,'primary');
 9221:     }
 9222:     if ($homeserver eq '') {
 9223:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9224:             $homeserver = &homeserver($cnum,$cdom);
 9225:         }
 9226:     }
 9227:     if ($homeserver eq '') {
 9228:         $authchk = 'nodomain';
 9229:     } else {
 9230:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9231:         if ($response eq 'refused') {
 9232:             $authchk = 'refused';
 9233:         } else {
 9234:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9235:         }
 9236:     }
 9237:     return ($authparam,$create_passwd,$authchk);
 9238: }
 9239: 
 9240: sub auto_photo_permission {
 9241:     my ($cnum,$cdom,$students) = @_;
 9242:     my $homeserver = &homeserver($cnum,$cdom);
 9243:     my ($outcome,$perm_reqd,$conditions) = 
 9244: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9245:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9246: 	return (undef,undef);
 9247:     }
 9248:     return ($outcome,$perm_reqd,$conditions);
 9249: }
 9250: 
 9251: sub auto_checkphotos {
 9252:     my ($uname,$udom,$pid) = @_;
 9253:     my $homeserver = &homeserver($uname,$udom);
 9254:     my ($result,$resulttype);
 9255:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9256: 				   &escape($uname).':'.&escape($pid),
 9257: 				   $homeserver));
 9258:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9259: 	return (undef,undef);
 9260:     }
 9261:     if ($outcome) {
 9262:         ($result,$resulttype) = split(/:/,$outcome);
 9263:     } 
 9264:     return ($result,$resulttype);
 9265: }
 9266: 
 9267: sub auto_photochoice {
 9268:     my ($cnum,$cdom) = @_;
 9269:     my $homeserver = &homeserver($cnum,$cdom);
 9270:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9271: 						       &escape($cdom),
 9272: 						       $homeserver)));
 9273:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9274: 	return (undef,undef);
 9275:     }
 9276:     return ($update,$comment);
 9277: }
 9278: 
 9279: sub auto_photoupdate {
 9280:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9281:     my $homeserver = &homeserver($cnum,$dom);
 9282:     my $host=&hostname($homeserver);
 9283:     my $cmd = '';
 9284:     my $maxtries = 1;
 9285:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9286:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9287:     }
 9288:     $cmd =~ s/%%$//;
 9289:     $cmd = &escape($cmd);
 9290:     my $query = 'institutionalphotos';
 9291:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9292:     unless ($queryid=~/^\Q$host\E\_/) {
 9293:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9294:         return 'error: '.$queryid;
 9295:     }
 9296:     my $reply = &get_query_reply($queryid);
 9297:     my $tries = 1;
 9298:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9299:         $reply = &get_query_reply($queryid);
 9300:         $tries ++;
 9301:     }
 9302:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9303:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9304:     } else {
 9305:         my @responses = split(/:/,$reply);
 9306:         my $outcome = shift(@responses); 
 9307:         foreach my $item (@responses) {
 9308:             my ($key,$value) = split(/=/,$item);
 9309:             $$photo{$key} = $value;
 9310:         }
 9311:         return $outcome;
 9312:     }
 9313:     return 'error';
 9314: }
 9315: 
 9316: sub auto_instcode_format {
 9317:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9318: 	$cat_order) = @_;
 9319:     my $courses = '';
 9320:     my @homeservers;
 9321:     if ($caller eq 'global') {
 9322: 	my %servers = &get_servers($codedom,'library');
 9323: 	foreach my $tryserver (keys(%servers)) {
 9324: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9325: 		push(@homeservers,$tryserver);
 9326: 	    }
 9327:         }
 9328:     } elsif ($caller eq 'requests') {
 9329:         if ($codedom =~ /^$match_domain$/) {
 9330:             my $chome = &domain($codedom,'primary');
 9331:             unless ($chome eq 'no_host') {
 9332:                 push(@homeservers,$chome);
 9333:             }
 9334:         }
 9335:     } else {
 9336:         push(@homeservers,&homeserver($caller,$codedom));
 9337:     }
 9338:     foreach my $code (keys(%{$instcodes})) {
 9339:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9340:     }
 9341:     chop($courses);
 9342:     my $ok_response = 0;
 9343:     my $response;
 9344:     while (@homeservers > 0 && $ok_response == 0) {
 9345:         my $server = shift(@homeservers); 
 9346:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9347:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9348:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9349: 		split(/:/,$response);
 9350:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9351:             push(@{$codetitles},&str2array($codetitles_str));
 9352:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9353:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9354:             $ok_response = 1;
 9355:         }
 9356:     }
 9357:     if ($ok_response) {
 9358:         return 'ok';
 9359:     } else {
 9360:         return $response;
 9361:     }
 9362: }
 9363: 
 9364: sub auto_instcode_defaults {
 9365:     my ($domain,$returnhash,$code_order) = @_;
 9366:     my @homeservers;
 9367: 
 9368:     my %servers = &get_servers($domain,'library');
 9369:     foreach my $tryserver (keys(%servers)) {
 9370: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9371: 	    push(@homeservers,$tryserver);
 9372: 	}
 9373:     }
 9374: 
 9375:     my $response;
 9376:     foreach my $server (@homeservers) {
 9377:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9378:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9379: 	
 9380: 	foreach my $pair (split(/\&/,$response)) {
 9381: 	    my ($name,$value)=split(/\=/,$pair);
 9382: 	    if ($name eq 'code_order') {
 9383: 		@{$code_order} = split(/\&/,&unescape($value));
 9384: 	    } else {
 9385: 		$returnhash->{&unescape($name)}=&unescape($value);
 9386: 	    }
 9387: 	}
 9388: 	return 'ok';
 9389:     }
 9390: 
 9391:     return $response;
 9392: }
 9393: 
 9394: sub auto_possible_instcodes {
 9395:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9396:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9397:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9398:         return;
 9399:     }
 9400:     my (@homeservers,$uhome);
 9401:     if (defined(&domain($domain,'primary'))) {
 9402:         $uhome=&domain($domain,'primary');
 9403:         push(@homeservers,&domain($domain,'primary'));
 9404:     } else {
 9405:         my %servers = &get_servers($domain,'library');
 9406:         foreach my $tryserver (keys(%servers)) {
 9407:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9408:                 push(@homeservers,$tryserver);
 9409:             }
 9410:         }
 9411:     }
 9412:     my $response;
 9413:     foreach my $server (@homeservers) {
 9414:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9415:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9416:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9417:             split(':',$response);
 9418:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9419:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9420:         foreach my $item (split('&',$cat_title)) {   
 9421:             my ($name,$value)=split('=',$item);
 9422:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9423:         }
 9424:         foreach my $item (split('&',$cat_order)) {
 9425:             my ($name,$value)=split('=',$item);
 9426:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9427:         }
 9428:         return 'ok';
 9429:     }
 9430:     return $response;
 9431: }
 9432: 
 9433: sub auto_courserequest_checks {
 9434:     my ($dom) = @_;
 9435:     my ($homeserver,%validations);
 9436:     if ($dom =~ /^$match_domain$/) {
 9437:         $homeserver = &domain($dom,'primary');
 9438:     }
 9439:     unless ($homeserver eq 'no_host') {
 9440:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9441:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9442:             my @items = split(/&/,$response);
 9443:             foreach my $item (@items) {
 9444:                 my ($key,$value) = split('=',$item);
 9445:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9446:             }
 9447:         }
 9448:     }
 9449:     return %validations; 
 9450: }
 9451: 
 9452: sub auto_courserequest_validation {
 9453:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9454:     my ($homeserver,$response);
 9455:     if ($dom =~ /^$match_domain$/) {
 9456:         $homeserver = &domain($dom,'primary');
 9457:     }
 9458:     unless ($homeserver eq 'no_host') {
 9459:         my $customdata;
 9460:         if (ref($custominfo) eq 'HASH') {
 9461:             $customdata = &freeze_escape($custominfo);
 9462:         }
 9463:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9464:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9465:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9466:                                     $customdata,$homeserver));
 9467:     }
 9468:     return $response;
 9469: }
 9470: 
 9471: sub auto_validate_class_sec {
 9472:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9473:     my $homeserver = &homeserver($cnum,$cdom);
 9474:     my $ownerlist;
 9475:     if (ref($owners) eq 'ARRAY') {
 9476:         $ownerlist = join(',',@{$owners});
 9477:     } else {
 9478:         $ownerlist = $owners;
 9479:     }
 9480:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9481:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9482:     return $response;
 9483: }
 9484: 
 9485: sub auto_validate_instclasses {
 9486:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9487:     my ($homeserver,%validations);
 9488:     $homeserver = &homeserver($cnum,$cdom);
 9489:     unless ($homeserver eq 'no_host') {
 9490:         my $ownerlist;
 9491:         if (ref($owners) eq 'ARRAY') {
 9492:             $ownerlist = join(',',@{$owners});
 9493:         } else {
 9494:             $ownerlist = $owners;
 9495:         }
 9496:         if (ref($classesref) eq 'HASH') {
 9497:             my $classes = &freeze_escape($classesref);
 9498:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9499:                                 ':'.$cdom.':'.$classes,$homeserver);
 9500:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9501:                 my @items = split(/&/,$response);
 9502:                 foreach my $item (@items) {
 9503:                     my ($key,$value) = split('=',$item);
 9504:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9505:                 }
 9506:             }
 9507:         }
 9508:     }
 9509:     return %validations;
 9510: }
 9511: 
 9512: sub auto_crsreq_update {
 9513:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9514:         $code,$accessstart,$accessend,$inbound) = @_;
 9515:     my ($homeserver,%crsreqresponse);
 9516:     if ($cdom =~ /^$match_domain$/) {
 9517:         $homeserver = &domain($cdom,'primary');
 9518:     }
 9519:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9520:         my $info;
 9521:         if (ref($inbound) eq 'HASH') {
 9522:             $info = &freeze_escape($inbound);
 9523:         }
 9524:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9525:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9526:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9527:                             &escape($title).':'.&escape($code).':'.
 9528:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9529:                             $homeserver);
 9530:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9531:             my @items = split(/&/,$response);
 9532:             foreach my $item (@items) {
 9533:                 my ($key,$value) = split('=',$item);
 9534:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9535:             }
 9536:         }
 9537:     }
 9538:     return \%crsreqresponse;
 9539: }
 9540: 
 9541: sub auto_export_grades {
 9542:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9543:     my ($homeserver,%exportresponse);
 9544:     if ($cdom =~ /^$match_domain$/) {
 9545:         $homeserver = &domain($cdom,'primary');
 9546:     }
 9547:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9548:         my $info;
 9549:         if (ref($inforef) eq 'HASH') {
 9550:             $info = &freeze_escape($inforef);
 9551:         }
 9552:         if (ref($gradesref) eq 'HASH') {
 9553:             my $grades = &freeze_escape($gradesref);
 9554:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9555:                                 $info.':'.$grades,$homeserver);
 9556:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9557:                 my @items = split(/&/,$response);
 9558:                 foreach my $item (@items) {
 9559:                     my ($key,$value) = split('=',$item);
 9560:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9561:                 }
 9562:             }
 9563:         }
 9564:     }
 9565:     return \%exportresponse;
 9566: }
 9567: 
 9568: sub check_instcode_cloning {
 9569:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9570:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9571:         return;
 9572:     }
 9573:     my $canclone;
 9574:     if (@{$code_order} > 0) {
 9575:         my $instcoderegexp ='^';
 9576:         my @clonecodes = split(/\&/,$cloner);
 9577:         foreach my $item (@{$code_order}) {
 9578:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9579:                 foreach my $pair (@clonecodes) {
 9580:                     my ($key,$val) = split(/\=/,$pair,2);
 9581:                     $val = &unescape($val);
 9582:                     if ($key eq $item) {
 9583:                         $instcoderegexp .= '('.$val.')';
 9584:                         last;
 9585:                     }
 9586:                 }
 9587:             } else {
 9588:                 $instcoderegexp .= $codedefaults->{$item};
 9589:             }
 9590:         }
 9591:         $instcoderegexp .= '$';
 9592:         my (@from,@to);
 9593:         eval {
 9594:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9595:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9596:         };
 9597:         if ((@from > 0) && (@to > 0)) {
 9598:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9599:             if (!@diffs) {
 9600:                 $canclone = 1;
 9601:             }
 9602:         }
 9603:     }
 9604:     return $canclone;
 9605: }
 9606: 
 9607: sub default_instcode_cloning {
 9608:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9609:     my (%codedefaults,@code_order,$canclone);
 9610:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9611:         %codedefaults = %{$codedefaultsref};
 9612:         @code_order = @{$codeorderref};
 9613:     } elsif ($clonedom) {
 9614:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9615:     }
 9616:     if (($domdefclone) && (@code_order)) {
 9617:         my @clonecodes = split(/\+/,$domdefclone);
 9618:         my $instcoderegexp ='^';
 9619:         foreach my $item (@code_order) {
 9620:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9621:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9622:             } else {
 9623:                 $instcoderegexp .= $codedefaults{$item};
 9624:             }
 9625:         }
 9626:         $instcoderegexp .= '$';
 9627:         my (@from,@to);
 9628:         eval {
 9629:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9630:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9631:         };
 9632:         if ((@from > 0) && (@to > 0)) {
 9633:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9634:             if (!@diffs) {
 9635:                 $canclone = 1;
 9636:             }
 9637:         }
 9638:     }
 9639:     return $canclone;
 9640: }
 9641: 
 9642: # ------------------------------------------------------- Course Group routines
 9643: 
 9644: sub get_coursegroups {
 9645:     my ($cdom,$cnum,$group,$namespace) = @_;
 9646:     return(&dump($namespace,$cdom,$cnum,$group));
 9647: }
 9648: 
 9649: sub modify_coursegroup {
 9650:     my ($cdom,$cnum,$groupsettings) = @_;
 9651:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9652: }
 9653: 
 9654: sub toggle_coursegroup_status {
 9655:     my ($cdom,$cnum,$group,$action) = @_;
 9656:     my ($from_namespace,$to_namespace);
 9657:     if ($action eq 'delete') {
 9658:         $from_namespace = 'coursegroups';
 9659:         $to_namespace = 'deleted_groups';
 9660:     } else {
 9661:         $from_namespace = 'deleted_groups';
 9662:         $to_namespace = 'coursegroups';
 9663:     }
 9664:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9665:     if (my $tmp = &error(%curr_group)) {
 9666:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9667:         return ('read error',$tmp);
 9668:     } else {
 9669:         my %savedsettings = %curr_group; 
 9670:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9671:         my $deloutcome;
 9672:         if ($result eq 'ok') {
 9673:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9674:         } else {
 9675:             return ('write error',$result);
 9676:         }
 9677:         if ($deloutcome eq 'ok') {
 9678:             return 'ok';
 9679:         } else {
 9680:             return ('delete error',$deloutcome);
 9681:         }
 9682:     }
 9683: }
 9684: 
 9685: sub modify_group_roles {
 9686:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9687:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9688:     my $role = 'gr/'.&escape($userprivs);
 9689:     my ($uname,$udom) = split(/:/,$user);
 9690:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9691:     if ($result eq 'ok') {
 9692:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9693:     }
 9694:     return $result;
 9695: }
 9696: 
 9697: sub modify_coursegroup_membership {
 9698:     my ($cdom,$cnum,$membership) = @_;
 9699:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9700:     return $result;
 9701: }
 9702: 
 9703: sub get_active_groups {
 9704:     my ($udom,$uname,$cdom,$cnum) = @_;
 9705:     my $now = time;
 9706:     my %groups = ();
 9707:     foreach my $key (keys(%env)) {
 9708:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9709:             my ($start,$end) = split(/\./,$env{$key});
 9710:             if (($end!=0) && ($end<$now)) { next; }
 9711:             if (($start!=0) && ($start>$now)) { next; }
 9712:             if ($1 eq $cdom && $2 eq $cnum) {
 9713:                 $groups{$3} = $env{$key} ;
 9714:             }
 9715:         }
 9716:     }
 9717:     return %groups;
 9718: }
 9719: 
 9720: sub get_group_membership {
 9721:     my ($cdom,$cnum,$group) = @_;
 9722:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9723: }
 9724: 
 9725: sub get_users_groups {
 9726:     my ($udom,$uname,$courseid) = @_;
 9727:     my @usersgroups;
 9728:     my $cachetime=1800;
 9729: 
 9730:     my $hashid="$udom:$uname:$courseid";
 9731:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9732:     if (defined($cached)) {
 9733:         @usersgroups = split(/:/,$grouplist);
 9734:     } else {  
 9735:         $grouplist = '';
 9736:         my $courseurl = &courseid_to_courseurl($courseid);
 9737:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9738:         my $access_end = $env{'course.'.$courseid.
 9739:                               '.default_enrollment_end_date'};
 9740:         my $now = time;
 9741:         foreach my $key (keys(%roleshash)) {
 9742:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9743:                 my $group = $1;
 9744:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9745:                     my $start = $2;
 9746:                     my $end = $1;
 9747:                     if ($start == -1) { next; } # deleted from group
 9748:                     if (($start!=0) && ($start>$now)) { next; }
 9749:                     if (($end!=0) && ($end<$now)) {
 9750:                         if ($access_end && $access_end < $now) {
 9751:                             if ($access_end - $end < 86400) {
 9752:                                 push(@usersgroups,$group);
 9753:                             }
 9754:                         }
 9755:                         next;
 9756:                     }
 9757:                     push(@usersgroups,$group);
 9758:                 }
 9759:             }
 9760:         }
 9761:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9762:         $grouplist = join(':',@usersgroups);
 9763:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9764:     }
 9765:     return @usersgroups;
 9766: }
 9767: 
 9768: sub devalidate_getgroups_cache {
 9769:     my ($udom,$uname,$cdom,$cnum)=@_;
 9770:     my $courseid = $cdom.'_'.$cnum;
 9771: 
 9772:     my $hashid="$udom:$uname:$courseid";
 9773:     &devalidate_cache_new('getgroups',$hashid);
 9774: }
 9775: 
 9776: # ------------------------------------------------------------------ Plain Text
 9777: 
 9778: sub plaintext {
 9779:     my ($short,$type,$cid,$forcedefault) = @_;
 9780:     if ($short =~ m{^cr/}) {
 9781: 	return (split('/',$short))[-1];
 9782:     }
 9783:     if (!defined($cid)) {
 9784:         $cid = $env{'request.course.id'};
 9785:     }
 9786:     my %rolenames = (
 9787:                       Course    => 'std',
 9788:                       Community => 'alt1',
 9789:                       Placement => 'std',
 9790:                     );
 9791:     if ($cid ne '') {
 9792:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9793:             unless ($forcedefault) {
 9794:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9795:                 &Apache::lonlocal::mt_escape(\$roletext);
 9796:                 return &Apache::lonlocal::mt($roletext);
 9797:             }
 9798:         }
 9799:     }
 9800:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9801:         (defined($rolenames{$type})) && 
 9802:         (defined($prp{$short}{$rolenames{$type}}))) {
 9803:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9804:     } elsif ($cid ne '') {
 9805:         my $crstype = $env{'course.'.$cid.'.type'};
 9806:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9807:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9808:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9809:         }
 9810:     }
 9811:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9812: }
 9813: 
 9814: # ----------------------------------------------------------------- Assign Role
 9815: 
 9816: sub assignrole {
 9817:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9818:         $context)=@_;
 9819:     my $mrole;
 9820:     if ($role =~ /^cr\//) {
 9821:         my $cwosec=$url;
 9822:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9823: 	unless (&allowed('ccr',$cwosec)) {
 9824:            my $refused = 1;
 9825:            if ($context eq 'requestcourses') {
 9826:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9827:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9828:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9829:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9830:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9831:                            if ($crsenv{'internal.courseowner'} eq
 9832:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9833:                                $refused = '';
 9834:                            }
 9835:                        }
 9836:                    }
 9837:                }
 9838:            }
 9839:            if ($refused) {
 9840:                &logthis('Refused custom assignrole: '.
 9841:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9842:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9843:                return 'refused';
 9844:            }
 9845:         }
 9846:         $mrole='cr';
 9847:     } elsif ($role =~ /^gr\//) {
 9848:         my $cwogrp=$url;
 9849:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9850:         unless (&allowed('mdg',$cwogrp)) {
 9851:             &logthis('Refused group assignrole: '.
 9852:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9853:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9854:             return 'refused';
 9855:         }
 9856:         $mrole='gr';
 9857:     } else {
 9858:         my $cwosec=$url;
 9859:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9860:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9861:             my $refused;
 9862:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9863:                 if (!(&allowed('c'.$role,$url))) {
 9864:                     $refused = 1;
 9865:                 }
 9866:             } else {
 9867:                 $refused = 1;
 9868:             }
 9869:             if ($refused) {
 9870:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9871:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9872:                     my %crsenv;
 9873:                     if ($role eq 'cc' || $role eq 'co') {
 9874:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9875:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9876:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9877:                                 if ($crsenv{'internal.courseowner'} eq 
 9878:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9879:                                     $refused = '';
 9880:                                 }
 9881:                             }
 9882:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9883:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9884:                                 if ($crsenv{'internal.courseowner'} eq 
 9885:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9886:                                     $refused = '';
 9887:                                 }
 9888:                             }
 9889:                         }
 9890:                     }
 9891:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9892:                     if ($role eq 'st') {
 9893:                         $refused = '';
 9894:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9895:                         $refused = '';
 9896:                     }
 9897:                 } elsif ($context eq 'requestcourses') {
 9898:                     my @possroles = ('st','ta','ep','in','cc','co');
 9899:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9900:                         my $wrongcc;
 9901:                         if ($cnum =~ /^$match_community$/) {
 9902:                             $wrongcc = 1 if ($role eq 'cc');
 9903:                         } else {
 9904:                             $wrongcc = 1 if ($role eq 'co');
 9905:                         }
 9906:                         unless ($wrongcc) {
 9907:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9908:                             if ($crsenv{'internal.courseowner'} eq 
 9909:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9910:                                 $refused = '';
 9911:                             }
 9912:                         }
 9913:                     }
 9914:                 } elsif ($context eq 'requestauthor') {
 9915:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9916:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9917:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9918:                             $refused = '';
 9919:                         } else {
 9920:                             my %domdefaults = &get_domain_defaults($udom);
 9921:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9922:                                 my $checkbystatus;
 9923:                                 if ($env{'user.adv'}) { 
 9924:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9925:                                     if ($disposition eq 'automatic') {
 9926:                                         $refused = '';
 9927:                                     } elsif ($disposition eq '') {
 9928:                                         $checkbystatus = 1;
 9929:                                     } 
 9930:                                 } else {
 9931:                                     $checkbystatus = 1;
 9932:                                 }
 9933:                                 if ($checkbystatus) {
 9934:                                     if ($env{'environment.inststatus'}) {
 9935:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9936:                                         foreach my $type (@inststatuses) {
 9937:                                             if (($type ne '') &&
 9938:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9939:                                                 $refused = '';
 9940:                                             }
 9941:                                         }
 9942:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9943:                                         $refused = '';
 9944:                                     }
 9945:                                 }
 9946:                             }
 9947:                         }
 9948:                     }
 9949:                 }
 9950:                 if ($refused) {
 9951:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9952:                              ' '.$role.' '.$end.' '.$start.' by '.
 9953: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9954:                     return 'refused';
 9955:                 }
 9956:             }
 9957:         } elsif ($role eq 'au') {
 9958:             if ($url ne '/'.$udom.'/') {
 9959:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9960:                          ' to assign author role for '.$uname.':'.$udom.
 9961:                          ' in domain: '.$url.' refused (wrong domain).');
 9962:                 return 'refused';
 9963:             }
 9964:         }
 9965:         $mrole=$role;
 9966:     }
 9967:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9968:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9969:     if ($end) { $command.='_'.$end; }
 9970:     if ($start) {
 9971: 	if ($end) { 
 9972:            $command.='_'.$start; 
 9973:         } else {
 9974:            $command.='_0_'.$start;
 9975:         }
 9976:     }
 9977:     my $origstart = $start;
 9978:     my $origend = $end;
 9979:     my $delflag;
 9980: # actually delete
 9981:     if ($deleteflag) {
 9982: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9983: # modify command to delete the role
 9984:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9985:                 "$udom:$uname:$url".'_'."$mrole";
 9986: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9987: # set start and finish to negative values for userrolelog
 9988:            $start=-1;
 9989:            $end=-1;
 9990:            $delflag = 1;
 9991:         }
 9992:     }
 9993: # send command
 9994:     my $answer=&reply($command,&homeserver($uname,$udom));
 9995: # log new user role if status is ok
 9996:     if ($answer eq 'ok') {
 9997: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9998:         if (($role eq 'cc') || ($role eq 'in') ||
 9999:             ($role eq 'ep') || ($role eq 'ad') ||
10000:             ($role eq 'ta') || ($role eq 'st') ||
10001:             ($role=~/^cr/) || ($role eq 'gr') ||
10002:             ($role eq 'co')) {
10003: # for course roles, perform group memberships changes triggered by role change.
10004:             unless ($role =~ /^gr/) {
10005:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10006:                                                  $origstart,$selfenroll,$context);
10007:             }
10008:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10009:                            $selfenroll,$context);
10010:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10011:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10012:                  ($role eq 'da')) {
10013:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10014:                            $context);
10015:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10016:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10017:                              $context); 
10018:         }
10019:         if ($role eq 'cc') {
10020:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10021:         }
10022:     }
10023:     return $answer;
10024: }
10025: 
10026: sub autoupdate_coowners {
10027:     my ($url,$end,$start,$uname,$udom) = @_;
10028:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10029:     if (($cdom ne '') && ($cnum ne '')) {
10030:         my $now = time;
10031:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10032:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10033:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10034:             my $instcode = $coursehash{'internal.coursecode'};
10035:             if ($instcode ne '') {
10036:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10037:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10038:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10039:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10040:                         if ($result eq 'valid') {
10041:                             if ($coursehash{'internal.co-owners'}) {
10042:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10043:                                     push(@newcoowners,$coowner);
10044:                                 }
10045:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10046:                                     push(@newcoowners,$uname.':'.$udom);
10047:                                 }
10048:                                 @newcoowners = sort(@newcoowners);
10049:                             } else {
10050:                                 push(@newcoowners,$uname.':'.$udom);
10051:                             }
10052:                         } else {
10053:                             if ($coursehash{'internal.co-owners'}) {
10054:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10055:                                     unless ($coowner eq $uname.':'.$udom) {
10056:                                         push(@newcoowners,$coowner);
10057:                                     }
10058:                                 }
10059:                                 unless (@newcoowners > 0) {
10060:                                     $delcoowners = 1;
10061:                                     $coowners = '';
10062:                                 }
10063:                             }
10064:                         }
10065:                         if (@newcoowners || $delcoowners) {
10066:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10067:                                             $delcoowners,@newcoowners);
10068:                         }
10069:                     }
10070:                 }
10071:             }
10072:         }
10073:     }
10074: }
10075: 
10076: sub store_coowners {
10077:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10078:     my $cid = $cdom.'_'.$cnum;
10079:     my ($coowners,$delresult,$putresult);
10080:     if (@newcoowners) {
10081:         $coowners = join(',',@newcoowners);
10082:         my %coownershash = (
10083:                             'internal.co-owners' => $coowners,
10084:                            );
10085:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10086:         if ($putresult eq 'ok') {
10087:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10088:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10089:             }
10090:         }
10091:     }
10092:     if ($delcoowners) {
10093:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10094:         if ($delresult eq 'ok') {
10095:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10096:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10097:             }
10098:         }
10099:     }
10100:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10101:         my %crsinfo =
10102:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10103:         if (ref($crsinfo{$cid}) eq 'HASH') {
10104:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10105:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10106:         }
10107:     }
10108: }
10109: 
10110: # -------------------------------------------------- Modify user authentication
10111: # Overrides without validation
10112: 
10113: sub modifyuserauth {
10114:     my ($udom,$uname,$umode,$upass)=@_;
10115:     my $uhome=&homeserver($uname,$udom);
10116:     my $allowed;
10117:     if (&allowed('mau',$udom)) {
10118:         $allowed = 1;
10119:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10120:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10121:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10122:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10123:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10124:         if (($cdom ne '') && ($cnum ne '')) {
10125:             my $is_owner = &is_course_owner($cdom,$cnum);
10126:             if ($is_owner) {
10127:                 $allowed = 1;
10128:             }
10129:         }
10130:     }
10131:     unless ($allowed) { return 'refused'; }
10132:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10133:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10134:              ' in domain '.$env{'request.role.domain'});  
10135:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10136: 		     &escape($upass),$uhome);
10137:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10138:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10139:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10140:     &log($udom,,$uname,$uhome,
10141:         'Authentication changed by '.$env{'user.domain'}.', '.
10142:                                      $env{'user.name'}.', '.$umode.
10143:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10144:     unless ($reply eq 'ok') {
10145:         &logthis('Authentication mode error: '.$reply);
10146: 	return 'error: '.$reply;
10147:     }   
10148:     return 'ok';
10149: }
10150: 
10151: # --------------------------------------------------------------- Modify a user
10152: 
10153: sub modifyuser {
10154:     my ($udom,    $uname, $uid,
10155:         $umode,   $upass, $first,
10156:         $middle,  $last,  $gene,
10157:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10158:     $udom= &LONCAPA::clean_domain($udom);
10159:     $uname=&LONCAPA::clean_username($uname);
10160:     my $showcandelete = 'none';
10161:     if (ref($candelete) eq 'ARRAY') {
10162:         if (@{$candelete} > 0) {
10163:             $showcandelete = join(', ',@{$candelete});
10164:         }
10165:     }
10166:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10167:              $umode.', '.$first.', '.$middle.', '.
10168: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10169:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10170:                                      ' desiredhome not specified'). 
10171:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10172:              ' in domain '.$env{'request.role.domain'});
10173:     my $uhome=&homeserver($uname,$udom,'true');
10174:     my $newuser;
10175:     if ($uhome eq 'no_host') {
10176:         $newuser = 1;
10177:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10178:                 ($umode eq 'lti')) {
10179:             return 'error: more information needed to create new user';
10180:         }
10181:     }
10182: # ----------------------------------------------------------------- Create User
10183:     if (($uhome eq 'no_host') && 
10184: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10185:         my $unhome='';
10186:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10187:             $unhome = $desiredhome;
10188: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10189: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10190:         } else { # load balancing routine for determining $unhome
10191:             my $loadm=10000000;
10192: 	    my %servers = &get_servers($udom,'library');
10193: 	    foreach my $tryserver (keys(%servers)) {
10194: 		my $answer=reply('load',$tryserver);
10195: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10196: 		    $loadm=$answer;
10197: 		    $unhome=$tryserver;
10198: 		}
10199: 	    }
10200:         }
10201:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10202: 	    return 'error: unable to find a home server for '.$uname.
10203:                    ' in domain '.$udom;
10204:         }
10205:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10206:                          &escape($upass),$unhome);
10207: 	unless ($reply eq 'ok') {
10208:             return 'error: '.$reply;
10209:         }   
10210:         $uhome=&homeserver($uname,$udom,'true');
10211:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10212: 	    return 'error: unable verify users home machine.';
10213:         }
10214:     }   # End of creation of new user
10215: # ---------------------------------------------------------------------- Add ID
10216:     if ($uid) {
10217:        $uid=~tr/A-Z/a-z/;
10218:        my %uidhash=&idrget($udom,$uname);
10219:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10220:          && (!$forceid)) {
10221: 	  unless ($uid eq $uidhash{$uname}) {
10222: 	      return 'error: user id "'.$uid.'" does not match '.
10223:                   'current user id "'.$uidhash{$uname}.'".';
10224:           }
10225:        } else {
10226: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10227:        }
10228:     }
10229: # -------------------------------------------------------------- Add names, etc
10230:     my @tmp=&get('environment',
10231: 		   ['firstname','middlename','lastname','generation','id',
10232:                     'permanentemail','inststatus'],
10233: 		   $udom,$uname);
10234:     my (%names,%oldnames);
10235:     if ($tmp[0] =~ m/^error:.*/) { 
10236:         %names=(); 
10237:     } else {
10238:         %names = @tmp;
10239:         %oldnames = %names;
10240:     }
10241: #
10242: # If name, email and/or uid are blank (e.g., because an uploaded file
10243: # of users did not contain them), do not overwrite existing values
10244: # unless field is in $candelete array ref.  
10245: #
10246: 
10247:     my @fields = ('firstname','middlename','lastname','generation',
10248:                   'permanentemail','id');
10249:     my %newvalues;
10250:     if (ref($candelete) eq 'ARRAY') {
10251:         foreach my $field (@fields) {
10252:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10253:                 if ($field eq 'firstname') {
10254:                     $names{$field} = $first;
10255:                 } elsif ($field eq 'middlename') {
10256:                     $names{$field} = $middle;
10257:                 } elsif ($field eq 'lastname') {
10258:                     $names{$field} = $last;
10259:                 } elsif ($field eq 'generation') { 
10260:                     $names{$field} = $gene;
10261:                 } elsif ($field eq 'permanentemail') {
10262:                     $names{$field} = $email;
10263:                 } elsif ($field eq 'id') {
10264:                     $names{$field}  = $uid;
10265:                 }
10266:             }
10267:         }
10268:     }
10269:     if ($first)  { $names{'firstname'}  = $first; }
10270:     if (defined($middle)) { $names{'middlename'} = $middle; }
10271:     if ($last)   { $names{'lastname'}   = $last; }
10272:     if (defined($gene))   { $names{'generation'} = $gene; }
10273:     if ($email) {
10274:        $email=~s/[^\w\@\.\-\,]//gs;
10275:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10276:     }
10277:     if ($uid) { $names{'id'}  = $uid; }
10278:     if (defined($inststatus)) {
10279:         $names{'inststatus'} = '';
10280:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10281:         if (ref($usertypes) eq 'HASH') {
10282:             my @okstatuses; 
10283:             foreach my $item (split(/:/,$inststatus)) {
10284:                 if (defined($usertypes->{$item})) {
10285:                     push(@okstatuses,$item);  
10286:                 }
10287:             }
10288:             if (@okstatuses) {
10289:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10290:             }
10291:         }
10292:     }
10293:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10294:                  $umode.', '.$first.', '.$middle.', '.
10295:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10296:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10297:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10298:     } else {
10299:         $logmsg .= ' during self creation';
10300:     }
10301:     my $changed;
10302:     if ($newuser) {
10303:         $changed = 1;
10304:     } else {
10305:         foreach my $field (@fields) {
10306:             if ($names{$field} ne $oldnames{$field}) {
10307:                 $changed = 1;
10308:                 last;
10309:             }
10310:         }
10311:     }
10312:     unless ($changed) {
10313:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10314:         &logthis($logmsg);
10315:         return 'ok';
10316:     }
10317:     my $reply = &put('environment', \%names, $udom,$uname);
10318:     if ($reply ne 'ok') { 
10319:         return 'error: '.$reply;
10320:     }
10321:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10322:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10323:     }
10324:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10325:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10326:     $logmsg = 'Success modifying user '.$logmsg;
10327:     &logthis($logmsg);
10328:     return 'ok';
10329: }
10330: 
10331: # -------------------------------------------------------------- Modify student
10332: 
10333: sub modifystudent {
10334:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10335:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10336:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10337:     if (!$cid) {
10338: 	unless ($cid=$env{'request.course.id'}) {
10339: 	    return 'not_in_class';
10340: 	}
10341:     }
10342: # --------------------------------------------------------------- Make the user
10343:     my $reply=&modifyuser
10344: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10345:          $desiredhome,$email,$inststatus);
10346:     unless ($reply eq 'ok') { return $reply; }
10347:     # This will cause &modify_student_enrollment to get the uid from the
10348:     # student's environment
10349:     $uid = undef if (!$forceid);
10350:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10351:                                         $gene,$usec,$end,$start,$type,$locktype,
10352:                                         $cid,$selfenroll,$context,$credits,$instsec);
10353:     return $reply;
10354: }
10355: 
10356: sub modify_student_enrollment {
10357:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10358:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10359:     my ($cdom,$cnum,$chome);
10360:     if (!$cid) {
10361: 	unless ($cid=$env{'request.course.id'}) {
10362: 	    return 'not_in_class';
10363: 	}
10364: 	$cdom=$env{'course.'.$cid.'.domain'};
10365: 	$cnum=$env{'course.'.$cid.'.num'};
10366:     } else {
10367: 	($cdom,$cnum)=split(/_/,$cid);
10368:     }
10369:     $chome=$env{'course.'.$cid.'.home'};
10370:     if (!$chome) {
10371: 	$chome=&homeserver($cnum,$cdom);
10372:     }
10373:     if (!$chome) { return 'unknown_course'; }
10374:     # Make sure the user exists
10375:     my $uhome=&homeserver($uname,$udom);
10376:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10377: 	return 'error: no such user';
10378:     }
10379:     # Get student data if we were not given enough information
10380:     if (!defined($first)  || $first  eq '' || 
10381:         !defined($last)   || $last   eq '' || 
10382:         !defined($uid)    || $uid    eq '' || 
10383:         !defined($middle) || $middle eq '' || 
10384:         !defined($gene)   || $gene   eq '') {
10385:         # They did not supply us with enough data to enroll the student, so
10386:         # we need to pick up more information.
10387:         my %tmp = &get('environment',
10388:                        ['firstname','middlename','lastname', 'generation','id']
10389:                        ,$udom,$uname);
10390: 
10391:         #foreach my $key (keys(%tmp)) {
10392:         #    &logthis("key $key = ".$tmp{$key});
10393:         #}
10394:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10395:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10396:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10397:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10398:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10399:     }
10400:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10401:     my $user = "$uname:$udom";
10402:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10403:     my $reply=cput('classlist',
10404: 		   {$user => 
10405: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10406: 		   $cdom,$cnum);
10407:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10408:         &devalidate_getsection_cache($udom,$uname,$cid);
10409:     } else { 
10410: 	return 'error: '.$reply;
10411:     }
10412:     # Add student role to user
10413:     my $uurl='/'.$cid;
10414:     $uurl=~s/\_/\//g;
10415:     if ($usec) {
10416: 	$uurl.='/'.$usec;
10417:     }
10418:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10419:                              $selfenroll,$context);
10420:     if ($result ne 'ok') {
10421:         if ($old_entry{$user} ne '') {
10422:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10423:         } else {
10424:             $reply = &del('classlist',[$user],$cdom,$cnum);
10425:         }
10426:     }
10427:     return $result; 
10428: }
10429: 
10430: sub format_name {
10431:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10432:     my $name;
10433:     if ($first ne 'lastname') {
10434: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10435:     } else {
10436: 	if ($lastname=~/\S/) {
10437: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10438: 	    $name=~s/\s+,/,/;
10439: 	} else {
10440: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10441: 	}
10442:     }
10443:     $name=~s/^\s+//;
10444:     $name=~s/\s+$//;
10445:     $name=~s/\s+/ /g;
10446:     return $name;
10447: }
10448: 
10449: # ------------------------------------------------- Write to course preferences
10450: 
10451: sub writecoursepref {
10452:     my ($courseid,%prefs)=@_;
10453:     $courseid=~s/^\///;
10454:     $courseid=~s/\_/\//g;
10455:     my ($cdomain,$cnum)=split(/\//,$courseid);
10456:     my $chome=homeserver($cnum,$cdomain);
10457:     if (($chome eq '') || ($chome eq 'no_host')) { 
10458: 	return 'error: no such course';
10459:     }
10460:     my $cstring='';
10461:     foreach my $pref (keys(%prefs)) {
10462: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10463:     }
10464:     $cstring=~s/\&$//;
10465:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10466: }
10467: 
10468: # ---------------------------------------------------------- Make/modify course
10469: 
10470: sub createcourse {
10471:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10472:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10473:     $url=&declutter($url);
10474:     my $cid='';
10475:     if ($context eq 'requestcourses') {
10476:         my $can_create = 0;
10477:         my ($ownername,$ownerdom) = split(':',$course_owner);
10478:         if ($udom eq $ownerdom) {
10479:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10480:                                   $context)) {
10481:                 $can_create = 1;
10482:             }
10483:         } else {
10484:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10485:                                            $category);
10486:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10487:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10488:                 if (@curr > 0) {
10489:                     my @options = qw(approval validate autolimit);
10490:                     my $optregex = join('|',@options);
10491:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10492:                         $can_create = 1;
10493:                     }
10494:                 }
10495:             }
10496:         }
10497:         if ($can_create) {
10498:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10499:                 unless (&allowed('ccc',$udom)) {
10500:                     return 'refused'; 
10501:                 }
10502:             }
10503:         } else {
10504:             return 'refused';
10505:         }
10506:     } elsif (!&allowed('ccc',$udom)) {
10507:         return 'refused';
10508:     }
10509: # --------------------------------------------------------------- Get Unique ID
10510:     my $uname;
10511:     if ($cnum =~ /^$match_courseid$/) {
10512:         my $chome=&homeserver($cnum,$udom,'true');
10513:         if (($chome eq '') || ($chome eq 'no_host')) {
10514:             $uname = $cnum;
10515:         } else {
10516:             $uname = &generate_coursenum($udom,$crstype);
10517:         }
10518:     } else {
10519:         $uname = &generate_coursenum($udom,$crstype);
10520:     }
10521:     return $uname if ($uname =~ /^error/);
10522: # -------------------------------------------------- Check supplied server name
10523:     if (!defined($course_server)) {
10524:         if (defined(&domain($udom,'primary'))) {
10525:             $course_server = &domain($udom,'primary');
10526:         } else {
10527:             $course_server = $env{'user.home'}; 
10528:         }
10529:     }
10530:     my %host_servers =
10531:         &Apache::lonnet::get_servers($udom,'library');
10532:     unless ($host_servers{$course_server}) {
10533:         return 'error: invalid home server for course: '.$course_server;
10534:     }
10535: # ------------------------------------------------------------- Make the course
10536:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10537:                       $course_server);
10538:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10539:     my $uhome=&homeserver($uname,$udom,'true');
10540:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10541: 	return 'error: no such course';
10542:     }
10543: # ----------------------------------------------------------------- Course made
10544: # log existence
10545:     my $now = time;
10546:     my $newcourse = {
10547:                     $udom.'_'.$uname => {
10548:                                      description => $description,
10549:                                      inst_code   => $inst_code,
10550:                                      owner       => $course_owner,
10551:                                      type        => $crstype,
10552:                                      creator     => $env{'user.name'}.':'.
10553:                                                     $env{'user.domain'},
10554:                                      created     => $now,
10555:                                      context     => $context,
10556:                                                 },
10557:                     };
10558:     &courseidput($udom,$newcourse,$uhome,'notime');
10559: # set toplevel url
10560:     my $topurl=$url;
10561:     unless ($nonstandard) {
10562: # ------------------------------------------ For standard courses, make top url
10563:         my $mapurl=&clutter($url);
10564:         if ($mapurl eq '/res/') { $mapurl=''; }
10565:         $env{'form.initmap'}=(<<ENDINITMAP);
10566: <map>
10567: <resource id="1" type="start"></resource>
10568: <resource id="2" src="$mapurl"></resource>
10569: <resource id="3" type="finish"></resource>
10570: <link index="1" from="1" to="2"></link>
10571: <link index="2" from="2" to="3"></link>
10572: </map>
10573: ENDINITMAP
10574:         $topurl=&declutter(
10575:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10576:                           );
10577:     }
10578: # ----------------------------------------------------------- Write preferences
10579:     &writecoursepref($udom.'_'.$uname,
10580:                      ('description'              => $description,
10581:                       'url'                      => $topurl,
10582:                       'internal.creator'         => $env{'user.name'}.':'.
10583:                                                     $env{'user.domain'},
10584:                       'internal.created'         => $now,
10585:                       'internal.creationcontext' => $context)
10586:                     );
10587:     return '/'.$udom.'/'.$uname;
10588: }
10589: 
10590: # ------------------------------------------------------------------- Create ID
10591: sub generate_coursenum {
10592:     my ($udom,$crstype) = @_;
10593:     my $domdesc = &domain($udom);
10594:     return 'error: invalid domain' if ($domdesc eq '');
10595:     my $first;
10596:     if ($crstype eq 'Community') {
10597:         $first = '0';
10598:     } else {
10599:         $first = int(1+rand(9)); 
10600:     } 
10601:     my $uname=$first.
10602:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10603:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10604:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10605: # ----------------------------------------------- Make sure that does not exist
10606:     my $uhome=&homeserver($uname,$udom,'true');
10607:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10608:         if ($crstype eq 'Community') {
10609:             $first = '0';
10610:         } else {
10611:             $first = int(1+rand(9));
10612:         }
10613:         $uname=$first.
10614:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10615:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10616:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10617:         $uhome=&homeserver($uname,$udom,'true');
10618:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10619:             return 'error: unable to generate unique course-ID';
10620:         }
10621:     }
10622:     return $uname;
10623: }
10624: 
10625: sub is_course {
10626:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10627:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10628: 
10629:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10630:     my $uhome=&homeserver($cnum,$cdom);
10631:     my $iscourse;
10632:     if (grep { $_ eq $uhome } current_machine_ids()) {
10633:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10634:     } else {
10635:         my $hashid = $cdom.':'.$cnum;
10636:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10637:         unless (defined($cached)) {
10638:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10639:                                         $cnum,undef,undef,'.');
10640:             $iscourse = 0;
10641:             if (exists($courses{$cdom.'_'.$cnum})) {
10642:                 $iscourse = 1;
10643:             }
10644:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10645:         }
10646:     }
10647:     return unless ($iscourse);
10648:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10649: }
10650: 
10651: sub store_userdata {
10652:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10653:     my $result;
10654:     if ($datakey ne '') {
10655:         if (ref($storehash) eq 'HASH') {
10656:             if ($udom eq '' || $uname eq '') {
10657:                 $udom = $env{'user.domain'};
10658:                 $uname = $env{'user.name'};
10659:             }
10660:             my $uhome=&homeserver($uname,$udom);
10661:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10662:                 $result = 'error: no_host';
10663:             } else {
10664:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10665:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10666: 
10667:                 my $namevalue='';
10668:                 foreach my $key (keys(%{$storehash})) {
10669:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10670:                 }
10671:                 $namevalue=~s/\&$//;
10672:                 unless ($namespace eq 'courserequests') {
10673:                     $datakey = &escape($datakey);
10674:                 }
10675:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10676:                                   $namevalue,$uhome);
10677:             }
10678:         } else {
10679:             $result = 'error: data to store was not a hash reference'; 
10680:         }
10681:     } else {
10682:         $result= 'error: invalid requestkey'; 
10683:     }
10684:     return $result;
10685: }
10686: 
10687: # ---------------------------------------------------------- Assign Custom Role
10688: 
10689: sub assigncustomrole {
10690:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10691:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10692:                        $end,$start,$deleteflag,$selfenroll,$context);
10693: }
10694: 
10695: # ----------------------------------------------------------------- Revoke Role
10696: 
10697: sub revokerole {
10698:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10699:     my $now=time;
10700:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10701: }
10702: 
10703: # ---------------------------------------------------------- Revoke Custom Role
10704: 
10705: sub revokecustomrole {
10706:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10707:     my $now=time;
10708:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10709:            $deleteflag,$selfenroll,$context);
10710: }
10711: 
10712: # ------------------------------------------------------------ Disk usage
10713: sub diskusage {
10714:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10715:     $directorypath =~ s/\/$//;
10716:     my $listing=&reply('du2:'.&escape($directorypath).':'
10717:                        .&escape($getpropath).':'.&escape($uname).':'
10718:                        .&escape($udom),homeserver($uname,$udom));
10719:     if ($listing eq 'unknown_cmd') {
10720:         if ($getpropath) {
10721:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10722:         }
10723:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10724:     }
10725:     return $listing;
10726: }
10727: 
10728: sub is_locked {
10729:     my ($file_name, $domain, $user, $which) = @_;
10730:     my @check;
10731:     my $is_locked;
10732:     push (@check,$file_name);
10733:     my %locked = &get('file_permissions',\@check,
10734: 		      $env{'user.domain'},$env{'user.name'});
10735:     my ($tmp)=keys(%locked);
10736:     if ($tmp=~/^error:/) { undef(%locked); }
10737:     
10738:     if (ref($locked{$file_name}) eq 'ARRAY') {
10739:         $is_locked = 'false';
10740:         foreach my $entry (@{$locked{$file_name}}) {
10741:            if (ref($entry) eq 'ARRAY') {
10742:                $is_locked = 'true';
10743:                if (ref($which) eq 'ARRAY') {
10744:                    push(@{$which},$entry);
10745:                } else {
10746:                    last;
10747:                }
10748:            }
10749:        }
10750:     } else {
10751:         $is_locked = 'false';
10752:     }
10753:     return $is_locked;
10754: }
10755: 
10756: sub declutter_portfile {
10757:     my ($file) = @_;
10758:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10759:     return $file;
10760: }
10761: 
10762: # ------------------------------------------------------------- Mark as Read Only
10763: 
10764: sub mark_as_readonly {
10765:     my ($domain,$user,$files,$what) = @_;
10766:     my %current_permissions = &dump('file_permissions',$domain,$user);
10767:     my ($tmp)=keys(%current_permissions);
10768:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10769:     foreach my $file (@{$files}) {
10770: 	$file = &declutter_portfile($file);
10771:         push(@{$current_permissions{$file}},$what);
10772:     }
10773:     &put('file_permissions',\%current_permissions,$domain,$user);
10774:     return;
10775: }
10776: 
10777: # ------------------------------------------------------------Save Selected Files
10778: 
10779: sub save_selected_files {
10780:     my ($user, $path, @files) = @_;
10781:     my $filename = $user."savedfiles";
10782:     my @other_files = &files_not_in_path($user, $path);
10783:     open (OUT,'>',LONCAPA::tempdir().$filename);
10784:     foreach my $file (@files) {
10785:         print (OUT $env{'form.currentpath'}.$file."\n");
10786:     }
10787:     foreach my $file (@other_files) {
10788:         print (OUT $file."\n");
10789:     }
10790:     close (OUT);
10791:     return 'ok';
10792: }
10793: 
10794: sub clear_selected_files {
10795:     my ($user) = @_;
10796:     my $filename = $user."savedfiles";
10797:     open (OUT,'>',LONCAPA::tempdir().$filename);
10798:     print (OUT undef);
10799:     close (OUT);
10800:     return ("ok");    
10801: }
10802: 
10803: sub files_in_path {
10804:     my ($user, $path) = @_;
10805:     my $filename = $user."savedfiles";
10806:     my %return_files;
10807:     open (IN,'<',LONCAPA::tempdir().$filename);
10808:     while (my $line_in = <IN>) {
10809:         chomp ($line_in);
10810:         my @paths_and_file = split (m!/!, $line_in);
10811:         my $file_part = pop (@paths_and_file);
10812:         my $path_part = join ('/', @paths_and_file);
10813:         $path_part.='/';
10814:         my $path_and_file = $path_part.$file_part;
10815:         if ($path_part eq $path) {
10816:             $return_files{$file_part}= 'selected';
10817:         }
10818:     }
10819:     close (IN);
10820:     return (\%return_files);
10821: }
10822: 
10823: # called in portfolio select mode, to show files selected NOT in current directory
10824: sub files_not_in_path {
10825:     my ($user, $path) = @_;
10826:     my $filename = $user."savedfiles";
10827:     my @return_files;
10828:     my $path_part;
10829:     open(IN, '<',LONCAPA::tempdir().$filename);
10830:     while (my $line = <IN>) {
10831:         #ok, I know it's clunky, but I want it to work
10832:         my @paths_and_file = split(m|/|, $line);
10833:         my $file_part = pop(@paths_and_file);
10834:         chomp($file_part);
10835:         my $path_part = join('/', @paths_and_file);
10836:         $path_part .= '/';
10837:         my $path_and_file = $path_part.$file_part;
10838:         if ($path_part ne $path) {
10839:             push(@return_files, ($path_and_file));
10840:         }
10841:     }
10842:     close(OUT);
10843:     return (@return_files);
10844: }
10845: 
10846: #------------------------------Submitted/Handedback Portfolio Files Versioning
10847:  
10848: sub portfiles_versioning {
10849:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10850:     my $portfolio_root = '/userfiles/portfolio';
10851:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10852:     foreach my $file (@{$portfiles}) {
10853:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10854:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10855:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10856:         my $getpropath = 1;
10857:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10858:                                              $stu_name,$getpropath);
10859:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10860:         my $new_answer = 
10861:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10862:         if ($new_answer ne 'problem getting file') {
10863:             push(@{$versioned_portfiles}, $directory.$new_answer);
10864:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10865:                               [$symb,$env{'request.course.id'},'graded']);
10866:         }
10867:     }
10868: }
10869: 
10870: sub get_next_version {
10871:     my ($answer_name, $answer_ext, $dir_list) = @_;
10872:     my $version;
10873:     if (ref($dir_list) eq 'ARRAY') {
10874:         foreach my $row (@{$dir_list}) {
10875:             my ($file) = split(/\&/,$row,2);
10876:             my ($file_name,$file_version,$file_ext) =
10877:                 &file_name_version_ext($file);
10878:             if (($file_name eq $answer_name) &&
10879:                 ($file_ext eq $answer_ext)) {
10880:                      # gets here if filename and extension match,
10881:                      # regardless of version
10882:                 if ($file_version ne '') {
10883:                     # a versioned file is found  so save it for later
10884:                     if ($file_version > $version) {
10885:                         $version = $file_version;
10886:                     }
10887:                 }
10888:             }
10889:         }
10890:     }
10891:     $version ++;
10892:     return($version);
10893: }
10894: 
10895: sub version_selected_portfile {
10896:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10897:     my ($answer_name,$answer_ver,$answer_ext) =
10898:         &file_name_version_ext($file_name);
10899:     my $new_answer;
10900:     $env{'form.copy'} =
10901:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10902:     if($env{'form.copy'} eq '-1') {
10903:         $new_answer = 'problem getting file';
10904:     } else {
10905:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10906:         my $copy_result = 
10907:             &finishuserfileupload($stu_name,$domain,'copy',
10908:                                   '/portfolio'.$directory.$new_answer);
10909:     }
10910:     undef($env{'form.copy'});
10911:     return ($new_answer);
10912: }
10913: 
10914: sub file_name_version_ext {
10915:     my ($file)=@_;
10916:     my @file_parts = split(/\./, $file);
10917:     my ($name,$version,$ext);
10918:     if (@file_parts > 1) {
10919:         $ext=pop(@file_parts);
10920:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10921:             $version=pop(@file_parts);
10922:         }
10923:         $name=join('.',@file_parts);
10924:     } else {
10925:         $name=join('.',@file_parts);
10926:     }
10927:     return($name,$version,$ext);
10928: }
10929: 
10930: #----------------------------------------------Get portfolio file permissions
10931: 
10932: sub get_portfile_permissions {
10933:     my ($domain,$user) = @_;
10934:     my %current_permissions = &dump('file_permissions',$domain,$user);
10935:     my ($tmp)=keys(%current_permissions);
10936:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10937:     return \%current_permissions;
10938: }
10939: 
10940: #---------------------------------------------Get portfolio file access controls
10941: 
10942: sub get_access_controls {
10943:     my ($current_permissions,$group,$file) = @_;
10944:     my %access;
10945:     my $real_file = $file;
10946:     $file =~ s/\.meta$//;
10947:     if (defined($file)) {
10948:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10949:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10950:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10951:             }
10952:         }
10953:     } else {
10954:         foreach my $key (keys(%{$current_permissions})) {
10955:             if ($key =~ /\0accesscontrol$/) {
10956:                 if (defined($group)) {
10957:                     if ($key !~ m-^\Q$group\E/-) {
10958:                         next;
10959:                     }
10960:                 }
10961:                 my ($fullpath) = split(/\0/,$key);
10962:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10963:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10964:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10965:                     }
10966:                 }
10967:             }
10968:         }
10969:     }
10970:     return %access;
10971: }
10972: 
10973: sub modify_access_controls {
10974:     my ($file_name,$changes,$domain,$user)=@_;
10975:     my ($outcome,$deloutcome);
10976:     my %store_permissions;
10977:     my %new_values;
10978:     my %new_control;
10979:     my %translation;
10980:     my @deletions = ();
10981:     my $now = time;
10982:     if (exists($$changes{'activate'})) {
10983:         if (ref($$changes{'activate'}) eq 'HASH') {
10984:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10985:             my $numnew = scalar(@newitems);
10986:             for (my $i=0; $i<$numnew; $i++) {
10987:                 my $newkey = $newitems[$i];
10988:                 my $newid = &Apache::loncommon::get_cgi_id();
10989:                 if ($newkey =~ /^\d+:/) { 
10990:                     $newkey =~ s/^(\d+)/$newid/;
10991:                     $translation{$1} = $newid;
10992:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10993:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10994:                     $translation{$1} = $newid;
10995:                 }
10996:                 $new_values{$file_name."\0".$newkey} = 
10997:                                           $$changes{'activate'}{$newitems[$i]};
10998:                 $new_control{$newkey} = $now;
10999:             }
11000:         }
11001:     }
11002:     my %todelete;
11003:     my %changed_items;
11004:     foreach my $action ('delete','update') {
11005:         if (exists($$changes{$action})) {
11006:             if (ref($$changes{$action}) eq 'HASH') {
11007:                 foreach my $key (keys(%{$$changes{$action}})) {
11008:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11009:                     if ($action eq 'delete') { 
11010:                         $todelete{$itemnum} = 1;
11011:                     } else {
11012:                         $changed_items{$itemnum} = $key;
11013:                     }
11014:                 }
11015:             }
11016:         }
11017:     }
11018:     # get lock on access controls for file.
11019:     my $lockhash = {
11020:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11021:                                                        ':'.$env{'user.domain'},
11022:                    }; 
11023:     my $tries = 0;
11024:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11025:    
11026:     while (($gotlock ne 'ok') && $tries < 10) {
11027:         $tries ++;
11028:         sleep(0.1);
11029:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11030:     }
11031:     if ($gotlock eq 'ok') {
11032:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11033:         my ($tmp)=keys(%curr_permissions);
11034:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11035:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11036:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11037:             if (ref($curr_controls) eq 'HASH') {
11038:                 foreach my $control_item (keys(%{$curr_controls})) {
11039:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11040:                     if (defined($todelete{$itemnum})) {
11041:                         push(@deletions,$file_name."\0".$control_item);
11042:                     } else {
11043:                         if (defined($changed_items{$itemnum})) {
11044:                             $new_control{$changed_items{$itemnum}} = $now;
11045:                             push(@deletions,$file_name."\0".$control_item);
11046:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11047:                         } else {
11048:                             $new_control{$control_item} = $$curr_controls{$control_item};
11049:                         }
11050:                     }
11051:                 }
11052:             }
11053:         }
11054:         my ($group);
11055:         if (&is_course($domain,$user)) {
11056:             ($group,my $file) = split(/\//,$file_name,2);
11057:         }
11058:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11059:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11060:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11061:         #  remove lock
11062:         my @del_lock = ($file_name."\0".'locked_access_records');
11063:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11064:         my $sqlresult =
11065:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11066:                                     $group);
11067:     } else {
11068:         $outcome = "error: could not obtain lockfile\n";  
11069:     }
11070:     return ($outcome,$deloutcome,\%new_values,\%translation);
11071: }
11072: 
11073: sub make_public_indefinitely {
11074:     my (@requrl) = @_;
11075:     return &automated_portfile_access('public',\@requrl);
11076: }
11077: 
11078: sub automated_portfile_access {
11079:     my ($accesstype,$addsref,$delsref,$info) = @_;
11080:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11081:         return 'invalid';
11082:     }
11083:     my %urls;
11084:     if (ref($addsref) eq 'ARRAY') {
11085:         foreach my $requrl (@{$addsref}) {
11086:             if (&is_portfolio_url($requrl)) {
11087:                 unless (exists($urls{$requrl})) {
11088:                     $urls{$requrl} = 'add';
11089:                 }
11090:             }
11091:         }
11092:     }
11093:     if (ref($delsref) eq 'ARRAY') {
11094:         foreach my $requrl (@{$delsref}) { 
11095:             if (&is_portfolio_url($requrl)) {
11096:                 unless (exists($urls{$requrl})) {
11097:                     $urls{$requrl} = 'delete'; 
11098:                 }
11099:             }
11100:         }
11101:     }
11102:     unless (keys(%urls)) {
11103:         return 'invalid';
11104:     }
11105:     my $ip;
11106:     if ($accesstype eq 'ip') {
11107:         if (ref($info) eq 'HASH') {
11108:             if ($info->{'ip'} ne '') {
11109:                 $ip = $info->{'ip'};
11110:             }
11111:         }
11112:         if ($ip eq '') {
11113:             return 'invalid';
11114:         }
11115:     }
11116:     my $errors;
11117:     my $now = time;
11118:     my %current_perms;
11119:     foreach my $requrl (sort(keys(%urls))) {
11120:         my $action;
11121:         if ($urls{$requrl} eq 'add') {
11122:             $action = 'activate';
11123:         } else {
11124:             $action = 'none';
11125:         }
11126:         my $aclnum = 0;
11127:         my (undef,$udom,$unum,$file_name,$group) =
11128:             &parse_portfolio_url($requrl);
11129:         unless (exists($current_perms{$unum.':'.$udom})) {
11130:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11131:         }
11132:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11133:                                                    $group,$file_name);
11134:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11135:             my ($num,$scope,$end,$start) = 
11136:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11137:             if ($scope eq $accesstype) {
11138:                 if (($start <= $now) && ($end == 0)) {
11139:                     if ($accesstype eq 'ip') {
11140:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11141:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11142:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11143:                                     if ($urls{$requrl} eq 'add') {
11144:                                         $action = 'none';
11145:                                         last;
11146:                                     } else {
11147:                                         $action = 'delete';
11148:                                         $aclnum = $num;
11149:                                         last;
11150:                                     }
11151:                                 }
11152:                             }
11153:                         }
11154:                     } elsif ($accesstype eq 'public') {
11155:                         if ($urls{$requrl} eq 'add') {
11156:                             $action = 'none';
11157:                             last;
11158:                         } else {
11159:                             $action = 'delete';
11160:                             $aclnum = $num;
11161:                             last;
11162:                         }
11163:                     }
11164:                 } elsif ($accesstype eq 'public') {
11165:                     $action = 'update';
11166:                     $aclnum = $num;
11167:                     last;
11168:                 }
11169:             }
11170:         }
11171:         if ($action eq 'none') {
11172:             next;
11173:         } else {
11174:             my %changes;
11175:             my $newend = 0;
11176:             my $newstart = $now;
11177:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11178:             $changes{$action}{$newkey} = {
11179:                 type => $accesstype,
11180:                 time => {
11181:                     start => $newstart,
11182:                     end   => $newend,
11183:                 },
11184:             };
11185:             if ($accesstype eq 'ip') {
11186:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11187:             }
11188:             my ($outcome,$deloutcome,$new_values,$translation) =
11189:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11190:             unless ($outcome eq 'ok') {
11191:                 $errors .= $outcome.' ';
11192:             }
11193:         }
11194:     }
11195:     if ($errors) {
11196:         $errors =~ s/\s$//;
11197:         return $errors;
11198:     } else {
11199:         return 'ok';
11200:     }
11201: }
11202: 
11203: #------------------------------------------------------Get Marked as Read Only
11204: 
11205: sub get_marked_as_readonly {
11206:     my ($domain,$user,$what,$group) = @_;
11207:     my $current_permissions = &get_portfile_permissions($domain,$user);
11208:     my @readonly_files;
11209:     my $cmp1=$what;
11210:     if (ref($what)) { $cmp1=join('',@{$what}) };
11211:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11212:         if (defined($group)) {
11213:             if ($file_name !~ m-^\Q$group\E/-) {
11214:                 next;
11215:             }
11216:         }
11217:         if (ref($value) eq "ARRAY"){
11218:             foreach my $stored_what (@{$value}) {
11219:                 my $cmp2=$stored_what;
11220:                 if (ref($stored_what) eq 'ARRAY') {
11221:                     $cmp2=join('',@{$stored_what});
11222:                 }
11223:                 if ($cmp1 eq $cmp2) {
11224:                     push(@readonly_files, $file_name);
11225:                     last;
11226:                 } elsif (!defined($what)) {
11227:                     push(@readonly_files, $file_name);
11228:                     last;
11229:                 }
11230:             }
11231:         }
11232:     }
11233:     return @readonly_files;
11234: }
11235: #-----------------------------------------------------------Get Marked as Read Only Hash
11236: 
11237: sub get_marked_as_readonly_hash {
11238:     my ($current_permissions,$group,$what) = @_;
11239:     my %readonly_files;
11240:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11241:         if (defined($group)) {
11242:             if ($file_name !~ m-^\Q$group\E/-) {
11243:                 next;
11244:             }
11245:         }
11246:         if (ref($value) eq "ARRAY"){
11247:             foreach my $stored_what (@{$value}) {
11248:                 if (ref($stored_what) eq 'ARRAY') {
11249:                     foreach my $lock_descriptor(@{$stored_what}) {
11250:                         if ($lock_descriptor eq 'graded') {
11251:                             $readonly_files{$file_name} = 'graded';
11252:                         } elsif ($lock_descriptor eq 'handback') {
11253:                             $readonly_files{$file_name} = 'handback';
11254:                         } else {
11255:                             if (!exists($readonly_files{$file_name})) {
11256:                                 $readonly_files{$file_name} = 'locked';
11257:                             }
11258:                         }
11259:                     }
11260:                 } 
11261:             }
11262:         } 
11263:     }
11264:     return %readonly_files;
11265: }
11266: # ------------------------------------------------------------ Unmark as Read Only
11267: 
11268: sub unmark_as_readonly {
11269:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11270:     # for portfolio submissions, $what contains [$symb,$crsid] 
11271:     my ($domain,$user,$what,$file_name,$group) = @_;
11272:     $file_name = &declutter_portfile($file_name);
11273:     my $symb_crs = $what;
11274:     if (ref($what)) { $symb_crs=join('',@$what); }
11275:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11276:     my ($tmp)=keys(%current_permissions);
11277:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11278:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11279:     foreach my $file (@readonly_files) {
11280: 	my $clean_file = &declutter_portfile($file);
11281: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11282: 	my $current_locks = $current_permissions{$file};
11283:         my @new_locks;
11284:         my @del_keys;
11285:         if (ref($current_locks) eq "ARRAY"){
11286:             foreach my $locker (@{$current_locks}) {
11287:                 my $compare=$locker;
11288:                 if (ref($locker) eq 'ARRAY') {
11289:                     $compare=join('',@{$locker});
11290:                     if ($compare ne $symb_crs) {
11291:                         push(@new_locks, $locker);
11292:                     }
11293:                 }
11294:             }
11295:             if (scalar(@new_locks) > 0) {
11296:                 $current_permissions{$file} = \@new_locks;
11297:             } else {
11298:                 push(@del_keys, $file);
11299:                 &del('file_permissions',\@del_keys, $domain, $user);
11300:                 delete($current_permissions{$file});
11301:             }
11302:         }
11303:     }
11304:     &put('file_permissions',\%current_permissions,$domain,$user);
11305:     return;
11306: }
11307: 
11308: # ------------------------------------------------------------ Directory lister
11309: 
11310: sub dirlist {
11311:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11312:     $uri=~s/^\///;
11313:     $uri=~s/\/$//;
11314:     my ($udom, $uname);
11315:     if ($getuserdir) {
11316:         $udom = $userdomain;
11317:         $uname = $username;
11318:     } else {
11319:         (undef,$udom,$uname)=split(/\//,$uri);
11320:         if(defined($userdomain)) {
11321:             $udom = $userdomain;
11322:         }
11323:         if(defined($username)) {
11324:             $uname = $username;
11325:         }
11326:     }
11327:     my ($dirRoot,$listing,@listing_results);
11328: 
11329:     $dirRoot = $perlvar{'lonDocRoot'};
11330:     if (defined($getpropath)) {
11331:         $dirRoot = &propath($udom,$uname);
11332:         $dirRoot =~ s/\/$//;
11333:     } elsif (defined($getuserdir)) {
11334:         my $subdir=$uname.'__';
11335:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11336:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11337:                    ."/$udom/$subdir/$uname";
11338:     } elsif (defined($alternateRoot)) {
11339:         $dirRoot = $alternateRoot;
11340:     }
11341: 
11342:     if($udom) {
11343:         if($uname) {
11344:             my $uhome = &homeserver($uname,$udom);
11345:             if ($uhome eq 'no_host') {
11346:                 return ([],'no_host');
11347:             }
11348:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11349:                               .$getuserdir.':'.&escape($dirRoot)
11350:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11351:             if ($listing eq 'unknown_cmd') {
11352:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11353:             } else {
11354:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11355:             }
11356:             if ($listing eq 'unknown_cmd') {
11357:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11358:                 @listing_results = split(/:/,$listing);
11359:             } else {
11360:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11361:             }
11362:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11363:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11364:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11365:                 return ([],$listing);
11366:             } else {
11367:                 return (\@listing_results);
11368:             }
11369:         } elsif(!$alternateRoot) {
11370:             my (%allusers,%listerror);
11371: 	    my %servers = &get_servers($udom,'library');
11372:  	    foreach my $tryserver (keys(%servers)) {
11373:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11374:                                   &escape($udom),$tryserver);
11375:                 if ($listing eq 'unknown_cmd') {
11376: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11377: 				      $udom, $tryserver);
11378:                 } else {
11379:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11380:                 }
11381: 		if ($listing eq 'unknown_cmd') {
11382: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11383: 				      $udom, $tryserver);
11384: 		    @listing_results = split(/:/,$listing);
11385: 		} else {
11386: 		    @listing_results =
11387: 			map { &unescape($_); } split(/:/,$listing);
11388: 		}
11389:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11390:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11391:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11392:                     $listerror{$tryserver} = $listing;
11393:                 } else {
11394: 		    foreach my $line (@listing_results) {
11395: 			my ($entry) = split(/&/,$line,2);
11396: 			$allusers{$entry} = 1;
11397: 		    }
11398: 		}
11399:             }
11400:             my @alluserslist=();
11401:             foreach my $user (sort(keys(%allusers))) {
11402:                 push(@alluserslist,$user.'&user');
11403:             }
11404: 
11405:             if (!%listerror) {
11406:                 # no errors
11407:                 return (\@alluserslist);
11408:             } elsif (scalar(keys(%servers)) == 1) {
11409:                 # one library server, one error 
11410:                 my ($key) = keys(%listerror);
11411:                 return (\@alluserslist, $listerror{$key});
11412:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11413:                 # con_lost indicates that we might miss data from at least one
11414:                 # library server
11415:                 return (\@alluserslist, 'con_lost');
11416:             } else {
11417:                 # multiple library servers and no con_lost -> data should be
11418:                 # complete. 
11419:                 return (\@alluserslist);
11420:             }
11421: 
11422:         } else {
11423:             return ([],'missing username');
11424:         }
11425:     } elsif(!defined($getpropath)) {
11426:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11427:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11428:         return (\@all_domains);
11429:     } else {
11430:         return ([],'missing domain');
11431:     }
11432: }
11433: 
11434: # --------------------------------------------- GetFileTimestamp
11435: # This function utilizes dirlist and returns the date stamp for
11436: # when it was last modified.  It will also return an error of -1
11437: # if an error occurs
11438: 
11439: sub GetFileTimestamp {
11440:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11441:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11442:     $studentName   = &LONCAPA::clean_username($studentName);
11443:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11444:                                     undef,$getuserdir);
11445:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11446:         return -1;
11447:     }
11448:     if (ref($fileref) eq 'ARRAY') {
11449:         my @stats = split('&',$fileref->[0]);
11450:         # @stats contains first the filename, then the stat output
11451:         return $stats[10]; # so this is 10 instead of 9.
11452:     } else {
11453:         return -1;
11454:     }
11455: }
11456: 
11457: sub stat_file {
11458:     my ($uri) = @_;
11459:     $uri = &clutter_with_no_wrapper($uri);
11460: 
11461:     my ($udom,$uname,$file);
11462:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11463: 	($udom,$uname,$file) =
11464: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11465: 	$file = 'userfiles/'.$file;
11466:     }
11467:     if ($uri =~ m-^/res/-) {
11468: 	($udom,$uname) = 
11469: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11470: 	$file = $uri;
11471:     }
11472: 
11473:     if (!$udom || !$uname || !$file) {
11474: 	# unable to handle the uri
11475: 	return ();
11476:     }
11477:     my $getpropath;
11478:     if ($file =~ /^userfiles\//) {
11479:         $getpropath = 1;
11480:     }
11481:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11482:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11483:         return ();
11484:     } else {
11485:         if (ref($listref) eq 'ARRAY') {
11486:             my @stats = split('&',$listref->[0]);
11487: 	    shift(@stats); #filename is first
11488: 	    return @stats;
11489:         }
11490:     }
11491:     return ();
11492: }
11493: 
11494: # --------------------------------------------------------- recursedirs
11495: # Recursive function to traverse either a specific user's Authoring Space
11496: # or corresponding Published Resource Space, and populate the hash ref:
11497: # $dirhashref with URLs of all directories, and if $filehashref hash
11498: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11499: # or .rights files in resource space, and .meta, .save, .log, and .bak
11500: # files in Authoring Space.
11501: #
11502: # Inputs:
11503: #
11504: # $is_home - true if current server is home server for user's space
11505: # $context - either: priv, or res respectively for Authoring or Resource Space.
11506: # $docroot - Document root (i.e., /home/httpd/html
11507: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11508: # $relpath - Current path (relative to top level).
11509: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11510: # $filehashref - reference to hash to populate with URLs of files (Optional)
11511: #
11512: # Returns: nothing
11513: #
11514: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11515: #
11516: # Currently used by interface/londocs.pm to create linked select boxes for
11517: # directory and filename to import a Course "Author" resource into a course, and
11518: # also to create linked select boxes for Authoring Space and Directory to choose
11519: # save location for creation of a new "standard" problem from the Course Editor.
11520: #
11521: 
11522: sub recursedirs {
11523:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11524:     return unless (ref($dirhashref) eq 'HASH');
11525:     my $currpath = $docroot.$toppath;
11526:     if ($relpath) {
11527:         $currpath .= "/$relpath";
11528:     }
11529:     my $savefile;
11530:     if (ref($filehashref)) {
11531:         $savefile = 1;
11532:     }
11533:     if ($is_home) {
11534:         if (opendir(my $dirh,$currpath)) {
11535:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11536:                 next if ($item eq '');
11537:                 if (-d "$currpath/$item") {
11538:                     my $newpath;
11539:                     if ($relpath) {
11540:                         $newpath = "$relpath/$item";
11541:                     } else {
11542:                         $newpath = $item;
11543:                     }
11544:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11545:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11546:                 } elsif ($savefile) {
11547:                     if ($context eq 'priv') {
11548:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11549:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11550:                         }
11551:                     } else {
11552:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11553:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11554:                         }
11555:                     }
11556:                 }
11557:             }
11558:             closedir($dirh);
11559:         }
11560:     } else {
11561:         my ($dirlistref,$listerror) =
11562:             &dirlist($toppath.$relpath);
11563:         my @dir_lines;
11564:         my $dirptr=16384;
11565:         if (ref($dirlistref) eq 'ARRAY') {
11566:             foreach my $dir_line (sort
11567:                               {
11568:                                   my ($afile)=split('&',$a,2);
11569:                                   my ($bfile)=split('&',$b,2);
11570:                                   return (lc($afile) cmp lc($bfile));
11571:                               } (@{$dirlistref})) {
11572:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11573:                     split(/\&/,$dir_line,16);
11574:                 $item =~ s/\s+$//;
11575:                 next if (($item =~ /^\.\.?$/) || ($obs));
11576:                 if ($dirptr&$testdir) {
11577:                     my $newpath;
11578:                     if ($relpath) {
11579:                         $newpath = "$relpath/$item";
11580:                     } else {
11581:                         $relpath = '/';
11582:                         $newpath = $item;
11583:                     }
11584:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11585:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11586:                 } elsif ($savefile) {
11587:                     if ($context eq 'priv') {
11588:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11589:                             $filehashref->{$relpath}{$item} = 1;
11590:                         }
11591:                     } else {
11592:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11593:                             $filehashref->{$relpath}{$item} = 1;
11594:                         }
11595:                     }
11596:                 }
11597:             }
11598:         }
11599:     }
11600:     return;
11601: }
11602: 
11603: # -------------------------------------------------------- Value of a Condition
11604: 
11605: # gets the value of a specific preevaluated condition
11606: #    stored in the string  $env{user.state.<cid>}
11607: # or looks up a condition reference in the bighash and if if hasn't
11608: # already been evaluated recurses into docondval to get the value of
11609: # the condition, then memoizing it to 
11610: #   $env{user.state.<cid>.<condition>}
11611: sub directcondval {
11612:     my $number=shift;
11613:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11614: 	&Apache::lonuserstate::evalstate();
11615:     }
11616:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11617: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11618:     } elsif ($number =~ /^_/) {
11619: 	my $sub_condition;
11620: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11621: 		&GDBM_READER(),0640)) {
11622: 	    $sub_condition=$bighash{'conditions'.$number};
11623: 	    untie(%bighash);
11624: 	}
11625: 	my $value = &docondval($sub_condition);
11626: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11627: 	return $value;
11628:     }
11629:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11630:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11631:     } else {
11632:        return 2;
11633:     }
11634: }
11635: 
11636: # get the collection of conditions for this resource
11637: sub condval {
11638:     my $condidx=shift;
11639:     my $allpathcond='';
11640:     foreach my $cond (split(/\|/,$condidx)) {
11641: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11642: 	    $allpathcond.=
11643: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11644: 	}
11645:     }
11646:     $allpathcond=~s/\|$//;
11647:     return &docondval($allpathcond);
11648: }
11649: 
11650: #evaluates an expression of conditions
11651: sub docondval {
11652:     my ($allpathcond) = @_;
11653:     my $result=0;
11654:     if ($env{'request.course.id'}
11655: 	&& defined($allpathcond)) {
11656: 	my $operand='|';
11657: 	my @stack;
11658: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11659: 	    if ($chunk eq '(') {
11660: 		push @stack,($operand,$result);
11661: 	    } elsif ($chunk eq ')') {
11662: 		my $before=pop @stack;
11663: 		if (pop @stack eq '&') {
11664: 		    $result=$result>$before?$before:$result;
11665: 		} else {
11666: 		    $result=$result>$before?$result:$before;
11667: 		}
11668: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11669: 		$operand=$chunk;
11670: 	    } else {
11671: 		my $new=directcondval($chunk);
11672: 		if ($operand eq '&') {
11673: 		    $result=$result>$new?$new:$result;
11674: 		} else {
11675: 		    $result=$result>$new?$result:$new;
11676: 		}
11677: 	    }
11678: 	}
11679:     }
11680:     return $result;
11681: }
11682: 
11683: # ---------------------------------------------------- Devalidate courseresdata
11684: 
11685: sub devalidatecourseresdata {
11686:     my ($coursenum,$coursedomain)=@_;
11687:     my $hashid=$coursenum.':'.$coursedomain;
11688:     &devalidate_cache_new('courseres',$hashid);
11689: }
11690: 
11691: 
11692: # --------------------------------------------------- Course Resourcedata Query
11693: #
11694: #  Parameters:
11695: #      $coursenum    - Number of the course.
11696: #      $coursedomain - Domain at which the course was created.
11697: #  Returns:
11698: #     A hash of the course parameters along (I think) with timestamps
11699: #     and version info.
11700: 
11701: sub get_courseresdata {
11702:     my ($coursenum,$coursedomain)=@_;
11703:     my $coursehom=&homeserver($coursenum,$coursedomain);
11704:     my $hashid=$coursenum.':'.$coursedomain;
11705:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11706:     my %dumpreply;
11707:     unless (defined($cached)) {
11708: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11709: 	$result=\%dumpreply;
11710: 	my ($tmp) = keys(%dumpreply);
11711: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11712: 	    &do_cache_new('courseres',$hashid,$result,600);
11713: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11714: 	    return $tmp;
11715: 	} elsif ($tmp =~ /^(error)/) {
11716: 	    $result=undef;
11717: 	    &do_cache_new('courseres',$hashid,$result,600);
11718: 	}
11719:     }
11720:     return $result;
11721: }
11722: 
11723: sub devalidateuserresdata {
11724:     my ($uname,$udom)=@_;
11725:     my $hashid="$udom:$uname";
11726:     &devalidate_cache_new('userres',$hashid);
11727: }
11728: 
11729: sub get_userresdata {
11730:     my ($uname,$udom)=@_;
11731:     #most student don\'t have any data set, check if there is some data
11732:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11733: 
11734:     my $hashid="$udom:$uname";
11735:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11736:     if (!defined($cached)) {
11737: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11738: 	$result=\%resourcedata;
11739: 	&do_cache_new('userres',$hashid,$result,600);
11740:     }
11741:     my ($tmp)=keys(%$result);
11742:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11743: 	return $result;
11744:     }
11745:     #error 2 occurs when the .db doesn't exist
11746:     if ($tmp!~/error: 2 /) {
11747:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11748: 	    &logthis("<font color=\"blue\">WARNING:".
11749: 		     " Trying to get resource data for ".
11750: 		     $uname." at ".$udom.": ".
11751: 		     $tmp."</font>");
11752:         }
11753:     } elsif ($tmp=~/error: 2 /) {
11754: 	#&EXT_cache_set($udom,$uname);
11755: 	&do_cache_new('userres',$hashid,undef,600);
11756: 	undef($tmp); # not really an error so don't send it back
11757:     }
11758:     return $tmp;
11759: }
11760: #----------------------------------------------- resdata - return resource data
11761: #  Purpose:
11762: #    Return resource data for either users or for a course.
11763: #  Parameters:
11764: #     $name      - Course/user name.
11765: #     $domain    - Name of the domain the user/course is registered on.
11766: #     $type      - Type of thing $name is (must be 'course' or 'user')
11767: #     $mapp      - decluttered URL of enclosing map  
11768: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11769: #     $recurseup - Ref to array of map URLs, starting with map containing
11770: #                  $mapp up through hierarchy of nested maps to top level map.  
11771: #     $courseid  - CourseID (first part of param identifier).
11772: #     $modifier  - Middle part of param identifier.
11773: #     $what      - Last part of param identifier.
11774: #     @which     - Array of names of resources desired.
11775: #  Returns:
11776: #     The value of the first reasource in @which that is found in the
11777: #     resource hash.
11778: #  Exceptional Conditions:
11779: #     If the $type passed in is not valid (not the string 'course' or 
11780: #     'user', an undefined  reference is returned.
11781: #     If none of the resources are found, an undef is returned
11782: sub resdata {
11783:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11784:         $modifier,$what,@which)=@_;
11785:     my $result;
11786:     if ($type eq 'course') {
11787: 	$result=&get_courseresdata($name,$domain);
11788:     } elsif ($type eq 'user') {
11789: 	$result=&get_userresdata($name,$domain);
11790:     }
11791:     if (!ref($result)) { return $result; }    
11792:     foreach my $item (@which) {
11793:         if ($item->[1] eq 'course') {
11794:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11795:                 unless ($$recursed) {
11796:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11797:                     $$recursed = 1;
11798:                 }
11799:                 foreach my $item (@${recurseup}) {
11800:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11801:                     last if (defined($result->{$norecursechk}));
11802:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11803:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11804:                 }
11805:             }
11806:         }
11807:         if (defined($result->{$item->[0]})) {
11808: 	    return [$result->{$item->[0]},$item->[1]];
11809: 	}
11810:     }
11811:     return undef;
11812: }
11813: 
11814: sub get_domain_lti {
11815:     my ($cdom,$context) = @_;
11816:     my ($name,%lti);
11817:     if ($context eq 'consumer') {
11818:         $name = 'ltitools';
11819:     } elsif ($context eq 'provider') {
11820:         $name = 'lti';
11821:     } else {
11822:         return %lti;
11823:     }
11824:     my ($result,$cached)=&is_cached_new($name,$cdom);
11825:     if (defined($cached)) {
11826:         if (ref($result) eq 'HASH') {
11827:             %lti = %{$result};
11828:         }
11829:     } else {
11830:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11831:         if (ref($domconfig{$name}) eq 'HASH') {
11832:             %lti = %{$domconfig{$name}};
11833:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11834:             if (ref($encdomconfig{$name}) eq 'HASH') {
11835:                 foreach my $id (keys(%lti)) {
11836:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11837:                         foreach my $item ('key','secret') {
11838:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11839:                         }
11840:                     }
11841:                 }
11842:             }
11843:         }
11844:         my $cachetime = 24*60*60;
11845:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11846:     }
11847:     return %lti;
11848: }
11849: 
11850: sub get_numsuppfiles {
11851:     my ($cnum,$cdom,$ignorecache)=@_;
11852:     my $hashid=$cnum.':'.$cdom;
11853:     my ($suppcount,$cached);
11854:     unless ($ignorecache) {
11855:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11856:     }
11857:     unless (defined($cached)) {
11858:         my $chome=&homeserver($cnum,$cdom);
11859:         unless ($chome eq 'no_host') {
11860:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11861:             my $suppmap = 'supplemental.sequence';
11862:             ($suppcount,$supptools,$errors) =
11863:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11864:                                                          $supptools,$errors);
11865:         }
11866:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11867:     }
11868:     return $suppcount;
11869: }
11870: 
11871: #
11872: # EXT resource caching routines
11873: #
11874: 
11875: {
11876: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11877: #
11878: # The course for which we cache
11879: my $cachedmapkey='';
11880: # The cached recursive maps for this course
11881: my %cachedmaps=();
11882: # When this was last done
11883: my $cachedmaptime='';
11884: 
11885: sub clear_EXT_cache_status {
11886:     &delenv('cache.EXT.');
11887: }
11888: 
11889: sub EXT_cache_status {
11890:     my ($target_domain,$target_user) = @_;
11891:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11892:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11893:         # We know already the user has no data
11894:         return 1;
11895:     } else {
11896:         return 0;
11897:     }
11898: }
11899: 
11900: sub EXT_cache_set {
11901:     my ($target_domain,$target_user) = @_;
11902:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11903:     #&appenv({$cachename => time});
11904: }
11905: 
11906: # --------------------------------------------------------- Value of a Variable
11907: sub EXT {
11908: 
11909:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11910:     unless ($varname) { return ''; }
11911:     #get real user name/domain, courseid and symb
11912:     my $courseid;
11913:     my $publicuser;
11914:     if ($symbparm) {
11915: 	$symbparm=&get_symb_from_alias($symbparm);
11916:     }
11917:     if (!($uname && $udom)) {
11918:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11919:       if (!$symbparm) {	$symbparm=$cursymb; }
11920:     } else {
11921: 	$courseid=$env{'request.course.id'};
11922:     }
11923:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11924:     my $rest;
11925:     if (defined($therest[0])) {
11926:        $rest=join('.',@therest);
11927:     } else {
11928:        $rest='';
11929:     }
11930: 
11931:     my $qualifierrest=$qualifier;
11932:     if ($rest) { $qualifierrest.='.'.$rest; }
11933:     my $spacequalifierrest=$space;
11934:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11935:     if ($realm eq 'user') {
11936: # --------------------------------------------------------------- user.resource
11937: 	if ($space eq 'resource') {
11938: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11939: 		  || defined($Apache::lonhomework::parsing_a_task))
11940: 		 &&
11941: 		 ($symbparm eq &symbread()) ) {	
11942: 		# if we are in the middle of processing the resource the
11943: 		# get the value we are planning on committing
11944:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11945:                     return $Apache::lonhomework::results{$qualifierrest};
11946:                 } else {
11947:                     return $Apache::lonhomework::history{$qualifierrest};
11948:                 }
11949: 	    } else {
11950: 		my %restored;
11951: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11952: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11953: 		} else {
11954: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11955: 		}
11956: 		return $restored{$qualifierrest};
11957: 	    }
11958: # ----------------------------------------------------------------- user.access
11959:         } elsif ($space eq 'access') {
11960: 	    # FIXME - not supporting calls for a specific user
11961:             return &allowed($qualifier,$rest);
11962: # ------------------------------------------ user.preferences, user.environment
11963:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11964: 	    if (($uname eq $env{'user.name'}) &&
11965: 		($udom eq $env{'user.domain'})) {
11966: 		return $env{join('.',('environment',$qualifierrest))};
11967: 	    } else {
11968: 		my %returnhash;
11969: 		if (!$publicuser) {
11970: 		    %returnhash=&userenvironment($udom,$uname,
11971: 						 $qualifierrest);
11972: 		}
11973: 		return $returnhash{$qualifierrest};
11974: 	    }
11975: # ----------------------------------------------------------------- user.course
11976:         } elsif ($space eq 'course') {
11977: 	    # FIXME - not supporting calls for a specific user
11978:             return $env{join('.',('request.course',$qualifier))};
11979: # ------------------------------------------------------------------- user.role
11980:         } elsif ($space eq 'role') {
11981: 	    # FIXME - not supporting calls for a specific user
11982:             my ($role,$where)=split(/\./,$env{'request.role'});
11983:             if ($qualifier eq 'value') {
11984: 		return $role;
11985:             } elsif ($qualifier eq 'extent') {
11986:                 return $where;
11987:             }
11988: # ----------------------------------------------------------------- user.domain
11989:         } elsif ($space eq 'domain') {
11990:             return $udom;
11991: # ------------------------------------------------------------------- user.name
11992:         } elsif ($space eq 'name') {
11993:             return $uname;
11994: # ---------------------------------------------------- Any other user namespace
11995:         } else {
11996: 	    my %reply;
11997: 	    if (!$publicuser) {
11998: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11999: 	    }
12000: 	    return $reply{$qualifierrest};
12001:         }
12002:     } elsif ($realm eq 'query') {
12003: # ---------------------------------------------- pull stuff out of query string
12004:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12005: 						[$spacequalifierrest]);
12006: 	return $env{'form.'.$spacequalifierrest}; 
12007:    } elsif ($realm eq 'request') {
12008: # ------------------------------------------------------------- request.browser
12009:         if ($space eq 'browser') {
12010:             return $env{'browser.'.$qualifier};
12011: # ------------------------------------------------------------ request.filename
12012:         } else {
12013:             return $env{'request.'.$spacequalifierrest};
12014:         }
12015:     } elsif ($realm eq 'course') {
12016: # ---------------------------------------------------------- course.description
12017:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12018:     } elsif ($realm eq 'resource') {
12019: 
12020: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12021: 	    if (!$symbparm) { $symbparm=&symbread(); }
12022: 	}
12023: 
12024:         if ($qualifier eq '') {
12025: 	    if ($space eq 'title') {
12026: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12027: 	        return &gettitle($symbparm);
12028: 	    }
12029: 	
12030: 	    if ($space eq 'map') {
12031: 	        my ($map) = &decode_symb($symbparm);
12032: 	        return &symbread($map);
12033: 	    }
12034:             if ($space eq 'maptitle') {
12035:                 my ($map) = &decode_symb($symbparm);
12036:                 return &gettitle($map);
12037:             }
12038: 	    if ($space eq 'filename') {
12039: 	        if ($symbparm) {
12040: 		    return &clutter((&decode_symb($symbparm))[2]);
12041: 	        }
12042: 	        return &hreflocation('',$env{'request.filename'});
12043: 	    }
12044: 
12045:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12046:                 if ($space eq 'visibleparts') {
12047:                     my $navmap = Apache::lonnavmaps::navmap->new();
12048:                     my $item;
12049:                     if (ref($navmap)) {
12050:                         my $res = $navmap->getBySymb($symbparm);
12051:                         my $parts = $res->parts();
12052:                         if (ref($parts) eq 'ARRAY') {
12053:                             $item = join(',',@{$parts});
12054:                         }
12055:                         undef($navmap);
12056:                     }
12057:                     return $item;
12058:                 }
12059:             }
12060:         }
12061: 
12062: 	my ($section, $group, @groups, @recurseup, $recursed);
12063: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12064:         if (($courseid eq '') && ($cid)) {
12065:             $courseid = $cid;
12066:         }
12067: 	if (($symbparm && $courseid) && 
12068: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12069: 
12070: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12071: 
12072: # ----------------------------------------------------- Cascading lookup scheme
12073: 	    my $symbp=$symbparm;
12074: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12075: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12076:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12077: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12078: 	    if (($env{'user.name'} eq $uname) &&
12079: 		($env{'user.domain'} eq $udom)) {
12080: 		$section=$env{'request.course.sec'};
12081:                 @groups = split(/:/,$env{'request.course.groups'});  
12082:                 @groups=&sort_course_groups($courseid,@groups); 
12083: 	    } else {
12084: 		if (! defined($usection)) {
12085: 		    $section=&getsection($udom,$uname,$courseid);
12086: 		} else {
12087: 		    $section = $usection;
12088: 		}
12089:                 @groups = &get_users_groups($udom,$uname,$courseid);
12090: 	    }
12091: 
12092: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12093: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12094:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12095: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12096: 
12097: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12098: 	    my $courselevelr=$courseid.'.'.$symbparm;
12099:             $courseleveli=$courseid.'.'.$recurseparm;
12100: 	    $courselevelm=$courseid.'.'.$mapparm;
12101: 
12102: # ----------------------------------------------------------- first, check user
12103: 
12104: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12105:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12106: 				       ([$courselevelr,'resource'],
12107: 					[$courselevelm,'map'     ],
12108:                                         [$courseleveli,'map'     ],
12109: 					[$courselevel, 'course'  ]));
12110: 	    if (defined($userreply)) { return &get_reply($userreply); }
12111: 
12112: # ------------------------------------------------ second, check some of course
12113:             my $coursereply;
12114:             if (@groups > 0) {
12115:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12116:                                        $recurseparm,$mapparm,$spacequalifierrest,
12117:                                        $mapp,\$recursed,\@recurseup);
12118:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12119:             }
12120: 
12121: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12122: 				  $env{'course.'.$courseid.'.domain'},
12123: 				  'course',$mapp,\$recursed,\@recurseup,
12124:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12125: 				  ([$seclevelr,   'resource'],
12126: 				   [$seclevelm,   'map'     ],
12127:                                    [$secleveli,   'map'     ],
12128: 				   [$seclevel,    'course'  ],
12129: 				   [$courselevelr,'resource']));
12130: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12131: 
12132: # ------------------------------------------------------ third, check map parms
12133: 	    my %parmhash=();
12134: 	    my $thisparm='';
12135: 	    if (tie(%parmhash,'GDBM_File',
12136: 		    $env{'request.course.fn'}.'_parms.db',
12137: 		    &GDBM_READER(),0640)) {
12138: 		$thisparm=$parmhash{$symbparm};
12139: 		untie(%parmhash);
12140: 	    }
12141: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12142: 	}
12143: # ------------------------------------------ fourth, look in resource metadata
12144:  
12145:         my $what = $spacequalifierrest;
12146: 	$what=~s/\./\_/;
12147: 	my $filename;
12148: 	if (!$symbparm) { $symbparm=&symbread(); }
12149: 	if ($symbparm) {
12150: 	    $filename=(&decode_symb($symbparm))[2];
12151: 	} else {
12152: 	    $filename=$env{'request.filename'};
12153: 	}
12154:         my $toolsymb;
12155:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12156:             $toolsymb = $symbparm;
12157:         }
12158: 	my $metadata=&metadata($filename,$what,$toolsymb);
12159: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12160: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12161: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12162: 
12163: # ----------------------------------------------- fifth, look in rest of course
12164: 	if ($symbparm && defined($courseid) && 
12165: 	    $courseid eq $env{'request.course.id'}) {
12166: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12167: 				     $env{'course.'.$courseid.'.domain'},
12168: 				     'course',$mapp,\$recursed,\@recurseup,
12169:                                      $courseid,'.',$spacequalifierrest,
12170: 				     ([$courselevelm,'map'   ],
12171:                                       [$courseleveli,'map'   ],
12172: 				      [$courselevel, 'course']));
12173: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12174: 	}
12175: # ------------------------------------------------------------------ Cascade up
12176: 	unless ($space eq '0') {
12177: 	    my @parts=split(/_/,$space);
12178: 	    my $id=pop(@parts);
12179: 	    my $part=join('_',@parts);
12180: 	    if ($part eq '') { $part='0'; }
12181: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12182: 				 $symbparm,$udom,$uname,$section,1);
12183: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12184: 	}
12185: 	if ($recurse) { return undef; }
12186: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12187: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12188: # ---------------------------------------------------- Any other user namespace
12189:     } elsif ($realm eq 'environment') {
12190: # ----------------------------------------------------------------- environment
12191: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12192: 	    return $env{'environment.'.$spacequalifierrest};
12193: 	} else {
12194: 	    if ($uname eq 'anonymous' && $udom eq '') {
12195: 		return '';
12196: 	    }
12197: 	    my %returnhash=&userenvironment($udom,$uname,
12198: 					    $spacequalifierrest);
12199: 	    return $returnhash{$spacequalifierrest};
12200: 	}
12201:     } elsif ($realm eq 'system') {
12202: # ----------------------------------------------------------------- system.time
12203: 	if ($space eq 'time') {
12204: 	    return time;
12205:         }
12206:     } elsif ($realm eq 'server') {
12207: # ----------------------------------------------------------------- system.time
12208: 	if ($space eq 'name') {
12209: 	    return $ENV{'SERVER_NAME'};
12210:         }
12211:     }
12212:     return '';
12213: }
12214: 
12215: sub get_reply {
12216:     my ($reply_value) = @_;
12217:     if (ref($reply_value) eq 'ARRAY') {
12218:         if (wantarray) {
12219: 	    return @$reply_value;
12220:         }
12221:         return $reply_value->[0];
12222:     } else {
12223:         return $reply_value;
12224:     }
12225: }
12226: 
12227: sub check_group_parms {
12228:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12229:         $recursed,$recurseupref) = @_;
12230:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12231:                   [$what,'course']);
12232:     my $coursereply;
12233:     foreach my $group (@{$groups}) {
12234:         my @groupitems = ();
12235:         foreach my $level (@levels) {
12236:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12237:              push(@groupitems,[$item,$level->[1]]);
12238:         }
12239:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12240:                                    $env{'course.'.$courseid.'.domain'},
12241:                                    'course',$mapp,$recursed,$recurseupref,
12242:                                    $courseid,'.['.$group.'].',$what,
12243:                                    @groupitems);
12244:         last if (defined($coursereply));
12245:     }
12246:     return $coursereply;
12247: }
12248: 
12249: sub get_map_hierarchy {
12250:     my ($mapname,$courseid) = @_;
12251:     my @recurseup = ();
12252:     if ($mapname) {
12253:         if (($cachedmapkey eq $courseid) &&
12254:             (abs($cachedmaptime-time)<5)) {
12255:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12256:                 return @{$cachedmaps{$mapname}};
12257:             }
12258:         }
12259:         my $navmap = Apache::lonnavmaps::navmap->new();
12260:         if (ref($navmap)) {
12261:             @recurseup = $navmap->recurseup_maps($mapname);
12262:             undef($navmap);
12263:             $cachedmaps{$mapname} = \@recurseup;
12264:             $cachedmaptime=time;
12265:             $cachedmapkey=$courseid;
12266:         }
12267:     }
12268:     return @recurseup;
12269: }
12270: 
12271: }
12272: 
12273: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12274:     my ($courseid,@groups) = @_;
12275:     @groups = sort(@groups);
12276:     return @groups;
12277: }
12278: 
12279: sub packages_tab_default {
12280:     my ($uri,$varname,$toolsymb)=@_;
12281:     my (undef,$part,$name)=split(/\./,$varname);
12282: 
12283:     my (@extension,@specifics,$do_default);
12284:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12285: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12286: 	if ($pack_type eq 'default') {
12287: 	    $do_default=1;
12288: 	} elsif ($pack_type eq 'extension') {
12289: 	    push(@extension,[$package,$pack_type,$pack_part]);
12290: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12291: 	    # only look at packages defaults for packages that this id is
12292: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12293: 	}
12294:     }
12295:     # first look for a package that matches the requested part id
12296:     foreach my $package (@specifics) {
12297: 	my (undef,$pack_type,$pack_part)=@{$package};
12298: 	next if ($pack_part ne $part);
12299: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12300: 	    return $packagetab{"$pack_type&$name&default"};
12301: 	}
12302:     }
12303:     # look for any possible matching non extension_ package
12304:     foreach my $package (@specifics) {
12305: 	my (undef,$pack_type,$pack_part)=@{$package};
12306: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12307: 	    return $packagetab{"$pack_type&$name&default"};
12308: 	}
12309: 	if ($pack_type eq 'part') { $pack_part='0'; }
12310: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12311: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12312: 	}
12313:     }
12314:     # look for any posible extension_ match
12315:     foreach my $package (@extension) {
12316: 	my ($package,$pack_type)=@{$package};
12317: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12318: 	    return $packagetab{"$pack_type&$name&default"};
12319: 	}
12320: 	if (defined($packagetab{$package."&$name&default"})) {
12321: 	    return $packagetab{$package."&$name&default"};
12322: 	}
12323:     }
12324:     # look for a global default setting
12325:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12326: 	return $packagetab{"default&$name&default"};
12327:     }
12328:     return undef;
12329: }
12330: 
12331: sub add_prefix_and_part {
12332:     my ($prefix,$part)=@_;
12333:     my $keyroot;
12334:     if (defined($prefix) && $prefix !~ /^__/) {
12335: 	# prefix that has a part already
12336: 	$keyroot=$prefix;
12337:     } elsif (defined($prefix)) {
12338: 	# prefix that is missing a part
12339: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12340:     } else {
12341: 	# no prefix at all
12342: 	if (defined($part)) { $keyroot='_'.$part; }
12343:     }
12344:     return $keyroot;
12345: }
12346: 
12347: # ---------------------------------------------------------------- Get metadata
12348: 
12349: my %metaentry;
12350: my %importedpartids;
12351: my %importedrespids;
12352: sub metadata {
12353:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12354:     $uri=&declutter($uri);
12355:     # if it is a non metadata possible uri return quickly
12356:     if (($uri eq '') || 
12357: 	(($uri =~ m|^/*adm/|) && 
12358: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12359:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12360: 	return undef;
12361:     }
12362:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12363: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12364: 	return undef;
12365:     }
12366:     my $filename=$uri;
12367:     $uri=~s/\.meta$//;
12368: #
12369: # Is the metadata already cached?
12370: # Look at timestamp of caching
12371: # Everything is cached by the main uri, libraries are never directly cached
12372: #
12373:     if (!defined($liburi)) {
12374: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12375: 	if (defined($cached)) { return $result->{':'.$what}; }
12376:     }
12377: 
12378: #
12379: # If the uri is for an external tool the file from
12380: # which metadata should be retrieved depends on whether
12381: # the tool had been configured to be gradable (set in the Course
12382: # Editor or Resource Editor).
12383: #
12384: # If a valid symb has been included as the third arg in the call
12385: # to &metadata() that can be used to retrieve the value of
12386: # parameter_0_gradable set for the resource, and included in the
12387: # uploaded map containing the tool. The value is retrieved via
12388: # &EXT(), if a valid symb is available.  Otherwise the value of
12389: # gradable in the exttool_$marker.db file for the tool instance
12390: # is retrieved via &get().
12391: #
12392: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12393: # hiddenresource and encrypturl (during course initialization)
12394: # the map-level parameter for resource.0.gradable included in the 
12395: # uploaded map containing the tool will not yet have been stored
12396: # in the user_course_parms.db file for the user's session, so in 
12397: # this case fall back to retrieving gradable status from the
12398: # exttool_$marker.db file.
12399: #
12400: # In order to avoid an infinite loop, &metadata() will return
12401: # before a call to &EXT(), if the uri is for an external tool
12402: # and the $what for which metadata is being requested is
12403: # parameter_0_gradable or 0_gradable.
12404: #
12405: 
12406:     if ($uri =~ /ext\.tool$/) {
12407:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12408:             return;
12409:         } else {
12410:             my ($checked,$use_passback);
12411:             if ($toolsymb ne '') {
12412:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12413:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12414:                     $checked = 1;
12415:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12416:                         $use_passback = 1;
12417:                     }
12418:                 }
12419:             }
12420:             unless ($checked) {
12421:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12422:                 $marker=~s/\D//g;
12423:                 if ($marker) {
12424:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12425:                     $use_passback = $toolsettings{'gradable'};
12426:                 }
12427:             }
12428:             if ($use_passback) {
12429:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12430:             } else {
12431:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12432:             }
12433:         }
12434:     }
12435: 
12436:     {
12437: # Imported parts would go here
12438:         my @origfiletagids=();
12439:         my $importedparts=0;
12440: 
12441: # Imported responseids would go here
12442:         my $importedresponses=0;
12443: #
12444: # Is this a recursive call for a library?
12445: #
12446: #	if (! exists($metacache{$uri})) {
12447: #	    $metacache{$uri}={};
12448: #	}
12449: 	my $cachetime = 60*60;
12450:         if ($liburi) {
12451: 	    $liburi=&declutter($liburi);
12452:             $filename=$liburi;
12453:         } else {
12454: 	    &devalidate_cache_new('meta',$uri);
12455: 	    undef(%metaentry);
12456: 	}
12457:         my %metathesekeys=();
12458:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12459: 	my $metastring;
12460: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12461: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12462: 	    $metastring = 
12463: 		&Apache::lonnet::ssi_body($which,
12464: 					  ('grade_target' => 'meta'));
12465: 	    $cachetime = 1; # only want this cached in the child not long term
12466: 	} elsif (($uri !~ m -^(editupload)/-) && 
12467:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12468: 	    my $file=&filelocation('',&clutter($filename));
12469: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12470: 	    $metastring=&getfile($file);
12471: 	}
12472:         my $parser=HTML::LCParser->new(\$metastring);
12473:         my $token;
12474:         undef %metathesekeys;
12475:         while ($token=$parser->get_token) {
12476: 	    if ($token->[0] eq 'S') {
12477: 		if (defined($token->[2]->{'package'})) {
12478: #
12479: # This is a package - get package info
12480: #
12481: 		    my $package=$token->[2]->{'package'};
12482: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12483: 		    if (defined($token->[2]->{'id'})) { 
12484: 			$keyroot.='_'.$token->[2]->{'id'}; 
12485: 		    }
12486: 		    if ($metaentry{':packages'}) {
12487: 			$metaentry{':packages'}.=','.$package.$keyroot;
12488: 		    } else {
12489: 			$metaentry{':packages'}=$package.$keyroot;
12490: 		    }
12491: 		    foreach my $pack_entry (keys(%packagetab)) {
12492: 			my $part=$keyroot;
12493: 			$part=~s/^\_//;
12494: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12495: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12496: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12497: 			    # ignore package.tab specified default values
12498:                             # here &package_tab_default() will fetch those
12499: 			    if ($subp eq 'default') { next; }
12500: 			    my $value=$packagetab{$pack_entry};
12501: 			    my $unikey;
12502: 			    if ($pack =~ /_0$/) {
12503: 				$unikey='parameter_0_'.$name;
12504: 				$part=0;
12505: 			    } else {
12506: 				$unikey='parameter'.$keyroot.'_'.$name;
12507: 			    }
12508: 			    if ($subp eq 'display') {
12509: 				$value.=' [Part: '.$part.']';
12510: 			    }
12511: 			    $metaentry{':'.$unikey.'.part'}=$part;
12512: 			    $metathesekeys{$unikey}=1;
12513: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12514: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12515: 			    }
12516: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12517: 				$metaentry{':'.$unikey}=
12518: 				    $metaentry{':'.$unikey.'.default'};
12519: 			    }
12520: 			}
12521: 		    }
12522: 		} else {
12523: #
12524: # This is not a package - some other kind of start tag
12525: #
12526: 		    my $entry=$token->[1];
12527: 		    my $unikey='';
12528: 
12529: 		    if ($entry eq 'import') {
12530: #
12531: # Importing a library here
12532: #
12533:                         my $location=$parser->get_text('/import');
12534:                         my $dir=$filename;
12535:                         $dir=~s|[^/]*$||;
12536:                         $location=&filelocation($dir,$location);
12537: 
12538:                         my $importid=$token->[2]->{'id'};
12539:                         my $importmode=$token->[2]->{'importmode'};
12540: #
12541: # Check metadata for imported file to
12542: # see if it contained response items
12543: #
12544:                         my ($origfile,@libfilekeys);
12545:                         my %currmetaentry = %metaentry;
12546:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12547:                                                            $depthcount+1));
12548:                         if (grep(/^responseorder$/,@libfilekeys)) {
12549:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12550:                                                              undef,$depthcount+1);
12551:                             if ($libresponseorder ne '') {
12552:                                 if ($#origfiletagids<0) {
12553:                                     undef(%importedrespids);
12554:                                     undef(%importedpartids);
12555:                                 }
12556:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12557:                                 if (@respids) {
12558:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12559:                                 }
12560:                                 if ($importedrespids{$importid} ne '') {
12561:                                     $importedresponses = 1;
12562: # We need to get the original file and the imported file to get the response order correct
12563: # Load and inspect original file
12564:                                     if ($#origfiletagids<0) {
12565:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12566:                                         $origfile=&getfile($origfilelocation);
12567:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12568:                                     }
12569:                                 }
12570:                             }
12571:                         }
12572: # Do not overwrite contents of %metaentry hash for resource itself with 
12573: # hash populated for imported library file
12574:                         %metaentry = %currmetaentry;
12575:                         undef(%currmetaentry);
12576:                         if ($importmode eq 'part') {
12577: # Import as part(s)
12578:                            $importedparts=1;
12579: # We need to get the original file and the imported file to get the part order correct
12580: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12581: # Load and inspect original file if we didn't do that already
12582:                            if ($#origfiletagids<0) {
12583:                                undef(%importedrespids);
12584:                                undef(%importedpartids);
12585:                                if ($origfile eq '') {
12586:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12587:                                    $origfile=&getfile($origfilelocation);
12588:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12589:                                }
12590:                            }
12591:                            my @impfilepartids;
12592: # If <partorder> tag is included in metadata for the imported file
12593: # get the parts in the imported file from that.
12594:                            if (grep(/^partorder$/,@libfilekeys)) {
12595:                                %currmetaentry = %metaentry;
12596:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12597:                                                             $depthcount+1);
12598:                                %metaentry = %currmetaentry;
12599:                                undef(%currmetaentry);
12600:                                if ($libpartorder ne '') {
12601:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12602:                                }
12603:                            } else {
12604: # If no <partorder> tag available, load and inspect imported file
12605:                                my $impfile=&getfile($location);
12606:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12607:                            }
12608:                            if ($#impfilepartids>=0) {
12609: # This problem had parts
12610:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12611:                            } else {
12612: # Importing by turning a single problem into a problem part
12613: # It gets the import-tags ID as part-ID
12614:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12615:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12616:                            }
12617:                         } else {
12618: # Import as problem or as normal import
12619:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12620:                             unless ($importmode eq 'problem') {
12621: # Normal import
12622:                                 if (defined($token->[2]->{'id'})) {
12623:                                     $unikey.='_'.$token->[2]->{'id'};
12624:                                 }
12625:                             }
12626: # Check metadata for imported file to
12627: # see if it contained parts
12628:                             if (grep(/^partorder$/,@libfilekeys)) {
12629:                                 %currmetaentry = %metaentry;
12630:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12631:                                                              $depthcount+1);
12632:                                 %metaentry = %currmetaentry;
12633:                                 undef(%currmetaentry);
12634:                                 if ($libpartorder ne '') {
12635:                                     $importedparts = 1;
12636:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12637:                                 }
12638:                             }
12639:                         }
12640: 			if ($depthcount<20) {
12641: 			    my $metadata = 
12642: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12643: 					  $depthcount+1);
12644: 			    foreach my $meta (split(',',$metadata)) {
12645: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12646: 				$metathesekeys{$meta}=1;
12647: 			    }
12648:                         }
12649: 		    } else {
12650: #
12651: # Not importing, some other kind of non-package, non-library start tag
12652: # 
12653:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12654:                         if (defined($token->[2]->{'id'})) {
12655:                             $unikey.='_'.$token->[2]->{'id'};
12656:                         }
12657: 			if (defined($token->[2]->{'name'})) { 
12658: 			    $unikey.='_'.$token->[2]->{'name'}; 
12659: 			}
12660: 			$metathesekeys{$unikey}=1;
12661: 			foreach my $param (@{$token->[3]}) {
12662: 			    $metaentry{':'.$unikey.'.'.$param} =
12663: 				$token->[2]->{$param};
12664: 			}
12665: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12666: 			my $default=$metaentry{':'.$unikey.'.default'};
12667: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12668: 		 # only ws inside the tag, and not in default, so use default
12669: 		 # as value
12670: 			    $metaentry{':'.$unikey}=$default;
12671: 			} elsif ( $internaltext =~ /\S/ ) {
12672: 		  # something interesting inside the tag
12673: 			    $metaentry{':'.$unikey}=$internaltext;
12674: 			} else {
12675: 		  # no interesting values, don't set a default
12676: 			}
12677: # end of not-a-package not-a-library import
12678: 		    }
12679: # end of not-a-package start tag
12680: 		}
12681: # the next is the end of "start tag"
12682: 	    }
12683: 	}
12684: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12685: 	$extension = lc($extension);
12686: 	if ($extension eq 'htm') { $extension='html'; }
12687: 
12688: 	foreach my $key (keys(%packagetab)) {
12689: 	    #no specific packages #how's our extension
12690: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12691: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12692: 					 \%metathesekeys);
12693: 	}
12694: 
12695: 	if (!exists($metaentry{':packages'})
12696: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12697: 	    foreach my $key (keys(%packagetab)) {
12698: 		#no specific packages well let's get default then
12699: 		if ($key!~/^default&/) { next; }
12700: 		&metadata_create_package_def($uri,$key,'default',
12701: 					     \%metathesekeys);
12702: 	    }
12703: 	}
12704: # are there custom rights to evaluate
12705: 	if ($metaentry{':copyright'} eq 'custom') {
12706: 
12707:     #
12708:     # Importing a rights file here
12709:     #
12710: 	    unless ($depthcount) {
12711: 		my $location=$metaentry{':customdistributionfile'};
12712: 		my $dir=$filename;
12713: 		$dir=~s|[^/]*$||;
12714: 		$location=&filelocation($dir,$location);
12715: 		my $rights_metadata =
12716: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12717: 			      $depthcount+1);
12718: 		foreach my $rights (split(',',$rights_metadata)) {
12719: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12720: 		    $metathesekeys{$rights}=1;
12721: 		}
12722: 	    }
12723: 	}
12724: 	# uniqifiy package listing
12725: 	my %seen;
12726: 	my @uniq_packages =
12727: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12728: 	$metaentry{':packages'} = join(',',@uniq_packages);
12729: 
12730:         if (($importedresponses) || ($importedparts)) {
12731:             if ($importedparts) {
12732: # We had imported parts and need to rebuild partorder
12733:                 $metaentry{':partorder'}='';
12734:                 $metathesekeys{'partorder'}=1;
12735:             }
12736:             if ($importedresponses) {
12737: # We had imported responses and need to rebuil responseorder
12738:                 $metaentry{':responseorder'}='';
12739:                 $metathesekeys{'responseorder'}=1;
12740:             }
12741:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12742:                 my $origid = $origfiletagids[$index+1];
12743:                 if ($origfiletagids[$index] eq 'part') {
12744: # Original part, part of the problem
12745:                     if ($importedparts) {
12746:                         $metaentry{':partorder'}.=','.$origid;
12747:                     }
12748:                 } elsif ($origfiletagids[$index] eq 'import') {
12749:                     if ($importedparts) {
12750: # We have imported parts at this position
12751:                         if ($importedpartids{$origid} ne '') {
12752:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12753:                         }
12754:                     }
12755:                     if ($importedresponses) {
12756: # We have imported responses at this position
12757:                         if ($importedrespids{$origid} ne '') {
12758:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12759:                         }
12760:                     }
12761:                 } else {
12762: # Original response item, part of the problem
12763:                     if ($importedresponses) {
12764:                         $metaentry{':responseorder'}.=','.$origid;
12765:                     }
12766:                 }
12767:             }
12768:             if ($importedparts) {
12769:                 $metaentry{':partorder'}=~s/^\,//;
12770:             }
12771:             if ($importedresponses) {
12772:                 $metaentry{':responseorder'}=~s/^\,//;
12773:             }
12774:         }
12775: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12776: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12777: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12778:         unless ($liburi) {
12779: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12780:         }
12781: # this is the end of "was not already recently cached
12782:     }
12783:     return $metaentry{':'.$what};
12784: }
12785: 
12786: sub metadata_create_package_def {
12787:     my ($uri,$key,$package,$metathesekeys)=@_;
12788:     my ($pack,$name,$subp)=split(/\&/,$key);
12789:     if ($subp eq 'default') { next; }
12790:     
12791:     if (defined($metaentry{':packages'})) {
12792: 	$metaentry{':packages'}.=','.$package;
12793:     } else {
12794: 	$metaentry{':packages'}=$package;
12795:     }
12796:     my $value=$packagetab{$key};
12797:     my $unikey;
12798:     $unikey='parameter_0_'.$name;
12799:     $metaentry{':'.$unikey.'.part'}=0;
12800:     $$metathesekeys{$unikey}=1;
12801:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12802: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12803:     }
12804:     if (defined($metaentry{':'.$unikey.'.default'})) {
12805: 	$metaentry{':'.$unikey}=
12806: 	    $metaentry{':'.$unikey.'.default'};
12807:     }
12808: }
12809: 
12810: sub metadata_generate_part0 {
12811:     my ($metadata,$metacache,$uri) = @_;
12812:     my %allnames;
12813:     foreach my $metakey (keys(%$metadata)) {
12814: 	if ($metakey=~/^parameter\_(.*)/) {
12815: 	  my $part=$$metacache{':'.$metakey.'.part'};
12816: 	  my $name=$$metacache{':'.$metakey.'.name'};
12817: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12818: 	    $allnames{$name}=$part;
12819: 	  }
12820: 	}
12821:     }
12822:     foreach my $name (keys(%allnames)) {
12823:       $$metadata{"parameter_0_$name"}=1;
12824:       my $key=":parameter_0_$name";
12825:       $$metacache{"$key.part"}='0';
12826:       $$metacache{"$key.name"}=$name;
12827:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12828: 					   $allnames{$name}.'_'.$name.
12829: 					   '.type'};
12830:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12831: 			     '.display'};
12832:       my $expr='[Part: '.$allnames{$name}.']';
12833:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12834:       $$metacache{"$key.display"}=$olddis;
12835:     }
12836: }
12837: 
12838: # ------------------------------------------------------ Devalidate title cache
12839: 
12840: sub devalidate_title_cache {
12841:     my ($url)=@_;
12842:     if (!$env{'request.course.id'}) { return; }
12843:     my $symb=&symbread($url);
12844:     if (!$symb) { return; }
12845:     my $key=$env{'request.course.id'}."\0".$symb;
12846:     &devalidate_cache_new('title',$key);
12847: }
12848: 
12849: # ------------------------------------------------- Get the title of a course
12850: 
12851: sub current_course_title {
12852:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12853: }
12854: # ------------------------------------------------- Get the title of a resource
12855: 
12856: sub gettitle {
12857:     my $urlsymb=shift;
12858:     my $symb=&symbread($urlsymb);
12859:     if ($symb) {
12860: 	my $key=$env{'request.course.id'}."\0".$symb;
12861: 	my ($result,$cached)=&is_cached_new('title',$key);
12862: 	if (defined($cached)) { 
12863: 	    return $result;
12864: 	}
12865: 	my ($map,$resid,$url)=&decode_symb($symb);
12866: 	my $title='';
12867: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12868: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12869: 	} else {
12870: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12871: 		    &GDBM_READER(),0640)) {
12872: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12873: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12874: 		untie(%bighash);
12875: 	    }
12876: 	}
12877: 	$title=~s/\&colon\;/\:/gs;
12878: 	if ($title) {
12879: # Remember both $symb and $title for dynamic metadata
12880:             $accesshash{$symb.'___crstitle'}=$title;
12881:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12882: # Cache this title and then return it
12883: 	    return &do_cache_new('title',$key,$title,600);
12884: 	}
12885: 	$urlsymb=$url;
12886:     }
12887:     my $title=&metadata($urlsymb,'title');
12888:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12889:     return $title;
12890: }
12891: 
12892: sub get_slot {
12893:     my ($which,$cnum,$cdom)=@_;
12894:     if (!$cnum || !$cdom) {
12895: 	(undef,my $courseid)=&whichuser();
12896: 	$cdom=$env{'course.'.$courseid.'.domain'};
12897: 	$cnum=$env{'course.'.$courseid.'.num'};
12898:     }
12899:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12900:     my %slotinfo;
12901:     if (exists($remembered{$key})) {
12902: 	$slotinfo{$which} = $remembered{$key};
12903:     } else {
12904: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12905: 	&Apache::lonhomework::showhash(%slotinfo);
12906: 	my ($tmp)=keys(%slotinfo);
12907: 	if ($tmp=~/^error:/) { return (); }
12908: 	$remembered{$key} = $slotinfo{$which};
12909:     }
12910:     if (ref($slotinfo{$which}) eq 'HASH') {
12911: 	return %{$slotinfo{$which}};
12912:     }
12913:     return $slotinfo{$which};
12914: }
12915: 
12916: sub get_reservable_slots {
12917:     my ($cnum,$cdom,$uname,$udom) = @_;
12918:     my $now = time;
12919:     my $reservable_info;
12920:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12921:     if (exists($remembered{$key})) {
12922:         $reservable_info = $remembered{$key};
12923:     } else {
12924:         my %resv;
12925:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12926:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12927:         $reservable_info = \%resv;
12928:         $remembered{$key} = $reservable_info;
12929:     }
12930:     return $reservable_info;
12931: }
12932: 
12933: sub get_course_slots {
12934:     my ($cnum,$cdom) = @_;
12935:     my $hashid=$cnum.':'.$cdom;
12936:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12937:     if (defined($cached)) {
12938:         if (ref($result) eq 'HASH') {
12939:             return %{$result};
12940:         }
12941:     } else {
12942:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12943:         my ($tmp) = keys(%slots);
12944:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12945:             &do_cache_new('allslots',$hashid,\%slots,600);
12946:             return %slots;
12947:         }
12948:     }
12949:     return;
12950: }
12951: 
12952: sub devalidate_slots_cache {
12953:     my ($cnum,$cdom)=@_;
12954:     my $hashid=$cnum.':'.$cdom;
12955:     &devalidate_cache_new('allslots',$hashid);
12956: }
12957: 
12958: sub get_coursechange {
12959:     my ($cdom,$cnum) = @_;
12960:     if ($cdom eq '' || $cnum eq '') {
12961:         return unless ($env{'request.course.id'});
12962:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12963:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12964:     }
12965:     my $hashid=$cdom.'_'.$cnum;
12966:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12967:     if ((defined($cached)) && ($change ne '')) {
12968:         return $change;
12969:     } else {
12970:         my %crshash;
12971:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12972:         if ($crshash{'internal.contentchange'} eq '') {
12973:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12974:             if ($change eq '') {
12975:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12976:                 $change = $crshash{'internal.created'};
12977:             }
12978:         } else {
12979:             $change = $crshash{'internal.contentchange'};
12980:         }
12981:         my $cachetime = 600;
12982:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12983:     }
12984:     return $change;
12985: }
12986: 
12987: sub devalidate_coursechange_cache {
12988:     my ($cnum,$cdom)=@_;
12989:     my $hashid=$cnum.':'.$cdom;
12990:     &devalidate_cache_new('crschange',$hashid);
12991: }
12992: 
12993: # ------------------------------------------------- Update symbolic store links
12994: 
12995: sub symblist {
12996:     my ($mapname,%newhash)=@_;
12997:     $mapname=&deversion(&declutter($mapname));
12998:     my %hash;
12999:     if (($env{'request.course.fn'}) && (%newhash)) {
13000:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13001:                       &GDBM_WRCREAT(),0640)) {
13002: 	    foreach my $url (keys(%newhash)) {
13003: 		next if ($url eq 'last_known'
13004: 			 && $env{'form.no_update_last_known'});
13005: 		$hash{declutter($url)}=&encode_symb($mapname,
13006: 						    $newhash{$url}->[1],
13007: 						    $newhash{$url}->[0]);
13008:             }
13009:             if (untie(%hash)) {
13010: 		return 'ok';
13011:             }
13012:         }
13013:     }
13014:     return 'error';
13015: }
13016: 
13017: # --------------------------------------------------------------- Verify a symb
13018: 
13019: sub symbverify {
13020:     my ($symb,$thisurl,$encstate)=@_;
13021:     my $thisfn=$thisurl;
13022:     $thisfn=&declutter($thisfn);
13023: # direct jump to resource in page or to a sequence - will construct own symbs
13024:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13025: # check URL part
13026:     my ($map,$resid,$url)=&decode_symb($symb);
13027: 
13028:     unless ($url eq $thisfn) { return 0; }
13029: 
13030:     $symb=&symbclean($symb);
13031:     $thisurl=&deversion($thisurl);
13032:     $thisfn=&deversion($thisfn);
13033: 
13034:     my %bighash;
13035:     my $okay=0;
13036: 
13037:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13038:                             &GDBM_READER(),0640)) {
13039:         my $noclutter;
13040:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13041:             $thisurl =~ s/\?.+$//;
13042:             if ($map =~ m{^uploaded/.+\.page$}) {
13043:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13044:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13045:                 $noclutter = 1;
13046:             }
13047:         }
13048:         my $ids;
13049:         if ($noclutter) {
13050:             $ids=$bighash{'ids_'.$thisurl};
13051:         } else {
13052:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13053:         }
13054:         unless ($ids) {
13055:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13056:             $ids=$bighash{$idkey};
13057:         }
13058:         if ($ids) {
13059: # ------------------------------------------------------------------- Has ID(s)
13060:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13061:                 $symb =~ s/\?.+$//;
13062:             }
13063: 	    foreach my $id (split(/\,/,$ids)) {
13064: 	       my ($mapid,$resid)=split(/\./,$id);
13065:                if (
13066:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13067:    eq $symb) {
13068:                    if (ref($encstate)) {
13069:                        $$encstate = $bighash{'encrypted_'.$id};
13070:                    }
13071: 		   if (($env{'request.role.adv'}) ||
13072: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13073:                        ($thisurl eq '/adm/navmaps')) {
13074: 		       $okay=1;
13075:                        last;
13076: 		   }
13077: 	       }
13078: 	   }
13079:         }
13080: 	untie(%bighash);
13081:     }
13082:     return $okay;
13083: }
13084: 
13085: # --------------------------------------------------------------- Clean-up symb
13086: 
13087: sub symbclean {
13088:     my $symb=shift;
13089:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13090: # remove version from map
13091:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13092: 
13093: # remove version from URL
13094:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13095: 
13096: # remove wrapper
13097: 
13098:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13099:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13100:     return $symb;
13101: }
13102: 
13103: # ---------------------------------------------- Split symb to find map and url
13104: 
13105: sub encode_symb {
13106:     my ($map,$resid,$url)=@_;
13107:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13108: }
13109: 
13110: sub decode_symb {
13111:     my $symb=shift;
13112:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13113:     my ($map,$resid,$url)=split(/___/,$symb);
13114:     return (&fixversion($map),$resid,&fixversion($url));
13115: }
13116: 
13117: sub fixversion {
13118:     my $fn=shift;
13119:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13120:     my %bighash;
13121:     my $uri=&clutter($fn);
13122:     my $key=$env{'request.course.id'}.'_'.$uri;
13123: # is this cached?
13124:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13125:     if (defined($cached)) { return $result; }
13126: # unfortunately not cached, or expired
13127:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13128: 	    &GDBM_READER(),0640)) {
13129:  	if ($bighash{'version_'.$uri}) {
13130:  	    my $version=$bighash{'version_'.$uri};
13131:  	    unless (($version eq 'mostrecent') || 
13132: 		    ($version==&getversion($uri))) {
13133:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13134:  	    }
13135:  	}
13136:  	untie %bighash;
13137:     }
13138:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13139: }
13140: 
13141: sub deversion {
13142:     my $url=shift;
13143:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13144:     return $url;
13145: }
13146: 
13147: # ------------------------------------------------------ Return symb list entry
13148: 
13149: sub symbread {
13150:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
13151:     my $cache_str='request.symbread.cached.'.$thisfn;
13152:     if (defined($env{$cache_str})) {
13153:         if ($ignorecachednull) {
13154:             return $env{$cache_str} unless ($env{$cache_str} eq '');
13155:         } else {
13156:             return $env{$cache_str};
13157:         }
13158:     }
13159: # no filename provided? try from environment
13160:     unless ($thisfn) {
13161:         if ($env{'request.symb'}) {
13162: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
13163: 	}
13164: 	$thisfn=$env{'request.filename'};
13165:     }
13166:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13167: # is that filename actually a symb? Verify, clean, and return
13168:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13169: 	if (&symbverify($thisfn,$1)) {
13170: 	    return $env{$cache_str}=&symbclean($thisfn);
13171: 	}
13172:     }
13173:     $thisfn=declutter($thisfn);
13174:     my %hash;
13175:     my %bighash;
13176:     my $syval='';
13177:     if (($env{'request.course.fn'}) && ($thisfn)) {
13178:         my $targetfn = $thisfn;
13179:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13180:             $targetfn = 'adm/wrapper/'.$thisfn;
13181:         }
13182: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13183: 	    $targetfn=$1;
13184: 	}
13185:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13186:                       &GDBM_READER(),0640)) {
13187: 	    $syval=$hash{$targetfn};
13188:             untie(%hash);
13189:         }
13190: # ---------------------------------------------------------- There was an entry
13191:         if ($syval) {
13192: 	    #unless ($syval=~/\_\d+$/) {
13193: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13194: 		    #&appenv({'request.ambiguous' => $thisfn});
13195: 		    #return $env{$cache_str}='';
13196: 		#}    
13197: 		#$syval.=$1;
13198: 	    #}
13199:         } else {
13200: # ------------------------------------------------------- Was not in symb table
13201:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13202:                             &GDBM_READER(),0640)) {
13203: # ---------------------------------------------- Get ID(s) for current resource
13204:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13205:               unless ($ids) { 
13206:                  $ids=$bighash{'ids_/'.$thisfn};
13207:               }
13208:               unless ($ids) {
13209: # alias?
13210: 		  $ids=$bighash{'mapalias_'.$thisfn};
13211:               }
13212:               if ($ids) {
13213: # ------------------------------------------------------------------- Has ID(s)
13214:                  my @possibilities=split(/\,/,$ids);
13215:                  if ($#possibilities==0) {
13216: # ----------------------------------------------- There is only one possibility
13217: 		     my ($mapid,$resid)=split(/\./,$ids);
13218: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13219: 						    $resid,$thisfn);
13220:                      if (ref($possibles) eq 'HASH') {
13221:                          $possibles->{$syval} = 1;    
13222:                      }
13223:                      if ($checkforblock) {
13224:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13225:                          if (@blockers) {
13226:                              $syval = '';
13227:                              return;
13228:                          }
13229:                      }
13230:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13231: # ------------------------------------------ There is more than one possibility
13232:                      my $realpossible=0;
13233:                      foreach my $id (@possibilities) {
13234: 			 my $file=$bighash{'src_'.$id};
13235:                          my $canaccess;
13236:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13237:                              $canaccess = 1;
13238:                          } else { 
13239:                              $canaccess = &allowed('bre',$file);
13240:                          }
13241:                          if ($canaccess) {
13242:          		     my ($mapid,$resid)=split(/\./,$id);
13243:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13244:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13245: 						             $resid,$thisfn);
13246:                                  if (ref($possibles) eq 'HASH') {
13247:                                      $possibles->{$syval} = 1;
13248:                                  }
13249:                                  if ($checkforblock) {
13250:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13251:                                      unless (@blockers > 0) {
13252:                                          $syval = $poss_syval;
13253:                                          $realpossible++;
13254:                                      }
13255:                                  } else {
13256:                                      $syval = $poss_syval;
13257:                                      $realpossible++;
13258:                                  }
13259:                              }
13260: 			 }
13261:                      }
13262: 		     if ($realpossible!=1) { $syval=''; }
13263:                  } else {
13264:                      $syval='';
13265:                  }
13266: 	      }
13267:               untie(%bighash);
13268:            }
13269:         }
13270:         if ($syval) {
13271: 	    return $env{$cache_str}=$syval;
13272:         }
13273:     }
13274:     &appenv({'request.ambiguous' => $thisfn});
13275:     return $env{$cache_str}='';
13276: }
13277: 
13278: # ---------------------------------------------------------- Return random seed
13279: 
13280: sub numval {
13281:     my $txt=shift;
13282:     $txt=~tr/A-J/0-9/;
13283:     $txt=~tr/a-j/0-9/;
13284:     $txt=~tr/K-T/0-9/;
13285:     $txt=~tr/k-t/0-9/;
13286:     $txt=~tr/U-Z/0-5/;
13287:     $txt=~tr/u-z/0-5/;
13288:     $txt=~s/\D//g;
13289:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13290:     return int($txt);
13291: }
13292: 
13293: sub numval2 {
13294:     my $txt=shift;
13295:     $txt=~tr/A-J/0-9/;
13296:     $txt=~tr/a-j/0-9/;
13297:     $txt=~tr/K-T/0-9/;
13298:     $txt=~tr/k-t/0-9/;
13299:     $txt=~tr/U-Z/0-5/;
13300:     $txt=~tr/u-z/0-5/;
13301:     $txt=~s/\D//g;
13302:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13303:     my $total;
13304:     foreach my $val (@txts) { $total+=$val; }
13305:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13306:     return int($total);
13307: }
13308: 
13309: sub numval3 {
13310:     use integer;
13311:     my $txt=shift;
13312:     $txt=~tr/A-J/0-9/;
13313:     $txt=~tr/a-j/0-9/;
13314:     $txt=~tr/K-T/0-9/;
13315:     $txt=~tr/k-t/0-9/;
13316:     $txt=~tr/U-Z/0-5/;
13317:     $txt=~tr/u-z/0-5/;
13318:     $txt=~s/\D//g;
13319:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13320:     my $total;
13321:     foreach my $val (@txts) { $total+=$val; }
13322:     if ($_64bit) { $total=(($total<<32)>>32); }
13323:     return $total;
13324: }
13325: 
13326: sub digest {
13327:     my ($data)=@_;
13328:     my $digest=&Digest::MD5::md5($data);
13329:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13330:     my ($e,$f);
13331:     {
13332:         use integer;
13333:         $e=($a+$b);
13334:         $f=($c+$d);
13335:         if ($_64bit) {
13336:             $e=(($e<<32)>>32);
13337:             $f=(($f<<32)>>32);
13338:         }
13339:     }
13340:     if (wantarray) {
13341: 	return ($e,$f);
13342:     } else {
13343: 	my $g;
13344: 	{
13345: 	    use integer;
13346: 	    $g=($e+$f);
13347: 	    if ($_64bit) {
13348: 		$g=(($g<<32)>>32);
13349: 	    }
13350: 	}
13351: 	return $g;
13352:     }
13353: }
13354: 
13355: sub latest_rnd_algorithm_id {
13356:     return '64bit5';
13357: }
13358: 
13359: sub get_rand_alg {
13360:     my ($courseid)=@_;
13361:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13362:     if ($courseid) {
13363: 	return $env{"course.$courseid.rndseed"};
13364:     }
13365:     return &latest_rnd_algorithm_id();
13366: }
13367: 
13368: sub validCODE {
13369:     my ($CODE)=@_;
13370:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13371:     return 0;
13372: }
13373: 
13374: sub getCODE {
13375:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13376:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13377: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13378: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13379: 	return $Apache::lonhomework::history{'resource.CODE'};
13380:     }
13381:     return undef;
13382: }
13383: #
13384: #  Determines the random seed for a specific context:
13385: #
13386: # parameters:
13387: #   symb      - in course context the symb for the seed.
13388: #   course_id - The course id of the form domain_coursenum.
13389: #   domain    - Domain for the user.
13390: #   course    - Course for the user.
13391: #   cenv      - environment of the course.
13392: #
13393: # NOTE:
13394: #   All parameters are picked out of the environment if missing
13395: #   or not defined.
13396: #   If a symb cannot be determined the current time is used instead.
13397: #
13398: #  For a given well defined symb, courside, domain, username,
13399: #  and course environment, the seed is reproducible.
13400: #
13401: sub rndseed {
13402:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13403:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13404:     if (!defined($symb)) {
13405: 	unless ($symb=$wsymb) { return time; }
13406:     }
13407:     if (!defined $courseid) { 
13408: 	$courseid=$wcourseid; 
13409:     }
13410:     if (!defined $domain) { $domain=$wdomain; }
13411:     if (!defined $username) { $username=$wusername }
13412: 
13413:     my $which;
13414:     if (defined($cenv->{'rndseed'})) {
13415: 	$which = $cenv->{'rndseed'};
13416:     } else {
13417: 	$which =&get_rand_alg($courseid);
13418:     }
13419:     if (defined(&getCODE())) {
13420: 
13421: 	if ($which eq '64bit5') {
13422: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13423: 	} elsif ($which eq '64bit4') {
13424: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13425: 	} else {
13426: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13427: 	}
13428:     } elsif ($which eq '64bit5') {
13429: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13430:     } elsif ($which eq '64bit4') {
13431: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13432:     } elsif ($which eq '64bit3') {
13433: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13434:     } elsif ($which eq '64bit2') {
13435: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13436:     } elsif ($which eq '64bit') {
13437: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13438:     }
13439:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13440: }
13441: 
13442: sub rndseed_32bit {
13443:     my ($symb,$courseid,$domain,$username)=@_;
13444:     {
13445: 	use integer;
13446: 	my $symbchck=unpack("%32C*",$symb) << 27;
13447: 	my $symbseed=numval($symb) << 22;
13448: 	my $namechck=unpack("%32C*",$username) << 17;
13449: 	my $nameseed=numval($username) << 12;
13450: 	my $domainseed=unpack("%32C*",$domain) << 7;
13451: 	my $courseseed=unpack("%32C*",$courseid);
13452: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13453: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13454: 	#&logthis("rndseed :$num:$symb");
13455: 	if ($_64bit) { $num=(($num<<32)>>32); }
13456: 	return $num;
13457:     }
13458: }
13459: 
13460: sub rndseed_64bit {
13461:     my ($symb,$courseid,$domain,$username)=@_;
13462:     {
13463: 	use integer;
13464: 	my $symbchck=unpack("%32S*",$symb) << 21;
13465: 	my $symbseed=numval($symb) << 10;
13466: 	my $namechck=unpack("%32S*",$username);
13467: 	
13468: 	my $nameseed=numval($username) << 21;
13469: 	my $domainseed=unpack("%32S*",$domain) << 10;
13470: 	my $courseseed=unpack("%32S*",$courseid);
13471: 	
13472: 	my $num1=$symbchck+$symbseed+$namechck;
13473: 	my $num2=$nameseed+$domainseed+$courseseed;
13474: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13475: 	#&logthis("rndseed :$num:$symb");
13476: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13477: 	return "$num1,$num2";
13478:     }
13479: }
13480: 
13481: sub rndseed_64bit2 {
13482:     my ($symb,$courseid,$domain,$username)=@_;
13483:     {
13484: 	use integer;
13485: 	# strings need to be an even # of cahracters long, it it is odd the
13486:         # last characters gets thrown away
13487: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13488: 	my $symbseed=numval($symb) << 10;
13489: 	my $namechck=unpack("%32S*",$username.' ');
13490: 	
13491: 	my $nameseed=numval($username) << 21;
13492: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13493: 	my $courseseed=unpack("%32S*",$courseid.' ');
13494: 	
13495: 	my $num1=$symbchck+$symbseed+$namechck;
13496: 	my $num2=$nameseed+$domainseed+$courseseed;
13497: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13498: 	#&logthis("rndseed :$num:$symb");
13499: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13500: 	return "$num1,$num2";
13501:     }
13502: }
13503: 
13504: sub rndseed_64bit3 {
13505:     my ($symb,$courseid,$domain,$username)=@_;
13506:     {
13507: 	use integer;
13508: 	# strings need to be an even # of cahracters long, it it is odd the
13509:         # last characters gets thrown away
13510: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13511: 	my $symbseed=numval2($symb) << 10;
13512: 	my $namechck=unpack("%32S*",$username.' ');
13513: 	
13514: 	my $nameseed=numval2($username) << 21;
13515: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13516: 	my $courseseed=unpack("%32S*",$courseid.' ');
13517: 	
13518: 	my $num1=$symbchck+$symbseed+$namechck;
13519: 	my $num2=$nameseed+$domainseed+$courseseed;
13520: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13521: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13522: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13523: 	
13524: 	return "$num1:$num2";
13525:     }
13526: }
13527: 
13528: sub rndseed_64bit4 {
13529:     my ($symb,$courseid,$domain,$username)=@_;
13530:     {
13531: 	use integer;
13532: 	# strings need to be an even # of cahracters long, it it is odd the
13533:         # last characters gets thrown away
13534: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13535: 	my $symbseed=numval3($symb) << 10;
13536: 	my $namechck=unpack("%32S*",$username.' ');
13537: 	
13538: 	my $nameseed=numval3($username) << 21;
13539: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13540: 	my $courseseed=unpack("%32S*",$courseid.' ');
13541: 	
13542: 	my $num1=$symbchck+$symbseed+$namechck;
13543: 	my $num2=$nameseed+$domainseed+$courseseed;
13544: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13545: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13546: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13547: 	
13548: 	return "$num1:$num2";
13549:     }
13550: }
13551: 
13552: sub rndseed_64bit5 {
13553:     my ($symb,$courseid,$domain,$username)=@_;
13554:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13555:     return "$num1:$num2";
13556: }
13557: 
13558: sub rndseed_CODE_64bit {
13559:     my ($symb,$courseid,$domain,$username)=@_;
13560:     {
13561: 	use integer;
13562: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13563: 	my $symbseed=numval2($symb);
13564: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13565: 	my $CODEseed=numval(&getCODE());
13566: 	my $courseseed=unpack("%32S*",$courseid.' ');
13567: 	my $num1=$symbseed+$CODEchck;
13568: 	my $num2=$CODEseed+$courseseed+$symbchck;
13569: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13570: 	#&logthis("rndseed :$num1:$num2:$symb");
13571: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13572: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13573: 	return "$num1:$num2";
13574:     }
13575: }
13576: 
13577: sub rndseed_CODE_64bit4 {
13578:     my ($symb,$courseid,$domain,$username)=@_;
13579:     {
13580: 	use integer;
13581: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13582: 	my $symbseed=numval3($symb);
13583: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13584: 	my $CODEseed=numval3(&getCODE());
13585: 	my $courseseed=unpack("%32S*",$courseid.' ');
13586: 	my $num1=$symbseed+$CODEchck;
13587: 	my $num2=$CODEseed+$courseseed+$symbchck;
13588: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13589: 	#&logthis("rndseed :$num1:$num2:$symb");
13590: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13591: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13592: 	return "$num1:$num2";
13593:     }
13594: }
13595: 
13596: sub rndseed_CODE_64bit5 {
13597:     my ($symb,$courseid,$domain,$username)=@_;
13598:     my $code = &getCODE();
13599:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13600:     return "$num1:$num2";
13601: }
13602: 
13603: sub setup_random_from_rndseed {
13604:     my ($rndseed)=@_;
13605:     if ($rndseed =~/([,:])/) {
13606:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13607:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13608:             &Math::Random::random_set_seed_from_phrase($rndseed);
13609:         } else {
13610:             &Math::Random::random_set_seed($num1,$num2);
13611:         }
13612:     } else {
13613: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13614:     }
13615: }
13616: 
13617: sub latest_receipt_algorithm_id {
13618:     return 'receipt3';
13619: }
13620: 
13621: sub recunique {
13622:     my $fucourseid=shift;
13623:     my $unique;
13624:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13625: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13626: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13627:     } else {
13628: 	$unique=$perlvar{'lonReceipt'};
13629:     }
13630:     return unpack("%32C*",$unique);
13631: }
13632: 
13633: sub recprefix {
13634:     my $fucourseid=shift;
13635:     my $prefix;
13636:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13637: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13638: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13639:     } else {
13640: 	$prefix=$perlvar{'lonHostID'};
13641:     }
13642:     return unpack("%32C*",$prefix);
13643: }
13644: 
13645: sub ireceipt {
13646:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13647: 
13648:     my $return =&recprefix($fucourseid).'-';
13649: 
13650:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13651: 	$env{'request.state'} eq 'construct') {
13652: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13653: 	return $return;
13654:     }
13655: 
13656:     my $cuname=unpack("%32C*",$funame);
13657:     my $cudom=unpack("%32C*",$fudom);
13658:     my $cucourseid=unpack("%32C*",$fucourseid);
13659:     my $cusymb=unpack("%32C*",$fusymb);
13660:     my $cunique=&recunique($fucourseid);
13661:     my $cpart=unpack("%32S*",$part);
13662:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13663: 
13664: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13665: 			       
13666: 	$return.= ($cunique%$cuname+
13667: 		   $cunique%$cudom+
13668: 		   $cusymb%$cuname+
13669: 		   $cusymb%$cudom+
13670: 		   $cucourseid%$cuname+
13671: 		   $cucourseid%$cudom+
13672: 		   $cpart%$cuname+
13673: 		   $cpart%$cudom);
13674:     } else {
13675: 	$return.= ($cunique%$cuname+
13676: 		   $cunique%$cudom+
13677: 		   $cusymb%$cuname+
13678: 		   $cusymb%$cudom+
13679: 		   $cucourseid%$cuname+
13680: 		   $cucourseid%$cudom);
13681:     }
13682:     return $return;
13683: }
13684: 
13685: sub receipt {
13686:     my ($part)=@_;
13687:     my ($symb,$courseid,$domain,$name) = &whichuser();
13688:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13689: }
13690: 
13691: sub whichuser {
13692:     my ($passedsymb)=@_;
13693:     my ($symb,$courseid,$domain,$name,$publicuser);
13694:     if (defined($env{'form.grade_symb'})) {
13695: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13696: 	my $allowed=&allowed('vgr',$tmp_courseid);
13697: 	if (!$allowed &&
13698: 	    exists($env{'request.course.sec'}) &&
13699: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13700: 	    $allowed=&allowed('vgr',$tmp_courseid.
13701: 			      '/'.$env{'request.course.sec'});
13702: 	}
13703: 	if ($allowed) {
13704: 	    ($symb)=&get_env_multiple('form.grade_symb');
13705: 	    $courseid=$tmp_courseid;
13706: 	    ($domain)=&get_env_multiple('form.grade_domain');
13707: 	    ($name)=&get_env_multiple('form.grade_username');
13708: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13709: 	}
13710:     }
13711:     if (!$passedsymb) {
13712: 	$symb=&symbread();
13713:     } else {
13714: 	$symb=$passedsymb;
13715:     }
13716:     $courseid=$env{'request.course.id'};
13717:     $domain=$env{'user.domain'};
13718:     $name=$env{'user.name'};
13719:     if ($name eq 'public' && $domain eq 'public') {
13720: 	if (!defined($env{'form.username'})) {
13721: 	    $env{'form.username'}.=time.rand(10000000);
13722: 	}
13723: 	$name.=$env{'form.username'};
13724:     }
13725:     return ($symb,$courseid,$domain,$name,$publicuser);
13726: 
13727: }
13728: 
13729: # ------------------------------------------------------------ Serves up a file
13730: # returns either the contents of the file or 
13731: # -1 if the file doesn't exist
13732: #
13733: # if the target is a file that was uploaded via DOCS, 
13734: # a check will be made to see if a current copy exists on the local server,
13735: # if it does this will be served, otherwise a copy will be retrieved from
13736: # the home server for the course and stored in /home/httpd/html/userfiles on
13737: # the local server.   
13738: 
13739: sub getfile {
13740:     my ($file) = @_;
13741:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13742:     &repcopy($file);
13743:     return &readfile($file);
13744: }
13745: 
13746: sub repcopy_userfile {
13747:     my ($file)=@_;
13748:     my $londocroot = $perlvar{'lonDocRoot'};
13749:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13750:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13751:     my ($cdom,$cnum,$filename) = 
13752: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13753:     my $uri="/uploaded/$cdom/$cnum/$filename";
13754:     if (-e "$file") {
13755: # we already have a local copy, check it out
13756: 	my @fileinfo = stat($file);
13757: 	my $rtncode;
13758: 	my $info;
13759: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13760: 	if ($lwpresp ne 'ok') {
13761: # there is no such file anymore, even though we had a local copy
13762: 	    if ($rtncode eq '404') {
13763: 		unlink($file);
13764: 	    }
13765: 	    return -1;
13766: 	}
13767: 	if ($info < $fileinfo[9]) {
13768: # nice, the file we have is up-to-date, just say okay
13769: 	    return 'ok';
13770: 	} else {
13771: # the file is outdated, get rid of it
13772: 	    unlink($file);
13773: 	}
13774:     }
13775: # one way or the other, at this point, we don't have the file
13776: # construct the correct path for the file
13777:     my @parts = ($cdom,$cnum); 
13778:     if ($filename =~ m|^(.+)/[^/]+$|) {
13779: 	push @parts, split(/\//,$1);
13780:     }
13781:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13782:     foreach my $part (@parts) {
13783: 	$path .= '/'.$part;
13784: 	if (!-e $path) {
13785: 	    mkdir($path,0770);
13786: 	}
13787:     }
13788: # now the path exists for sure
13789: # get a user agent
13790:     my $transferfile=$file.'.in.transfer';
13791: # FIXME: this should flock
13792:     if (-e $transferfile) { return 'ok'; }
13793:     my $request;
13794:     $uri=~s/^\///;
13795:     my $homeserver = &homeserver($cnum,$cdom);
13796:     my $hostname = &hostname($homeserver);
13797:     my $protocol = $protocol{$homeserver};
13798:     $protocol = 'http' if ($protocol ne 'https');
13799:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13800:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13801: # did it work?
13802:     if ($response->is_error()) {
13803: 	unlink($transferfile);
13804: 	&logthis("Userfile repcopy failed for $uri");
13805: 	return -1;
13806:     }
13807: # worked, rename the transfer file
13808:     rename($transferfile,$file);
13809:     return 'ok';
13810: }
13811: 
13812: sub tokenwrapper {
13813:     my $uri=shift;
13814:     $uri=~s|^https?\://([^/]+)||;
13815:     $uri=~s|^/||;
13816:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13817:     my $token=$1;
13818:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13819:     if ($udom && $uname && $file) {
13820: 	$file=~s|(\?\.*)*$||;
13821:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13822:         my $homeserver = &homeserver($uname,$udom);
13823:         my $hostname = &hostname($homeserver);
13824:         my $protocol = $protocol{$homeserver};
13825:         $protocol = 'http' if ($protocol ne 'https');
13826:         return $protocol.'://'.$hostname.'/'.$uri.
13827:                (($uri=~/\?/)?'&':'?').'token='.$token.
13828:                                '&tokenissued='.$perlvar{'lonHostID'};
13829:     } else {
13830:         return '/adm/notfound.html';
13831:     }
13832: }
13833: 
13834: # call with reqtype HEAD: get last modification time
13835: # call with reqtype GET: get the file contents
13836: # Do not call this with reqtype GET for large files! It loads everything into memory
13837: #
13838: sub getuploaded {
13839:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13840:     $uri=~s/^\///;
13841:     my $homeserver = &homeserver($cnum,$cdom);
13842:     my $hostname = &hostname($homeserver);
13843:     my $protocol = $protocol{$homeserver};
13844:     $protocol = 'http' if ($protocol ne 'https');
13845:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13846:     my $request=new HTTP::Request($reqtype,$uri);
13847:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13848:     $$rtncode = $response->code;
13849:     if (! $response->is_success()) {
13850: 	return 'failed';
13851:     }      
13852:     if ($reqtype eq 'HEAD') {
13853: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13854:     } elsif ($reqtype eq 'GET') {
13855: 	$$info = $response->content;
13856:     }
13857:     return 'ok';
13858: }
13859: 
13860: sub readfile {
13861:     my $file = shift;
13862:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13863:     my $fh;
13864:     open($fh,"<",$file);
13865:     my $a='';
13866:     while (my $line = <$fh>) { $a .= $line; }
13867:     return $a;
13868: }
13869: 
13870: sub filelocation {
13871:     my ($dir,$file) = @_;
13872:     my $location;
13873:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13874: 
13875:     if ($file =~ m-^/adm/-) {
13876: 	$file=~s-^/adm/wrapper/-/-;
13877: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13878:     }
13879: 
13880:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13881:         $location = $file;
13882:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13883:         my ($udom,$uname,$filename)=
13884:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13885:         my $home=&homeserver($uname,$udom);
13886:         my $is_me=0;
13887:         my @ids=&current_machine_ids();
13888:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13889:         if ($is_me) {
13890:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13891:         } else {
13892:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13893:   	      $udom.'/'.$uname.'/'.$filename;
13894:         }
13895:     } elsif ($file =~ m-^/adm/-) {
13896: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13897:     } else {
13898:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13899:         $file=~s:^/(res|priv)/:/:;
13900:         my $space=$1;
13901:         if ( !( $file =~ m:^/:) ) {
13902:             $location = $dir. '/'.$file;
13903:         } else {
13904:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13905:         }
13906:     }
13907:     $location=~s://+:/:g; # remove duplicate /
13908:     while ($location=~m{/\.\./}) {
13909: 	if ($location =~ m{/[^/]+/\.\./}) {
13910: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13911: 	} else {
13912: 	    $location=~ s{/\.\./}{/}g;
13913: 	}
13914:     } #remove dir/..
13915:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13916:     return $location;
13917: }
13918: 
13919: sub hreflocation {
13920:     my ($dir,$file)=@_;
13921:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13922: 	$file=filelocation($dir,$file);
13923:     } elsif ($file=~m-^/adm/-) {
13924: 	$file=~s-^/adm/wrapper/-/-;
13925: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13926:     }
13927:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13928: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13929:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13930: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13931: 	        {/uploaded/$1/$2/}x;
13932:     }
13933:     if ($file=~ m{^/userfiles/}) {
13934: 	$file =~ s{^/userfiles/}{/uploaded/};
13935:     }
13936:     return $file;
13937: }
13938: 
13939: 
13940: 
13941: 
13942: 
13943: sub current_machine_domains {
13944:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13945: }
13946: 
13947: sub machine_domains {
13948:     my ($hostname) = @_;
13949:     my @domains;
13950:     my %hostname = &all_hostnames();
13951:     while( my($id, $name) = each(%hostname)) {
13952: #	&logthis("-$id-$name-$hostname-");
13953: 	if ($hostname eq $name) {
13954: 	    push(@domains,&host_domain($id));
13955: 	}
13956:     }
13957:     return @domains;
13958: }
13959: 
13960: sub current_machine_ids {
13961:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13962: }
13963: 
13964: sub machine_ids {
13965:     my ($hostname) = @_;
13966:     $hostname ||= &hostname($perlvar{'lonHostID'});
13967:     my @ids;
13968:     my %name_to_host = &all_names();
13969:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13970: 	return @{ $name_to_host{$hostname} };
13971:     }
13972:     return;
13973: }
13974: 
13975: sub additional_machine_domains {
13976:     my @domains;
13977:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13978:     while( my $line = <$fh>) {
13979:         $line =~ s/\s//g;
13980:         push(@domains,$line);
13981:     }
13982:     return @domains;
13983: }
13984: 
13985: sub default_login_domain {
13986:     my $domain = $perlvar{'lonDefDomain'};
13987:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13988:     foreach my $posdom (&current_machine_domains(),
13989:                         &additional_machine_domains()) {
13990:         if (lc($posdom) eq lc($testdomain)) {
13991:             $domain=$posdom;
13992:             last;
13993:         }
13994:     }
13995:     return $domain;
13996: }
13997: 
13998: sub uses_sts {
13999:     my ($ignore_cache) = @_;
14000:     my $lonhost = $perlvar{'lonHostID'};
14001:     my $hostname = &hostname($lonhost);
14002:     my $sts_on;
14003:     if ($protocol{$lonhost} eq 'https') {
14004:         my $cachetime = 12*3600;
14005:         if (!$ignore_cache) {
14006:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14007:             if (defined($cached)) {
14008:                 return $sts_on;
14009:             }
14010:         }
14011:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14012:         my $request=new HTTP::Request('HEAD',$url);
14013:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14014:         if ($response->is_success) {
14015:             my $has_sts = $response->header('Strict-Transport-Security');
14016:             if ($has_sts eq '') {
14017:                 $sts_on = 0;
14018:             } else {
14019:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14020:                     my $maxage = $1;
14021:                     if ($maxage) {
14022:                         $sts_on = 1;
14023:                     } else {
14024:                         $sts_on = 0;
14025:                     }
14026:                 } else {
14027:                     $sts_on = 0;
14028:                 }
14029:             }
14030:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14031:         }
14032:     }
14033:     return;
14034: }
14035: 
14036: # ------------------------------------------------------------- Declutters URLs
14037: 
14038: sub declutter {
14039:     my $thisfn=shift;
14040:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14041:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14042:         $thisfn=~s{^/home/httpd/html}{};
14043:     }
14044:     $thisfn=~s/^\///;
14045:     $thisfn=~s|^adm/wrapper/||;
14046:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14047:     $thisfn=~s/^res\///;
14048:     $thisfn=~s/^priv\///;
14049:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14050:         $thisfn=~s/\?.+$//;
14051:     }
14052:     return $thisfn;
14053: }
14054: 
14055: # ------------------------------------------------------------- Clutter up URLs
14056: 
14057: sub clutter {
14058:     my $thisfn='/'.&declutter(shift);
14059:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14060: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14061:        $thisfn='/res'.$thisfn; 
14062:     }
14063:     if ($thisfn !~m|^/adm|) {
14064: 	if ($thisfn =~ m|^/ext/|) {
14065: 	    $thisfn='/adm/wrapper'.$thisfn;
14066: 	} else {
14067: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14068: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14069: 	    if ($embstyle eq 'ssi'
14070: 		|| ($embstyle eq 'hdn')
14071: 		|| ($embstyle eq 'rat')
14072: 		|| ($embstyle eq 'prv')
14073: 		|| ($embstyle eq 'ign')) {
14074: 		#do nothing with these
14075: 	    } elsif (($embstyle eq 'img') 
14076: 		|| ($embstyle eq 'emb')
14077: 		|| ($embstyle eq 'wrp')) {
14078: 		$thisfn='/adm/wrapper'.$thisfn;
14079: 	    } elsif ($embstyle eq 'unk'
14080: 		     && $thisfn!~/\.(sequence|page)$/) {
14081: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14082: 	    } else {
14083: #		&logthis("Got a blank emb style");
14084: 	    }
14085: 	}
14086:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14087:         $thisfn='/adm/wrapper'.$thisfn;
14088:     }
14089:     return $thisfn;
14090: }
14091: 
14092: sub clutter_with_no_wrapper {
14093:     my $uri = &clutter(shift);
14094:     if ($uri =~ m-^/adm/-) {
14095: 	$uri =~ s-^/adm/wrapper/-/-;
14096: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14097:     }
14098:     return $uri;
14099: }
14100: 
14101: sub freeze_escape {
14102:     my ($value)=@_;
14103:     if (ref($value)) {
14104: 	$value=&nfreeze($value);
14105: 	return '__FROZEN__'.&escape($value);
14106:     }
14107:     return &escape($value);
14108: }
14109: 
14110: 
14111: sub thaw_unescape {
14112:     my ($value)=@_;
14113:     if ($value =~ /^__FROZEN__/) {
14114: 	substr($value,0,10,undef);
14115: 	$value=&unescape($value);
14116: 	return &thaw($value);
14117:     }
14118:     return &unescape($value);
14119: }
14120: 
14121: sub correct_line_ends {
14122:     my ($result)=@_;
14123:     $$result =~s/\r\n/\n/mg;
14124:     $$result =~s/\r/\n/mg;
14125: }
14126: # ================================================================ Main Program
14127: 
14128: sub goodbye {
14129:    &logthis("Starting Shut down");
14130: #not converted to using infrastruture and probably shouldn't be
14131:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14132: #converted
14133: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14134:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14135: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14136: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14137: #1.1 only
14138: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14139: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14140: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14141: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14142:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14143:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14144:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14145:    &flushcourselogs();
14146:    &logthis("Shutting down");
14147: }
14148: 
14149: sub get_dns {
14150:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14151:     if (!$ignore_cache) {
14152: 	my ($content,$cached)=
14153: 	    &Apache::lonnet::is_cached_new('dns',$url);
14154: 	if ($cached) {
14155: 	    &$func($content,$hashref);
14156: 	    return;
14157: 	}
14158:     }
14159: 
14160:     my %alldns;
14161:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14162:         foreach my $dns (<$config>) {
14163: 	    next if ($dns !~ /^\^(\S*)/x);
14164:             my $line = $1;
14165:             my ($host,$protocol) = split(/:/,$line);
14166:             if ($protocol ne 'https') {
14167:                 $protocol = 'http';
14168:             }
14169: 	    $alldns{$host} = $protocol;
14170:         }
14171:         close($config);
14172:     }
14173:     while (%alldns) {
14174: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14175: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14176:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14177:         delete($alldns{$dns});
14178: 	next if ($response->is_error());
14179:         if ($url eq '/adm/dns/loncapaCRL') {
14180:             return &$func($response);
14181:         } else {
14182: 	    my @content = split("\n",$response->content);
14183: 	    unless ($nocache) {
14184: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14185: 	    }
14186: 	    &$func(\@content,$hashref);
14187:             return;
14188:         }
14189:     }
14190:     my $which = (split('/',$url,4))[3];
14191:     if ($which eq 'loncapaCRL') {
14192:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14193:         if (-e $diskfile) {
14194:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14195:         } else {
14196:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14197:         }
14198:     } else {
14199:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14200:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14201:             my @content = <$config>;
14202:             close($config);
14203:             &$func(\@content,$hashref);
14204:         }
14205:     }
14206:     return;
14207: }
14208: 
14209: # ------------------------------------------------------Get DNS checksums file
14210: sub parse_dns_checksums_tab {
14211:     my ($lines,$hashref) = @_;
14212:     my $lonhost = $perlvar{'lonHostID'};
14213:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14214:     my $loncaparev = &get_server_loncaparev($machine_dom);
14215:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14216:     my $webconfdir = '/etc/httpd/conf';
14217:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14218:         $webconfdir = '/etc/apache2';
14219:     } elsif ($distro =~ /^sles(\d+)$/) {
14220:         if ($1 >= 10) {
14221:             $webconfdir = '/etc/apache2';
14222:         }
14223:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14224:         if ($1 >= 10.0) {
14225:             $webconfdir = '/etc/apache2';
14226:         }
14227:     }
14228:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14229:     my (%chksum,%revnum);
14230:     if (ref($lines) eq 'ARRAY') {
14231:         chomp(@{$lines});
14232:         my $version = shift(@{$lines});
14233:         if ($version eq $release) {  
14234:             foreach my $line (@{$lines}) {
14235:                 my ($file,$version,$shasum) = split(/,/,$line);
14236:                 if ($file =~ m{^/etc/httpd/conf}) {
14237:                     if ($webconfdir eq '/etc/apache2') {
14238:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14239:                     }
14240:                 }
14241:                 $chksum{$file} = $shasum;
14242:                 $revnum{$file} = $version;
14243:             }
14244:             if (ref($hashref) eq 'HASH') {
14245:                 %{$hashref} = (
14246:                                 sums     => \%chksum,
14247:                                 versions => \%revnum,
14248:                               );
14249:             }
14250:         }
14251:     }
14252:     return;
14253: }
14254: 
14255: sub fetch_dns_checksums {
14256:     my %checksums;
14257:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14258:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14259:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14260:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14261:              \%checksums);
14262:     return \%checksums;
14263: }
14264: 
14265: sub fetch_crl_pemfile {
14266:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14267: }
14268: 
14269: sub save_crl_pem {
14270:     my ($response) = @_;
14271:     my ($msg,$hadchanges);
14272:     if (ref($response)) {
14273:         my $now = time;
14274:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14275:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14276:         if (open(my $fh,'>',"$tmpcrl")) {
14277:             print $fh $response->content;
14278:             close($fh);
14279:             if (-e $lonca) {
14280:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14281:                     my $check = <PIPE>;
14282:                     close(PIPE);
14283:                     chomp($check);
14284:                     if ($check eq 'verify OK') {
14285:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14286:                         my $backup;
14287:                         if (-e $dest) {
14288:                             if (&File::Copy::move($dest,"$dest.bak")) {
14289:                                 $backup = 'ok';
14290:                             }
14291:                         }
14292:                         if (&File::Copy::move($tmpcrl,$dest)) {
14293:                             $msg = 'ok';
14294:                             if ($backup) {
14295:                                 my (%oldnums,%newnums);
14296:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14297:                                     while (<PIPE>) {
14298:                                         $oldnums{(split(/:/))[1]} = 1;
14299:                                     }
14300:                                     close(PIPE);
14301:                                 }
14302:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14303:                                     while(<PIPE>) {
14304:                                         $newnums{(split(/:/))[1]} = 1;
14305:                                     }
14306:                                     close(PIPE);
14307:                                 }
14308:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14309:                                     unless (exists($oldnums{$key})) {
14310:                                         $hadchanges = 1;
14311:                                         last;
14312:                                     }
14313:                                 }
14314:                                 unless ($hadchanges) {
14315:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14316:                                         unless (exists($newnums{$key})) {
14317:                                             $hadchanges = 1;
14318:                                             last;
14319:                                         }
14320:                                     }
14321:                                 }
14322:                             }
14323:                         }
14324:                     } else {
14325:                         unlink($tmpcrl);
14326:                     }
14327:                 } else {
14328:                     unlink($tmpcrl);
14329:                 }
14330:             } else {
14331:                 unlink($tmpcrl);
14332:             }
14333:         }
14334:     }
14335:     return ($msg,$hadchanges);
14336: }
14337: 
14338: # ------------------------------------------------------------ Read domain file
14339: {
14340:     my $loaded;
14341:     my %domain;
14342: 
14343:     sub parse_domain_tab {
14344: 	my ($lines) = @_;
14345: 	foreach my $line (@$lines) {
14346: 	    next if ($line =~ /^(\#|\s*$ )/x);
14347: 
14348: 	    chomp($line);
14349: 	    my ($name,@elements) = split(/:/,$line,9);
14350: 	    my %this_domain;
14351: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14352: 			       'lang_def', 'city', 'longi', 'lati',
14353: 			       'primary') {
14354: 		$this_domain{$field} = shift(@elements);
14355: 	    }
14356: 	    $domain{$name} = \%this_domain;
14357: 	}
14358:     }
14359: 
14360:     sub reset_domain_info {
14361: 	undef($loaded);
14362: 	undef(%domain);
14363:     }
14364: 
14365:     sub load_domain_tab {
14366: 	my ($ignore_cache,$nocache) = @_;
14367: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14368: 	my $fh;
14369: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14370: 	    my @lines = <$fh>;
14371: 	    &parse_domain_tab(\@lines);
14372: 	}
14373: 	close($fh);
14374: 	$loaded = 1;
14375:     }
14376: 
14377:     sub domain {
14378: 	&load_domain_tab() if (!$loaded);
14379: 
14380: 	my ($name,$what) = @_;
14381: 	return if ( !exists($domain{$name}) );
14382: 
14383: 	if (!$what) {
14384: 	    return $domain{$name}{'description'};
14385: 	}
14386: 	return $domain{$name}{$what};
14387:     }
14388: 
14389:     sub domain_info {
14390:         &load_domain_tab() if (!$loaded);
14391:         return %domain;
14392:     }
14393: 
14394: }
14395: 
14396: 
14397: # ------------------------------------------------------------- Read hosts file
14398: {
14399:     my %hostname;
14400:     my %hostdom;
14401:     my %libserv;
14402:     my $loaded;
14403:     my %name_to_host;
14404:     my %internetdom;
14405:     my %LC_dns_serv;
14406: 
14407:     sub parse_hosts_tab {
14408: 	my ($file) = @_;
14409: 	foreach my $configline (@$file) {
14410: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14411:             chomp($configline);
14412: 	    if ($configline =~ /^\^/) {
14413:                 if ($configline =~ /^\^([\w.\-]+)/) {
14414:                     $LC_dns_serv{$1} = 1;
14415:                 }
14416:                 next;
14417:             }
14418: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14419: 	    $name=~s/\s//g;
14420: 	    if ($id && $domain && $role && $name) {
14421:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14422:                     my $curr = $hostname{$id};
14423:                     my $skip;
14424:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14425:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14426:                             $skip = 1;
14427:                         } else {
14428:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14429:                         }
14430:                     }
14431:                     unless ($skip) {
14432:                         push(@{$name_to_host{$name}},$id);
14433:                     }
14434:                 } else {
14435:                     push(@{$name_to_host{$name}},$id);
14436:                 }
14437: 		$hostname{$id}=$name;
14438: 		$hostdom{$id}=$domain;
14439: 		if ($role eq 'library') { $libserv{$id}=$name; }
14440:                 if (defined($protocol)) {
14441:                     if ($protocol eq 'https') {
14442:                         $protocol{$id} = $protocol;
14443:                     } else {
14444:                         $protocol{$id} = 'http'; 
14445:                     }
14446:                 } else {
14447:                     $protocol{$id} = 'http';
14448:                 }
14449:                 if (defined($intdom)) {
14450:                     $internetdom{$id} = $intdom;
14451:                 }
14452: 	    }
14453: 	}
14454:     }
14455:     
14456:     sub reset_hosts_info {
14457: 	&purge_remembered();
14458: 	&reset_domain_info();
14459: 	&reset_hosts_ip_info();
14460:         undef(%internetdom);
14461: 	undef(%name_to_host);
14462: 	undef(%hostname);
14463: 	undef(%hostdom);
14464: 	undef(%libserv);
14465: 	undef($loaded);
14466:     }
14467: 
14468:     sub load_hosts_tab {
14469: 	my ($ignore_cache,$nocache) = @_;
14470: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14471: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14472: 	my @config = <$config>;
14473: 	&parse_hosts_tab(\@config);
14474: 	close($config);
14475: 	$loaded=1;
14476:     }
14477: 
14478:     sub hostname {
14479: 	&load_hosts_tab() if (!$loaded);
14480: 
14481: 	my ($lonid) = @_;
14482: 	return $hostname{$lonid};
14483:     }
14484: 
14485:     sub all_hostnames {
14486: 	&load_hosts_tab() if (!$loaded);
14487: 
14488: 	return %hostname;
14489:     }
14490: 
14491:     sub all_names {
14492:         my ($ignore_cache,$nocache) = @_;
14493: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14494: 
14495: 	return %name_to_host;
14496:     }
14497: 
14498:     sub all_host_domain {
14499:         &load_hosts_tab() if (!$loaded);
14500:         return %hostdom;
14501:     }
14502: 
14503:     sub all_host_intdom {
14504:         &load_hosts_tab() if (!$loaded);
14505:         return %internetdom;
14506:     }
14507: 
14508:     sub is_library {
14509: 	&load_hosts_tab() if (!$loaded);
14510: 
14511: 	return exists($libserv{$_[0]});
14512:     }
14513: 
14514:     sub all_library {
14515: 	&load_hosts_tab() if (!$loaded);
14516: 
14517: 	return %libserv;
14518:     }
14519: 
14520:     sub unique_library {
14521: 	#2x reverse removes all hostnames that appear more than once
14522:         my %unique = reverse &all_library();
14523:         return reverse %unique;
14524:     }
14525: 
14526:     sub get_servers {
14527: 	&load_hosts_tab() if (!$loaded);
14528: 
14529: 	my ($domain,$type) = @_;
14530: 	my %possible_hosts = ($type eq 'library') ? %libserv
14531: 	                                          : %hostname;
14532: 	my %result;
14533: 	if (ref($domain) eq 'ARRAY') {
14534: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14535: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14536: 		    $result{$host} = $hostname;
14537: 		}
14538: 	    }
14539: 	} else {
14540: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14541: 		if ($hostdom{$host} eq $domain) {
14542: 		    $result{$host} = $hostname;
14543: 		}
14544: 	    }
14545: 	}
14546: 	return %result;
14547:     }
14548: 
14549:     sub get_unique_servers {
14550:         my %unique = reverse &get_servers(@_);
14551: 	return reverse %unique;
14552:     }
14553: 
14554:     sub host_domain {
14555: 	&load_hosts_tab() if (!$loaded);
14556: 
14557: 	my ($lonid) = @_;
14558: 	return $hostdom{$lonid};
14559:     }
14560: 
14561:     sub all_domains {
14562: 	&load_hosts_tab() if (!$loaded);
14563: 
14564: 	my %seen;
14565: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14566: 	return @uniq;
14567:     }
14568: 
14569:     sub internet_dom {
14570:         &load_hosts_tab() if (!$loaded);
14571: 
14572:         my ($lonid) = @_;
14573:         return $internetdom{$lonid};
14574:     }
14575: 
14576:     sub is_LC_dns {
14577:         &load_hosts_tab() if (!$loaded);
14578: 
14579:         my ($hostname) = @_;
14580:         return exists($LC_dns_serv{$hostname});
14581:     }
14582: 
14583: }
14584: 
14585: { 
14586:     my %iphost;
14587:     my %name_to_ip;
14588:     my %lonid_to_ip;
14589: 
14590:     sub get_hosts_from_ip {
14591: 	my ($ip) = @_;
14592: 	my %iphosts = &get_iphost();
14593: 	if (ref($iphosts{$ip})) {
14594: 	    return @{$iphosts{$ip}};
14595: 	}
14596: 	return;
14597:     }
14598:     
14599:     sub reset_hosts_ip_info {
14600: 	undef(%iphost);
14601: 	undef(%name_to_ip);
14602: 	undef(%lonid_to_ip);
14603:     }
14604: 
14605:     sub get_host_ip {
14606: 	my ($lonid) = @_;
14607: 	if (exists($lonid_to_ip{$lonid})) {
14608: 	    return $lonid_to_ip{$lonid};
14609: 	}
14610: 	my $name=&hostname($lonid);
14611:    	my $ip = gethostbyname($name);
14612: 	return if (!$ip || length($ip) ne 4);
14613: 	$ip=inet_ntoa($ip);
14614: 	$name_to_ip{$name}   = $ip;
14615: 	$lonid_to_ip{$lonid} = $ip;
14616: 	return $ip;
14617:     }
14618:     
14619:     sub get_iphost {
14620: 	my ($ignore_cache,$nocache) = @_;
14621: 
14622: 	if (!$ignore_cache) {
14623: 	    if (%iphost) {
14624: 		return %iphost;
14625: 	    }
14626: 	    my ($ip_info,$cached)=
14627: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14628: 	    if ($cached) {
14629: 		%iphost      = %{$ip_info->[0]};
14630: 		%name_to_ip  = %{$ip_info->[1]};
14631: 		%lonid_to_ip = %{$ip_info->[2]};
14632: 		return %iphost;
14633: 	    }
14634: 	}
14635: 
14636: 	# get yesterday's info for fallback
14637: 	my %old_name_to_ip;
14638: 	my ($ip_info,$cached)=
14639: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14640: 	if ($cached) {
14641: 	    %old_name_to_ip = %{$ip_info->[1]};
14642: 	}
14643: 
14644: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14645: 	foreach my $name (keys(%name_to_host)) {
14646: 	    my $ip;
14647: 	    if (!exists($name_to_ip{$name})) {
14648: 		$ip = gethostbyname($name);
14649: 		if (!$ip || length($ip) ne 4) {
14650: 		    if (defined($old_name_to_ip{$name})) {
14651: 			$ip = $old_name_to_ip{$name};
14652: 			&logthis("Can't find $name defaulting to old $ip");
14653: 		    } else {
14654: 			&logthis("Name $name no IP found");
14655: 			next;
14656: 		    }
14657: 		} else {
14658: 		    $ip=inet_ntoa($ip);
14659: 		}
14660: 		$name_to_ip{$name} = $ip;
14661: 	    } else {
14662: 		$ip = $name_to_ip{$name};
14663: 	    }
14664: 	    foreach my $id (@{ $name_to_host{$name} }) {
14665: 		$lonid_to_ip{$id} = $ip;
14666: 	    }
14667: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14668: 	}
14669:         unless ($nocache) {
14670: 	    &do_cache_new('iphost','iphost',
14671: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14672: 		          48*60*60);
14673:         }
14674: 
14675: 	return %iphost;
14676:     }
14677: 
14678:     #
14679:     #  Given a DNS returns the loncapa host name for that DNS 
14680:     # 
14681:     sub host_from_dns {
14682:         my ($dns) = @_;
14683:         my @hosts;
14684:         my $ip;
14685: 
14686:         if (exists($name_to_ip{$dns})) {
14687:             $ip = $name_to_ip{$dns};
14688:         }
14689:         if (!$ip) {
14690:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14691:             if (length($ip) == 4) { 
14692: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14693:             }
14694:         }
14695:         if ($ip) {
14696: 	    @hosts = get_hosts_from_ip($ip);
14697: 	    return $hosts[0];
14698:         }
14699:         return undef;
14700:     }
14701: 
14702:     sub get_internet_names {
14703:         my ($lonid) = @_;
14704:         return if ($lonid eq '');
14705:         my ($idnref,$cached)=
14706:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14707:         if ($cached) {
14708:             return $idnref;
14709:         }
14710:         my $ip = &get_host_ip($lonid);
14711:         my @hosts = &get_hosts_from_ip($ip);
14712:         my %iphost = &get_iphost();
14713:         my (@idns,%seen);
14714:         foreach my $id (@hosts) {
14715:             my $dom = &host_domain($id);
14716:             my $prim_id = &domain($dom,'primary');
14717:             my $prim_ip = &get_host_ip($prim_id);
14718:             next if ($seen{$prim_ip});
14719:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14720:                 foreach my $id (@{$iphost{$prim_ip}}) {
14721:                     my $intdom = &internet_dom($id);
14722:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14723:                         push(@idns,$intdom);
14724:                     }
14725:                 }
14726:             }
14727:             $seen{$prim_ip} = 1;
14728:         }
14729:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14730:     }
14731: 
14732: }
14733: 
14734: sub all_loncaparevs {
14735:     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);
14736: }
14737: 
14738: # ---------------------------------------------------------- Read loncaparev table
14739: {
14740:     sub load_loncaparevs { 
14741:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14742:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14743:                 while (my $configline=<$config>) {
14744:                     chomp($configline);
14745:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14746:                     $loncaparevs{$hostid}=$loncaparev;
14747:                 }
14748:                 close($config);
14749:             }
14750:         }
14751:     }
14752: }
14753: 
14754: # ---------------------------------------------------------- Read serverhostID table
14755: {
14756:     sub load_serverhomeIDs {
14757:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14758:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14759:                 while (my $configline=<$config>) {
14760:                     chomp($configline);
14761:                     my ($name,$id)=split(/:/,$configline);
14762:                     $serverhomeIDs{$name}=$id;
14763:                 }
14764:                 close($config);
14765:             }
14766:         }
14767:     }
14768: }
14769: 
14770: 
14771: BEGIN {
14772: 
14773: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14774:     unless ($readit) {
14775: {
14776:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14777:     %perlvar = (%perlvar,%{$configvars});
14778: }
14779: 
14780: 
14781: # ------------------------------------------------------ Read spare server file
14782: {
14783:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14784: 
14785:     while (my $configline=<$config>) {
14786:        chomp($configline);
14787:        if ($configline) {
14788: 	   my ($host,$type) = split(':',$configline,2);
14789: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14790: 	   push(@{ $spareid{$type} }, $host);
14791:        }
14792:     }
14793:     close($config);
14794: }
14795: # ------------------------------------------------------------ Read permissions
14796: {
14797:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14798: 
14799:     while (my $configline=<$config>) {
14800: 	chomp($configline);
14801: 	if ($configline) {
14802: 	    my ($role,$perm)=split(/ /,$configline);
14803: 	    if ($perm ne '') { $pr{$role}=$perm; }
14804: 	}
14805:     }
14806:     close($config);
14807: }
14808: 
14809: # -------------------------------------------- Read plain texts for permissions
14810: {
14811:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14812: 
14813:     while (my $configline=<$config>) {
14814: 	chomp($configline);
14815: 	if ($configline) {
14816: 	    my ($short,@plain)=split(/:/,$configline);
14817:             %{$prp{$short}} = ();
14818: 	    if (@plain > 0) {
14819:                 $prp{$short}{'std'} = $plain[0];
14820:                 for (my $i=1; $i<@plain; $i++) {
14821:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14822:                 }
14823:             }
14824: 	}
14825:     }
14826:     close($config);
14827: }
14828: 
14829: # ---------------------------------------------------------- Read package table
14830: {
14831:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14832: 
14833:     while (my $configline=<$config>) {
14834: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14835: 	chomp($configline);
14836: 	my ($short,$plain)=split(/:/,$configline);
14837: 	my ($pack,$name)=split(/\&/,$short);
14838: 	if ($plain ne '') {
14839: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14840: 	    $packagetab{$short}=$plain; 
14841: 	}
14842:     }
14843:     close($config);
14844: }
14845: 
14846: # ---------------------------------------------------------- Read loncaparev table
14847: 
14848: &load_loncaparevs();
14849: 
14850: # ---------------------------------------------------------- Read serverhostID table
14851: 
14852: &load_serverhomeIDs();
14853: 
14854: # ---------------------------------------------------------- Read releaseslist XML
14855: {
14856:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14857:     if (-e $file) {
14858:         my $parser = HTML::LCParser->new($file);
14859:         while (my $token = $parser->get_token()) {
14860:             if ($token->[0] eq 'S') {
14861:                 my $item = $token->[1];
14862:                 my $name = $token->[2]{'name'};
14863:                 my $value = $token->[2]{'value'};
14864:                 my $valuematch = $token->[2]{'valuematch'};
14865:                 my $namematch = $token->[2]{'namematch'};
14866:                 if ($item eq 'parameter') {
14867:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14868:                         my $release = $parser->get_text();
14869:                         $release =~ s/(^\s*|\s*$ )//gx;
14870:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14871:                     }
14872:                 } elsif ($item ne '' && $name ne '') {
14873:                     my $release = $parser->get_text();
14874:                     $release =~ s/(^\s*|\s*$ )//gx;
14875:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14876:                 }
14877:             }
14878:         }
14879:     }
14880: }
14881: 
14882: # ---------------------------------------------------------- Read managers table
14883: {
14884:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14885:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14886:             while (my $configline=<$config>) {
14887:                 chomp($configline);
14888:                 next if ($configline =~ /^\#/);
14889:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14890:                     $managerstab{$configline} = 1;
14891:                 }
14892:             }
14893:             close($config);
14894:         }
14895:     }
14896: }
14897: 
14898: # ------------- set up temporary directory
14899: {
14900:     $tmpdir = LONCAPA::tempdir();
14901: 
14902: }
14903: 
14904: # ------------- set default texengine (domain default overrides this)
14905: {
14906:     $deftex = LONCAPA::texengine();
14907: }
14908: 
14909: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14910: 				'compress_threshold'=> 20_000,
14911:  			        });
14912: 
14913: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14914: $dumpcount=0;
14915: $locknum=0;
14916: 
14917: &logtouch();
14918: &logthis('<font color="yellow">INFO: Read configuration</font>');
14919: $readit=1;
14920:     {
14921: 	use integer;
14922: 	my $test=(2**32)+1;
14923: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14924: 	&logthis(" Detected 64bit platform ($_64bit)");
14925:     }
14926: }
14927: }
14928: 
14929: 1;
14930: __END__
14931: 
14932: =pod
14933: 
14934: =head1 NAME
14935: 
14936: Apache::lonnet - Subroutines to ask questions about things in the network.
14937: 
14938: =head1 SYNOPSIS
14939: 
14940: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14941: 
14942:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14943: 
14944: Common parameters:
14945: 
14946: =over 4
14947: 
14948: =item *
14949: 
14950: $uname : an internal username (if $cname expecting a course Id specifically)
14951: 
14952: =item *
14953: 
14954: $udom : a domain (if $cdom expecting a course's domain specifically)
14955: 
14956: =item *
14957: 
14958: $symb : a resource instance identifier
14959: 
14960: =item *
14961: 
14962: $namespace : the name of a .db file that contains the data needed or
14963: being set.
14964: 
14965: =back
14966: 
14967: =head1 OVERVIEW
14968: 
14969: lonnet provides subroutines which interact with the
14970: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14971: about classes, users, and resources.
14972: 
14973: For many of these objects you can also use this to store data about
14974: them or modify them in various ways.
14975: 
14976: =head2 Symbs
14977: 
14978: To identify a specific instance of a resource, LON-CAPA uses symbols
14979: or "symbs"X<symb>. These identifiers are built from the URL of the
14980: map, the resource number of the resource in the map, and the URL of
14981: the resource itself. The latter is somewhat redundant, but might help
14982: if maps change.
14983: 
14984: An example is
14985: 
14986:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14987: 
14988: The respective map entry is
14989: 
14990:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14991:   title="Problem 2">
14992:  </resource>
14993: 
14994: Symbs are used by the random number generator, as well as to store and
14995: restore data specific to a certain instance of for example a problem.
14996: 
14997: =head2 Storing And Retrieving Data
14998: 
14999: X<store()>X<cstore()>X<restore()>Three of the most important functions
15000: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15001: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15002: is is the non-critical message twin of cstore. These functions are for
15003: handlers to store a perl hash to a user's permanent data space in an
15004: easy manner, and to retrieve it again on another call. It is expected
15005: that a handler would use this once at the beginning to retrieve data,
15006: and then again once at the end to send only the new data back.
15007: 
15008: The data is stored in the user's data directory on the user's
15009: homeserver under the ID of the course.
15010: 
15011: The hash that is returned by restore will have all of the previous
15012: value for all of the elements of the hash.
15013: 
15014: Example:
15015: 
15016:  #creating a hash
15017:  my %hash;
15018:  $hash{'foo'}='bar';
15019: 
15020:  #storing it
15021:  &Apache::lonnet::cstore(\%hash);
15022: 
15023:  #changing a value
15024:  $hash{'foo'}='notbar';
15025: 
15026:  #adding a new value
15027:  $hash{'bar'}='foo';
15028:  &Apache::lonnet::cstore(\%hash);
15029: 
15030:  #retrieving the hash
15031:  my %history=&Apache::lonnet::restore();
15032: 
15033:  #print the hash
15034:  foreach my $key (sort(keys(%history))) {
15035:    print("\%history{$key} = $history{$key}");
15036:  }
15037: 
15038: Will print out:
15039: 
15040:  %history{1:foo} = bar
15041:  %history{1:keys} = foo:timestamp
15042:  %history{1:timestamp} = 990455579
15043:  %history{2:bar} = foo
15044:  %history{2:foo} = notbar
15045:  %history{2:keys} = foo:bar:timestamp
15046:  %history{2:timestamp} = 990455580
15047:  %history{bar} = foo
15048:  %history{foo} = notbar
15049:  %history{timestamp} = 990455580
15050:  %history{version} = 2
15051: 
15052: Note that the special hash entries C<keys>, C<version> and
15053: C<timestamp> were added to the hash. C<version> will be equal to the
15054: total number of versions of the data that have been stored. The
15055: C<timestamp> attribute will be the UNIX time the hash was
15056: stored. C<keys> is available in every historical section to list which
15057: keys were added or changed at a specific historical revision of a
15058: hash.
15059: 
15060: B<Warning>: do not store the hash that restore returns directly. This
15061: will cause a mess since it will restore the historical keys as if the
15062: were new keys. I.E. 1:foo will become 1:1:foo etc.
15063: 
15064: Calling convention:
15065: 
15066:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15067:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15068: 
15069: For more detailed information, see lonnet specific documentation.
15070: 
15071: =head1 RETURN MESSAGES
15072: 
15073: =over 4
15074: 
15075: =item * B<con_lost>: unable to contact remote host
15076: 
15077: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15078: when the connection is brought back up
15079: 
15080: =item * B<con_failed>: unable to contact remote host and unable to save message
15081: for later delivery
15082: 
15083: =item * B<error:>: an error a occurred, a description of the error follows the :
15084: 
15085: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15086: that was requested
15087: 
15088: =back
15089: 
15090: =head1 PUBLIC SUBROUTINES
15091: 
15092: =head2 Session Environment Functions
15093: 
15094: =over 4
15095: 
15096: =item * 
15097: X<appenv()>
15098: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15099: the user envirnoment file, and will be restored for each access this
15100: user makes during this session, also modifies the %env for the current
15101: process. Optional rolesarrayref - if defined contains a reference to an array
15102: of roles which are exempt from the restriction on modifying user.role entries 
15103: in the user's environment.db and in %env.    
15104: 
15105: =item *
15106: X<delenv()>
15107: B<delenv($delthis,$regexp)>: removes all items from the session
15108: environment file that begin with $delthis. If the 
15109: optional second arg - $regexp - is true, $delthis is treated as a 
15110: regular expression, otherwise \Q$delthis\E is used. 
15111: The values are also deleted from the current processes %env.
15112: 
15113: =item * get_env_multiple($name) 
15114: 
15115: gets $name from the %env hash, it seemlessly handles the cases where multiple
15116: values may be defined and end up as an array ref.
15117: 
15118: returns an array of values
15119: 
15120: =back
15121: 
15122: =head2 User Information
15123: 
15124: =over 4
15125: 
15126: =item *
15127: X<queryauthenticate()>
15128: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15129: authentication scheme
15130: 
15131: =item *
15132: X<authenticate()>
15133: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15134: authenticate user from domain's lib servers (first use the current
15135: one). C<$upass> should be the users password.
15136: $checkdefauth is optional (value is 1 if a check should be made to
15137:    authenticate user using default authentication method, and allow
15138:    account creation if username does not have account in the domain).
15139: $clientcancheckhost is optional (value is 1 if checking whether the
15140:    server can host will occur on the client side in lonauth.pm).   
15141: 
15142: =item *
15143: X<homeserver()>
15144: B<homeserver($uname,$udom)>: find the server which has
15145: the user's directory and files (there must be only one), this caches
15146: the answer, and also caches if there is a borken connection.
15147: 
15148: =item *
15149: X<idget()>
15150: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15151: a list of student/employee IDs or clicker IDs
15152: (student/employee IDs are a unique resource in a domain, there must be 
15153: only 1 ID per username, and only 1 username per ID in a specific domain).
15154: clickerIDs are not necessarily unique, as students might share clickers.
15155: (returns hash: id=>name,id=>name)
15156: 
15157: =item *
15158: X<idrget()>
15159: B<idrget($udom,@unames)>: find the IDs behind a list of
15160: usernames (returns hash: name=>id,name=>id)
15161: 
15162: =item *
15163: X<idput()>
15164: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15165: names and associated student/employee IDs or clicker IDs.
15166: 
15167: =item *
15168: X<iddel()>
15169: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15170: student/employee ID or clicker ID username look-ups from domain.
15171: The homeserver ($uhome) and namespace ($namespace) are optional.
15172: If no $uhome is provided, it will be determined usig &homeserver()
15173: for each user.  If no $namespace is provided, the default is ids.
15174: 
15175: =item *
15176: X<updateclickers()>
15177: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15178: clicker ID-to-username look-ups in clickers.db on library server.
15179: Permitted actions are add or del (i.e., add or delete). The 
15180: clickers.db contains clickerID as keys (escaped), and each corresponding
15181: value is an escaped comma-separated list of usernames (for whom the
15182: library server is the homeserver), who registered that particular ID.
15183: If $critical is true, the update will be sent via &critical, otherwise
15184: &reply() will be used.
15185: 
15186: =item *
15187: X<rolesinit()>
15188: B<rolesinit($udom,$username)>: get user privileges.
15189: returns user role, first access and timer interval hashes
15190: 
15191: =item *
15192: X<privileged()>
15193: B<privileged($username,$domain)>: returns a true if user has a
15194: privileged and active role (i.e. su or dc), false otherwise.
15195: 
15196: =item *
15197: X<getsection()>
15198: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15199: course $cname, return section name/number or '' for "not in course"
15200: and '-1' for "no section"
15201: 
15202: =item *
15203: X<userenvironment()>
15204: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15205: passed in @what from the requested user's environment, returns a hash
15206: 
15207: =item * 
15208: X<userlog_query()>
15209: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15210: activity.log file. %filters defines filters applied when parsing the
15211: log file. These can be start or end timestamps, or the type of action
15212: - log to look for Login or Logout events, check for Checkin or
15213: Checkout, role for role selection. The response is in the form
15214: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15215: escaped strings of the action recorded in the activity.log file.
15216: 
15217: =back
15218: 
15219: =head2 User Roles
15220: 
15221: =over 4
15222: 
15223: =item *
15224: 
15225: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15226: returns codes for allowed actions.
15227: 
15228: The first argument is required, all others are optional.
15229: 
15230: $priv is the privilege being checked.
15231: $uri contains additional information about what is being checked for access (e.g.,
15232: URL, course ID etc.). 
15233: $symb is the unique resource instance identifier in a course; if needed,
15234: but not provided, it will be retrieved via a call to &symbread(). 
15235: $role is the role for which a priv is being checked (only used if priv is evb). 
15236: $clientip is the user's IP address (only used when checking for access to portfolio 
15237: files).
15238: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15239: prevents recursive calls to &allowed.
15240: 
15241:  F: full access
15242:  U,I,K: authentication modes (cxx only)
15243:  '': forbidden
15244:  1: user needs to choose course
15245:  2: browse allowed
15246:  A: passphrase authentication needed
15247:  B: access temporarily blocked because of a blocking event in a course.
15248:  D: access blocked because access is required via session initiated via deep-link 
15249: 
15250: =item *
15251: 
15252: constructaccess($url,$setpriv) : check for access to construction space URL
15253: 
15254: See if the owner domain and name in the URL match those in the
15255: expected environment.  If so, return three element list
15256: ($ownername,$ownerdomain,$ownerhome).
15257: 
15258: Otherwise return the null string.
15259: 
15260: If second argument 'setpriv' is true, it assigns the privileges,
15261: and returns the same three element list, unless the owner has
15262: blocked "ad hoc" Domain Coordinator access to the Author Space,
15263: in which case the null string is returned.
15264: 
15265: =item *
15266: 
15267: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15268: define a custom role rolename set privileges in format of lonTabs/roles.tab
15269: for system, domain, and course level. $uname and $udom are optional (current
15270: user's username and domain will be used when either of $uname or $udom are absent.
15271: 
15272: =item *
15273: 
15274: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15275: (rolesplain.tab); plain text explanation of a user role term.
15276: $type is Course (default) or Community.
15277: If $forcedefault evaluates to true, text returned will be default 
15278: text for $type. Otherwise, if this is a course, the text returned 
15279: will be a custom name for the role (if defined in the course's 
15280: environment).  If no custom name is defined the default is returned.
15281:    
15282: =item *
15283: 
15284: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15285: All arguments are optional. Returns a hash of a roles, either for
15286: co-author/assistant author roles for a user's Construction Space
15287: (default), or if $context is 'userroles', roles for the user himself,
15288: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15289: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15290: For each key, value is set to colon-separated start and end times for
15291: the role.  If no username and domain are specified, will default to
15292: current user/domain. Types, roles, and roledoms are references to arrays
15293: of role statuses (active, future or previous), roles 
15294: (e.g., cc,in, st etc.) and domains of the roles which can be used
15295: to restrict the list of roles reported. If no array ref is 
15296: provided for types, will default to return only active roles.
15297: 
15298: =item *
15299: 
15300: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15301: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15302: 
15303: Additional optional arguments are: $type (if role checking is to be restricted 
15304: to certain user status types -- previous (expired roles), active (currently
15305: available roles) or future (roles available in the future), and
15306: $hideprivileged -- if true will not report course roles for users who
15307: have active Domain Coordinator role in course's domain or in additional
15308: domains (specified in 'Domains to check for privileged users' in course
15309: environment -- set via:  Course Settings -> Classlists and staff listing).
15310: 
15311: =item *
15312: 
15313: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15314: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15315: $possdomains and $possroles are optional array refs -- to domains to check and
15316: roles to check.  If $possdomains is not specified, a dump will be done of the
15317: users' roles.db to check for a dc or su role in any domain. This can be
15318: time consuming if &privileged is called repeatedly (e.g., when displaying a
15319: classlist), so in such cases, supplying a $possdomains array is preferred, as
15320: this then allows &privileged_by_domain() to be used, which caches the identity
15321: of privileged users, eliminating the need for repeated calls to &dump().
15322: 
15323: =item *
15324: 
15325: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15326: where the outer hash keys are domains specified in the $possdomains array ref,
15327: next inner hash keys are privileged roles specified in the $roles array ref,
15328: and the innermost hash contains key = value pairs for username:domain = end:start
15329: for active or future "privileged" users with that role in that domain. To avoid
15330: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15331: innerhash are cached using priv_$role and $dom as the identifiers.
15332: 
15333: =back
15334: 
15335: =head2 User Modification
15336: 
15337: =over 4
15338: 
15339: =item *
15340: 
15341: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15342: user for the level given by URL.  Optional start and end dates (leave empty
15343: string or zero for "no date")
15344: 
15345: =item *
15346: 
15347: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15348: change a users, password, possible return values are: ok,
15349: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15350: refused
15351: 
15352: =item *
15353: 
15354: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15355: 
15356: =item *
15357: 
15358: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15359:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15360: 
15361: will update user information (firstname,middlename,lastname,generation,
15362: permanentemail), and if forceid is true, student/employee ID also.
15363: A user's institutional affiliation(s) can also be updated.
15364: User information fields will not be overwritten with empty entries 
15365: unless the field is included in the $candelete array reference.
15366: This array is included when a single user is modified via "Manage Users",
15367: or when Autoupdate.pl is run by cron in a domain.
15368: 
15369: =item *
15370: 
15371: modifystudent
15372: 
15373: modify a student's enrollment and identification information.
15374: The course id is resolved based on the current user's environment.  
15375: This means the invoking user must be a course coordinator or otherwise
15376: associated with a course.
15377: 
15378: This call is essentially a wrapper for lonnet::modifyuser and
15379: lonnet::modify_student_enrollment
15380: 
15381: Inputs: 
15382: 
15383: =over 4
15384: 
15385: =item B<$udom> Student's loncapa domain
15386: 
15387: =item B<$uname> Student's loncapa login name
15388: 
15389: =item B<$uid> Student/Employee ID
15390: 
15391: =item B<$umode> Student's authentication mode
15392: 
15393: =item B<$upass> Student's password
15394: 
15395: =item B<$first> Student's first name
15396: 
15397: =item B<$middle> Student's middle name
15398: 
15399: =item B<$last> Student's last name
15400: 
15401: =item B<$gene> Student's generation
15402: 
15403: =item B<$usec> Student's section in course
15404: 
15405: =item B<$end> Unix time of the roles expiration
15406: 
15407: =item B<$start> Unix time of the roles start date
15408: 
15409: =item B<$forceid> If defined, allow $uid to be changed
15410: 
15411: =item B<$desiredhome> server to use as home server for student
15412: 
15413: =item B<$email> Student's permanent e-mail address
15414: 
15415: =item B<$type> Type of enrollment (auto or manual)
15416: 
15417: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15418: 
15419: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15420: 
15421: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15422: 
15423: =item B<$context> role change context (shown in User Management Logs display in a course)
15424: 
15425: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15426: 
15427: =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.
15428: 
15429: =back
15430: 
15431: =item *
15432: 
15433: modify_student_enrollment
15434: 
15435: Change a student's enrollment status in a class.  The environment variable
15436: 'role.request.course' must be defined for this function to proceed.
15437: 
15438: Inputs:
15439: 
15440: =over 4
15441: 
15442: =item $udom, student's domain
15443: 
15444: =item $uname, student's name
15445: 
15446: =item $uid, student's user id
15447: 
15448: =item $first, student's first name
15449: 
15450: =item $middle
15451: 
15452: =item $last
15453: 
15454: =item $gene
15455: 
15456: =item $usec
15457: 
15458: =item $end
15459: 
15460: =item $start
15461: 
15462: =item $type
15463: 
15464: =item $locktype
15465: 
15466: =item $cid
15467: 
15468: =item $selfenroll
15469: 
15470: =item $context
15471: 
15472: =item $credits, number of credits student will earn from this class
15473: 
15474: =item $instsec, institutional course section code for student
15475: 
15476: =back
15477: 
15478: 
15479: =item *
15480: 
15481: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15482: custom role; give a custom role to a user for the level given by URL.  Specify
15483: name and domain of role author, and role name
15484: 
15485: =item *
15486: 
15487: revokerole($udom,$uname,$url,$role) : revoke a role for url
15488: 
15489: =item *
15490: 
15491: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15492: 
15493: =back
15494: 
15495: =head2 Course Infomation
15496: 
15497: =over 4
15498: 
15499: =item *
15500: 
15501: coursedescription($courseid,$options) : returns a hash of information about the
15502: specified course id, including all environment settings for the
15503: course, the description of the course will be in the hash under the
15504: key 'description'
15505: 
15506: $options is an optional parameter that if supplied is a hash reference that controls
15507: what how this function works.  It has the following key/values:
15508: 
15509: =over 4
15510: 
15511: =item freshen_cache
15512: 
15513: If defined, and the environment cache for the course is valid, it is 
15514: returned in the returned hash.
15515: 
15516: =item one_time
15517: 
15518: If defined, the last cache time is set to _now_
15519: 
15520: =item user
15521: 
15522: If defined, the supplied username is used instead of the current user.
15523: 
15524: 
15525: =back
15526: 
15527: =item *
15528: 
15529: resdata($name,$domain,$type,@which) : request for current parameter
15530: setting for a specific $type, where $type is either 'course' or 'user',
15531: @what should be a list of parameters to ask about. This routine caches
15532: answers for 10 minutes.
15533: 
15534: =item *
15535: 
15536: get_courseresdata($courseid, $domain) : dump the entire course resource
15537: data base, returning a hash that is keyed by the resource name and has
15538: values that are the resource value.  I believe that the timestamps and
15539: versions are also returned.
15540: 
15541: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15542: supplemental content area. This routine caches the number of files for 
15543: 10 minutes.
15544: 
15545: =back
15546: 
15547: =head2 Course Modification
15548: 
15549: =over 4
15550: 
15551: =item *
15552: 
15553: writecoursepref($courseid,%prefs) : write preferences (environment
15554: database) for a course
15555: 
15556: =item *
15557: 
15558: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15559: 
15560: =item *
15561: 
15562: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15563: 
15564: =item *
15565: 
15566: is_course($courseid), is_course($cdom, $cnum)
15567: 
15568: Accepts either a combined $courseid (in the form of domain_courseid) or the
15569: two component version $cdom, $cnum. It checks if the specified course exists.
15570: 
15571: Returns:
15572:     undef if the course doesn't exist, otherwise
15573:     in scalar context the combined courseid.
15574:     in list context the two components of the course identifier, domain and 
15575:     courseid.    
15576: 
15577: =back
15578: 
15579: =head2 Bubblesheet Configuration
15580: 
15581: =over 4
15582: 
15583: =item *
15584: 
15585: get_scantron_config($which)
15586: 
15587: $which - the name of the configuration to parse from the file.
15588: 
15589: Parses and returns the bubblesheet configuration line selected as a
15590: hash of configuration file fields.
15591: 
15592: 
15593: Returns:
15594:     If the named configuration is not in the file, an empty
15595:     hash is returned.
15596: 
15597:     a hash with the fields
15598:       name         - internal name for the this configuration setup
15599:       description  - text to display to operator that describes this config
15600:       CODElocation - if 0 or the string 'none'
15601:                           - no CODE exists for this config
15602:                      if -1 || the string 'letter'
15603:                           - a CODE exists for this config and is
15604:                             a string of letters
15605:                      Unsupported value (but planned for future support)
15606:                           if a positive integer
15607:                                - The CODE exists as the first n items from
15608:                                  the question section of the form
15609:                           if the string 'number'
15610:                                - The CODE exists for this config and is
15611:                                  a string of numbers
15612:       CODEstart   - (only matter if a CODE exists) column in the line where
15613:                      the CODE starts
15614:       CODElength  - length of the CODE
15615:       IDstart     - column where the student/employee ID starts
15616:       IDlength    - length of the student/employee ID info
15617:       Qstart      - column where the information from the bubbled
15618:                     'questions' start
15619:       Qlength     - number of columns comprising a single bubble line from
15620:                     the sheet. (usually either 1 or 10)
15621:       Qon         - either a single character representing the character used
15622:                     to signal a bubble was chosen in the positional setup, or
15623:                     the string 'letter' if the letter of the chosen bubble is
15624:                     in the final, or 'number' if a number representing the
15625:                     chosen bubble is in the file (1->A 0->J)
15626:       Qoff        - the character used to represent that a bubble was
15627:                     left blank
15628:       PaperID     - if the scanning process generates a unique number for each
15629:                     sheet scanned the column that this ID number starts in
15630:       PaperIDlength - number of columns that comprise the unique ID number
15631:                       for the sheet of paper
15632:       FirstName   - column that the first name starts in
15633:       FirstNameLength - number of columns that the first name spans
15634:       LastName    - column that the last name starts in
15635:       LastNameLength - number of columns that the last name spans
15636:       BubblesPerRow - number of bubbles available in each row used to
15637:                       bubble an answer. (If not specified, 10 assumed).
15638: 
15639: 
15640: =item *
15641: 
15642: get_scantronformat_file($cdom)
15643: 
15644: $cdom - the course's domain (optional); if not supplied, uses
15645: domain for current $env{'request.course.id'}.
15646: 
15647: Returns an array containing lines from the scantron format file for
15648: the domain of the course.
15649: 
15650: If a url for a custom.tab file is listed in domain's configuration.db,
15651: lines are from this file.
15652: 
15653: Otherwise, if a default.tab has been published in RES space by the
15654: domainconfig user, lines are from this file.
15655: 
15656: Otherwise, fall back to getting lines from the legacy file on the
15657: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15658: 
15659: =back
15660: 
15661: =head2 Resource Subroutines
15662: 
15663: =over 4
15664: 
15665: =item *
15666: 
15667: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15668: 
15669: =item *
15670: 
15671: repcopy($filename) : subscribes to the requested file, and attempts to
15672: replicate from the owning library server, Might return
15673: 'unavailable', 'not_found', 'forbidden', 'ok', or
15674: 'bad_request', also attempts to grab the metadata for the
15675: resource. Expects the local filesystem pathname
15676: (/home/httpd/html/res/....)
15677: 
15678: =back
15679: 
15680: =head2 Resource Information
15681: 
15682: =over 4
15683: 
15684: =item *
15685: 
15686: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15687: and returns the value of a variety of different possible values,
15688: $varname should be a request string, and the other parameters can be
15689: used to specify who and what one is asking about. Ordinarily, $cid 
15690: does not need to be specified, as it is retrived from 
15691: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15692: within lonuserstate::loadmap() when initializing a course, before
15693: $env{'request.course.id'} has been set, so it needs to be provided
15694: in that one case.
15695: 
15696: Possible values for $varname are environment.lastname (or other item
15697: from the envirnment hash), user.name (or someother aspect about the
15698: user), resource.0.maxtries (or some other part and parameter of a
15699: resource)
15700: 
15701: =item *
15702: 
15703: directcondval($number) : get current value of a condition; reads from a state
15704: string
15705: 
15706: =item *
15707: 
15708: condval($condidx) : value of condition index based on state
15709: 
15710: =item *
15711: 
15712: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15713: resource's metadata, $what should be either a specific key, or either
15714: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15715: packages that this resource currently uses, the last 3 arguments are 
15716: only used internally for recursive metadata.
15717: 
15718: the toolsymb is only used where the uri is for an external tool (for which
15719: the uri as well as the symb are guaranteed to be unique).
15720: 
15721: this function automatically caches all requests except any made recursively
15722: to retrieve a list of metadata keys for an imported library file ($liburi is 
15723: defined).
15724: 
15725: =item *
15726: 
15727: metadata_query($query,$custom,$customshow) : make a metadata query against the
15728: network of library servers; returns file handle of where SQL and regex results
15729: will be stored for query
15730: 
15731: =item *
15732: 
15733: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15734: return symbolic list entry (all arguments optional). 
15735: 
15736: Args: filename is the filename (including path) for the file for which a symb 
15737: is required; donotrecurse, if true will prevent calls to allowed() being made 
15738: to check access status if more than one resource was found in the bighash 
15739: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15740: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15741: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15742: cause possible symbs to be checked to determine if they are subject to content
15743: blocking, if so they will not be included as possible symbs; possibles is a
15744: ref to a hash, which, as a side effect, will be populated with all possible 
15745: symbs (content blocking not tested).
15746:  
15747: returns the data handle
15748: 
15749: =item *
15750: 
15751: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15752: and is a possible symb for the URL in $thisfn, and if is an encrypted
15753: resource that the user accessed using /enc/ returns a 1 on success, 0
15754: on failure, user must be in a course, as it assumes the existence of
15755: the course initial hash, and uses $env('request.course.id'}.  The third
15756: arg is an optional reference to a scalar.  If this arg is passed in the 
15757: call to symbverify, it will be set to 1 if the symb has been set to be 
15758: encrypted; otherwise it will be null.  
15759: 
15760: =item *
15761: 
15762: symbclean($symb) : removes versions numbers from a symb, returns the
15763: cleaned symb
15764: 
15765: =item *
15766: 
15767: is_on_map($uri) : checks if the $uri is somewhere on the current
15768: course map, user must be in a course for it to work.
15769: 
15770: =item *
15771: 
15772: numval($salt) : return random seed value (addend for rndseed)
15773: 
15774: =item *
15775: 
15776: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15777: a random seed, all arguments are optional, if they aren't sent it uses the
15778: environment to derive them. Note: if symb isn't sent and it can't get one
15779: from &symbread it will use the current time as its return value
15780: 
15781: =item *
15782: 
15783: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15784: unfakeable, receipt
15785: 
15786: =item *
15787: 
15788: receipt() : API to ireceipt working off of env values; given out to users
15789: 
15790: =item *
15791: 
15792: countacc($url) : count the number of accesses to a given URL
15793: 
15794: =item *
15795: 
15796: 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
15797: 
15798: =item *
15799: 
15800: 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)
15801: 
15802: =item *
15803: 
15804: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15805: 
15806: =item *
15807: 
15808: devalidate($symb) : devalidate temporary spreadsheet calculations,
15809: forcing spreadsheet to reevaluate the resource scores next time.
15810: 
15811: =item * 
15812: 
15813: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15814: when viewing in course context.
15815: 
15816:  input: six args -- filename (decluttered), course number, course domain,
15817:                     url, symb (if registered) and group (if this is a 
15818:                     group item -- e.g., bulletin board, group page etc.).
15819: 
15820:  output: array of five scalars --
15821:          $cfile -- url for file editing if editable on current server
15822:          $home -- homeserver of resource (i.e., for author if published,
15823:                                           or course if uploaded.).
15824:          $switchserver --  1 if server switch will be needed.
15825:          $forceedit -- 1 if icon/link should be to go to edit mode 
15826:          $forceview -- 1 if icon/link should be to go to view mode
15827: 
15828: =item *
15829: 
15830: is_course_upload($file,$cnum,$cdom)
15831: 
15832: Used in course context to determine if current file was uploaded to 
15833: the course (i.e., would be found in /userfiles/docs on the course's 
15834: homeserver.
15835: 
15836:   input: 3 args -- filename (decluttered), course number and course domain.
15837:   output: boolean -- 1 if file was uploaded.
15838: 
15839: =back
15840: 
15841: =head2 Storing/Retreiving Data
15842: 
15843: =over 4
15844: 
15845: =item *
15846: 
15847: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15848: permanently for this url; hashref needs to be given and should be a \%hashname;
15849: the remaining args aren't required and if they aren't passed or are '' they will
15850: be derived from the env (with the exception of $laststore, which is an 
15851: optional arg used when a user's submission is stored in grading).
15852: $laststore is $version=$timestamp, where $version is the most recent version
15853: number retrieved for the corresponding $symb in the $namespace db file, and
15854: $timestamp is the timestamp for that transaction (UNIX time).
15855: $laststore is currently only passed when cstore() is called by 
15856: structuretags::finalize_storage().
15857: 
15858: =item *
15859: 
15860: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15861: but uses critical subroutine
15862: 
15863: =item *
15864: 
15865: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15866: all args are optional
15867: 
15868: =item *
15869: 
15870: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15871: dumps the complete (or key matching regexp) namespace into a hash
15872: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15873: normally &store()ed into
15874: 
15875: $range should be either an integer '100' (give me the first 100
15876:                                            matching records)
15877:               or be  two integers sperated by a - with no spaces
15878:                  '30-50' (give me the 30th through the 50th matching
15879:                           records)
15880: 
15881: 
15882: =item *
15883: 
15884: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15885: replaces a &store() version of data with a replacement set of data
15886: for a particular resource in a namespace passed in the $storehash hash 
15887: reference. If $tolog is true, the transaction is logged in the courselog
15888: with an action=PUTSTORE.
15889: 
15890: =item *
15891: 
15892: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15893: works very similar to store/cstore, but all data is stored in a
15894: temporary location and can be reset using tmpreset, $storehash should
15895: be a hash reference, returns nothing on success
15896: 
15897: =item *
15898: 
15899: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15900: similar to restore, but all data is stored in a temporary location and
15901: can be reset using tmpreset. Returns a hash of values on success,
15902: error string otherwise.
15903: 
15904: =item *
15905: 
15906: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15907: deltes all keys for $symb form the temporary storage hash.
15908: 
15909: =item *
15910: 
15911: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15912: reference filled in from namesp ($udom and $uname are optional)
15913: 
15914: =item *
15915: 
15916: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15917: namesp ($udom and $uname are optional)
15918: 
15919: =item *
15920: 
15921: dump($namespace,$udom,$uname,$regexp,$range) : 
15922: dumps the complete (or key matching regexp) namespace into a hash
15923: ($udom, $uname, $regexp, $range are optional)
15924: 
15925: $range should be either an integer '100' (give me the first 100
15926:                                            matching records)
15927:               or be  two integers sperated by a - with no spaces
15928:                  '30-50' (give me the 30th through the 50th matching
15929:                           records)
15930: =item *
15931: 
15932: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15933: $store can be a scalar, an array reference, or if the amount to be 
15934: incremented is > 1, a hash reference.
15935: 
15936: ($udom and $uname are optional)
15937: 
15938: =item *
15939: 
15940: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15941: ($udom and $uname are optional)
15942: 
15943: =item *
15944: 
15945: cput($namespace,$storehash,$udom,$uname) : critical put
15946: ($udom and $uname are optional)
15947: 
15948: =item *
15949: 
15950: newput($namespace,$storehash,$udom,$uname) :
15951: 
15952: Attempts to store the items in the $storehash, but only if they don't
15953: currently exist, if this succeeds you can be certain that you have 
15954: successfully created a new key value pair in the $namespace db.
15955: 
15956: 
15957: Args:
15958:  $namespace: name of database to store values to
15959:  $storehash: hashref to store to the db
15960:  $udom: (optional) domain of user containing the db
15961:  $uname: (optional) name of user caontaining the db
15962: 
15963: Returns:
15964:  'ok' -> succeeded in storing all keys of $storehash
15965:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15966:                         least <key> already existed in the db (other
15967:                         requested keys may also already exist)
15968:  'error: <msg>' -> unable to tie the DB or other error occurred
15969:  'con_lost' -> unable to contact request server
15970:  'refused' -> action was not allowed by remote machine
15971: 
15972: 
15973: =item *
15974: 
15975: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15976: reference filled in from namesp (encrypts the return communication)
15977: ($udom and $uname are optional)
15978: 
15979: =item *
15980: 
15981: log($udom,$name,$home,$message) : write to permanent log for user; use
15982: critical subroutine
15983: 
15984: =item *
15985: 
15986: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15987: array reference filled in from namespace found in domain level on either
15988: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15989: 
15990: =item *
15991: 
15992: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15993: domain level either on specified domain server ($uhome) or primary domain 
15994: server ($udom and $uhome are optional)
15995: 
15996: =item * 
15997: 
15998: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15999: for: authentication, language, quotas, timezone, date locale, and portal URL in
16000: the target domain.
16001: 
16002: May also include additional key => value pairs for the following groups:
16003: 
16004: =over
16005: 
16006: =item
16007: disk quotas (MB allocated by default to portfolios and authoring spaces).
16008: 
16009: =over
16010: 
16011: =item defaultquota, authorquota
16012: 
16013: =back
16014: 
16015: =item
16016: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16017: portfolio for users).
16018: 
16019: =over
16020: 
16021: =item
16022: aboutme, blog, webdav, portfolio
16023: 
16024: =back
16025: 
16026: =item
16027: requestcourses: ability to request courses, and how requests are processed.
16028: 
16029: =over
16030: 
16031: =item
16032: official, unofficial, community, textbook, placement
16033: 
16034: =back
16035: 
16036: =item
16037: inststatus: types of institutional affiliation, and order in which they are displayed.
16038: 
16039: =over
16040: 
16041: =item
16042: inststatustypes, inststatusorder, inststatusguest
16043: 
16044: =back
16045: 
16046: =item
16047: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16048: for course's uploaded content.
16049: 
16050: =over
16051: 
16052: =item
16053: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16054: communityquota, textbookquota, placementquota
16055: 
16056: =back
16057: 
16058: =item
16059: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16060: on your servers.
16061: 
16062: =over
16063: 
16064: =item 
16065: remotesessions, hostedsessions
16066: 
16067: =back
16068: 
16069: =back
16070: 
16071: In cases where a domain coordinator has never used the "Set Domain Configuration"
16072: utility to create a configuration.db file on a domain's primary library server 
16073: only the following domain defaults: auth_def, auth_arg_def, lang_def
16074: -- corresponding values are authentication type (internal, krb4, krb5,
16075: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16076: will be available. Values are retrieved from cache (if current), unless the
16077: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16078: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16079: 
16080: Typical usage:
16081: 
16082: %domdefaults = &get_domain_defaults($target_domain);
16083: 
16084: =back
16085: 
16086: =head2 Network Status Functions
16087: 
16088: =over 4
16089: 
16090: =item *
16091: 
16092: dirlist() : return directory list based on URI (first arg).
16093: 
16094: Inputs: 1 required, 5 optional.
16095: 
16096: =over
16097: 
16098: =item 
16099: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16100: 
16101: =item
16102: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16103: 
16104: =item
16105: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16106: 
16107: =item
16108: $getpropath - boolean: 1 if prepend path using &propath(). 
16109: 
16110: =item
16111: $getuserdir - boolean: 1 if prepend path for "userfiles".
16112: 
16113: =item 
16114: $alternateRoot - path to prepend in place of path from $uri.
16115: 
16116: =back
16117: 
16118: Returns: Array of up to two items.
16119: 
16120: =over
16121: 
16122: a reference to an array of files/subdirectories
16123: 
16124: =over
16125: 
16126: Each element in the array of files/subdirectories is a & separated list of
16127: item name and the result of running stat on the item.  If dirlist was requested
16128: for a file instead of a directory, the item name will be ''. For a directory 
16129: listing, if the item is a metadata file, the element will end &N&M 
16130: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16131: default copyright set (1).  
16132: 
16133: =back
16134: 
16135: a scalar containing error condition (if encountered).
16136: 
16137: =over
16138: 
16139: =item 
16140: no_host (no homeserver identified for $username:$domain).
16141: 
16142: =item 
16143: no_such_host (server contacted for listing not identified as valid host).
16144: 
16145: =item 
16146: con_lost (connection to remote server failed).
16147: 
16148: =item 
16149: refused (invalid $username:$domain received on lond side).
16150: 
16151: =item 
16152: no_such_dir (directory at specified path on lond side does not exist). 
16153: 
16154: =item 
16155: empty (directory at specified path on lond side is empty).
16156: 
16157: =over
16158: 
16159: This is currently not encountered because the &ls3, &ls2, 
16160: &ls (_handler) routines on the lond side do not filter out
16161: . and .. from a directory listing. 
16162: 
16163: =back
16164: 
16165: =back
16166: 
16167: =back
16168: 
16169: =item *
16170: 
16171: spareserver() : find server with least workload from spare.tab
16172: 
16173: 
16174: =item *
16175: 
16176: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16177: if there is no corresponding loncapa host.
16178: 
16179: =back
16180: 
16181: 
16182: =head2 Apache Request
16183: 
16184: =over 4
16185: 
16186: =item *
16187: 
16188: ssi($url,%hash) : server side include, does a complete request cycle on url to
16189: localhost, posts hash
16190: 
16191: =back
16192: 
16193: =head2 Data to String to Data
16194: 
16195: =over 4
16196: 
16197: =item *
16198: 
16199: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16200: and '&' separators, supports elements that are arrayrefs and hashrefs
16201: 
16202: =item *
16203: 
16204: hashref2str($hashref) : convert a hashref into a string complete with
16205: escaping and '=' and '&' separators, supports elements that are
16206: arrayrefs and hashrefs
16207: 
16208: =item *
16209: 
16210: arrayref2str($arrayref) : convert an arrayref into a string complete
16211: with escaping and '&' separators, supports elements that are arrayrefs
16212: and hashrefs
16213: 
16214: =item *
16215: 
16216: str2hash($string) : convert string to hash using unescaping and
16217: splitting on '=' and '&', supports elements that are arrayrefs and
16218: hashrefs
16219: 
16220: =item *
16221: 
16222: str2array($string) : convert string to hash using unescaping and
16223: splitting on '&', supports elements that are arrayrefs and hashrefs
16224: 
16225: =back
16226: 
16227: =head2 Logging Routines
16228: 
16229: 
16230: These routines allow one to make log messages in the lonnet.log and
16231: lonnet.perm logfiles.
16232: 
16233: =over 4
16234: 
16235: =item *
16236: 
16237: logtouch() : make sure the logfile, lonnet.log, exists
16238: 
16239: =item *
16240: 
16241: logthis() : append message to the normal lonnet.log file, it gets
16242: preiodically rolled over and deleted.
16243: 
16244: =item *
16245: 
16246: logperm() : append a permanent message to lonnet.perm.log, this log
16247: file never gets deleted by any automated portion of the system, only
16248: messages of critical importance should go in here.
16249: 
16250: 
16251: =back
16252: 
16253: =head2 General File Helper Routines
16254: 
16255: =over 4
16256: 
16257: =item *
16258: 
16259: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16260: (a) files in /uploaded
16261:   (i) If a local copy of the file exists - 
16262:       compares modification date of local copy with last-modified date for 
16263:       definitive version stored on home server for course. If local copy is 
16264:       stale, requests a new version from the home server and stores it. 
16265:       If the original has been removed from the home server, then local copy 
16266:       is unlinked.
16267:   (ii) If local copy does not exist -
16268:       requests the file from the home server and stores it. 
16269:   
16270:   If $caller is 'uploadrep':  
16271:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16272:     for request for files originally uploaded via DOCS. 
16273:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16274:   
16275:   Otherwise:
16276:      This indicates a call from the content generation phase of the request.
16277:      -  returns the entire contents of the file or -1.
16278:      
16279: (b) files in /res
16280:    - returns the entire contents of a file or -1; 
16281:    it properly subscribes to and replicates the file if neccessary.
16282: 
16283: 
16284: =item *
16285: 
16286: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16287:                   reference
16288: 
16289: returns either a stat() list of data about the file or an empty list
16290: if the file doesn't exist or couldn't find out about it (connection
16291: problems or user unknown)
16292: 
16293: =item *
16294: 
16295: filelocation($dir,$file) : returns file system location of a file
16296: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16297: directory that relative $file lookups are to looked in ($dir of /a/dir
16298: and a file of ../bob will become /a/bob)
16299: 
16300: =item *
16301: 
16302: hreflocation($dir,$file) : returns file system location or a URL; same as
16303: filelocation except for hrefs
16304: 
16305: =item *
16306: 
16307: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16308: also removes beginning /home/httpd/html unless /priv/ follows it.
16309: 
16310: =back
16311: 
16312: =head2 Usererfile file routines (/uploaded*)
16313: 
16314: =over 4
16315: 
16316: =item *
16317: 
16318: userfileupload(): main rotine for putting a file in a user or course's
16319:                   filespace, arguments are,
16320: 
16321:  formname - required - this is the name of the element in $env where the
16322:            filename, and the contents of the file to create/modifed exist
16323:            the filename is in $env{'form.'.$formname.'.filename'} and the
16324:            contents of the file is located in $env{'form.'.$formname}
16325:  context - if coursedoc, store the file in the course of the active role
16326:              of the current user; 
16327:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16328:            if 'canceloverwrite': delete file in tmp/overwrites directory
16329:  subdir - required - subdirectory to put the file in under ../userfiles/
16330:          if undefined, it will be placed in "unknown"
16331: 
16332:  (This routine calls clean_filename() to remove any dangerous
16333:  characters from the filename, and then calls finuserfileupload() to
16334:  complete the transaction)
16335: 
16336:  returns either the url of the uploaded file (/uploaded/....) if successful
16337:  and /adm/notfound.html if unsuccessful
16338: 
16339: =item *
16340: 
16341: clean_filename(): routine for cleaing a filename up for storage in
16342:                  userfile space, argument is:
16343: 
16344:  filename - proposed filename
16345: 
16346: returns: the new clean filename
16347: 
16348: =item *
16349: 
16350: finishuserfileupload(): routine that creates and sends the file to
16351: userspace, probably shouldn't be called directly
16352: 
16353:   docuname: username or courseid of destination for the file
16354:   docudom: domain of user/course of destination for the file
16355:   formname: same as for userfileupload()
16356:   fname: filename (including subdirectories) for the file
16357:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16358:           if hashref, and context is scantron, will convert csv format to standard format
16359:   allfiles: reference to hash used to store objects found by parser
16360:   codebase: reference to hash used for codebases of java objects found by parser
16361:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16362:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16363:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16364:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16365:   context: if 'overwrite', will move the uploaded file from its temporary location to
16366:             userfiles to facilitate overwriting a previously uploaded file with same name.
16367:   mimetype: reference to scalar to accommodate mime type determined
16368:             from File::MMagic if $parser = parse.
16369: 
16370:  returns either the url of the uploaded file (/uploaded/....) if successful
16371:  and /adm/notfound.html if unsuccessful (or an error message if context 
16372:  was 'overwrite').
16373:  
16374: 
16375: =item *
16376: 
16377: renameuserfile(): renames an existing userfile to a new name
16378: 
16379:   Args:
16380:    docuname: username or courseid of destination for the file
16381:    docudom: domain of user/course of destination for the file
16382:    old: current file name (including any subdirs under userfiles)
16383:    new: desired file name (including any subdirs under userfiles)
16384: 
16385: =item *
16386: 
16387: mkdiruserfile(): creates a directory is a userfiles dir
16388: 
16389:   Args:
16390:    docuname: username or courseid of destination for the file
16391:    docudom: domain of user/course of destination for the file
16392:    dir: dir to create (including any subdirs under userfiles)
16393: 
16394: =item *
16395: 
16396: removeuserfile(): removes a file that exists in userfiles
16397: 
16398:   Args:
16399:    docuname: username or courseid of destination for the file
16400:    docudom: domain of user/course of destination for the file
16401:    fname: filname to delete (including any subdirs under userfiles)
16402: 
16403: =item *
16404: 
16405: removeuploadedurl(): convience function for removeuserfile()
16406: 
16407:   Args:
16408:    url:  a full /uploaded/... url to delete
16409: 
16410: =item * 
16411: 
16412: get_portfile_permissions():
16413:   Args:
16414:     domain: domain of user or course contain the portfolio files
16415:     user: name of user or num of course contain the portfolio files
16416:   Returns:
16417:     hashref of a dump of the proper file_permissions.db
16418:    
16419: 
16420: =item * 
16421: 
16422: get_access_controls():
16423: 
16424: Args:
16425:   current_permissions: the hash ref returned from get_portfile_permissions()
16426:   group: (optional) the group you want the files associated with
16427:   file: (optional) the file you want access info on
16428: 
16429: Returns:
16430:     a hash (keys are file names) of hashes containing
16431:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16432:         values are XML containing access control settings (see below) 
16433: 
16434: Internal notes:
16435: 
16436:  access controls are stored in file_permissions.db as key=value pairs.
16437:     key -> path to file/file_name\0uniqueID:scope_end_start
16438:         where scope -> public,guest,course,group,domains or users.
16439:               end -> UNIX time for end of access (0 -> no end date)
16440:               start -> UNIX time for start of access
16441: 
16442:     value -> XML description of access control
16443:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16444:             <start></start>
16445:             <end></end>
16446: 
16447:             <password></password>  for scope type = guest
16448: 
16449:             <domain></domain>     for scope type = course or group
16450:             <number></number>
16451:             <roles id="">
16452:              <role></role>
16453:              <access></access>
16454:              <section></section>
16455:              <group></group>
16456:             </roles>
16457: 
16458:             <dom></dom>         for scope type = domains
16459: 
16460:             <users>             for scope type = users
16461:              <user>
16462:               <uname></uname>
16463:               <udom></udom>
16464:              </user>
16465:             </users>
16466:            </scope> 
16467:               
16468:  Access data is also aggregated for each file in an additional key=value pair:
16469:  key -> path to file/file_name\0accesscontrol 
16470:  value -> reference to hash
16471:           hash contains key = value pairs
16472:           where key = uniqueID:scope_end_start
16473:                 value = UNIX time record was last updated
16474: 
16475:           Used to improve speed of look-ups of access controls for each file.  
16476:  
16477:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16478: 
16479: =item *
16480: 
16481: modify_access_controls():
16482: 
16483: Modifies access controls for a portfolio file
16484: Args
16485: 1. file name
16486: 2. reference to hash of required changes,
16487: 3. domain
16488: 4. username
16489:   where domain,username are the domain of the portfolio owner 
16490:   (either a user or a course) 
16491: 
16492: Returns:
16493: 1. result of additions or updates ('ok' or 'error', with error message). 
16494: 2. result of deletions ('ok' or 'error', with error message).
16495: 3. reference to hash of any new or updated access controls.
16496: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16497:    key = integer (inbound ID)
16498:    value = uniqueID
16499: 
16500: =item *
16501: 
16502: get_timebased_id():
16503: 
16504: Attempts to get a unique timestamp-based suffix for use with items added to a 
16505: course via the Course Editor (e.g., folders, composite pages, 
16506: group bulletin boards).
16507: 
16508: Args: (first three required; six others optional)
16509: 
16510: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16511:    docssequence, or name of group
16512: 
16513: 2. keyid (alphanumeric): name of temporary locking key in hash,
16514:    e.g., num, boardids
16515: 
16516: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16517:    file will be named nohist_namespace.db
16518: 
16519: 4. cdom: domain of course; default is current course domain from %env
16520: 
16521: 5. cnum: course number; default is current course number from %env
16522: 
16523: 6. idtype: set to concat if an additional digit is to be appended to the 
16524:    unix timestamp to form the suffix, if the plain timestamp is already
16525:    in use.  Default is to not do this, but simply increment the unix 
16526:    timestamp by 1 until a unique key is obtained.
16527: 
16528: 7. who: holder of locking key; defaults to user:domain for user.
16529: 
16530: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16531:    retrying); default is 3.
16532: 
16533: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16534: 
16535: Returns:
16536: 
16537: 1. suffix obtained (numeric)
16538: 
16539: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16540: 
16541: 3. error: contains (localized) error message if an error occurred.
16542: 
16543: 
16544: =back
16545: 
16546: =head2 HTTP Helper Routines
16547: 
16548: =over 4
16549: 
16550: =item *
16551: 
16552: escape() : unpack non-word characters into CGI-compatible hex codes
16553: 
16554: =item *
16555: 
16556: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16557: 
16558: =back
16559: 
16560: =head1 PRIVATE SUBROUTINES
16561: 
16562: =head2 Underlying communication routines (Shouldn't call)
16563: 
16564: =over 4
16565: 
16566: =item *
16567: 
16568: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16569: 
16570: =item *
16571: 
16572: reply() : uses subreply to send a message to remote machine, logs all failures
16573: 
16574: =item *
16575: 
16576: critical() : passes a critical message to another server; if cannot
16577: get through then place message in connection buffer directory and
16578: returns con_delayed, if incapable of saving message, returns
16579: con_failed
16580: 
16581: =item *
16582: 
16583: reconlonc() : tries to reconnect lonc client processes.
16584: 
16585: =back
16586: 
16587: =head2 Resource Access Logging
16588: 
16589: =over 4
16590: 
16591: =item *
16592: 
16593: flushcourselogs() : flush (save) buffer logs and access logs
16594: 
16595: =item *
16596: 
16597: courselog($what) : save message for course in hash
16598: 
16599: =item *
16600: 
16601: courseacclog($what) : save message for course using &courselog().  Perform
16602: special processing for specific resource types (problems, exams, quizzes, etc).
16603: 
16604: =item *
16605: 
16606: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16607: as a PerlChildExitHandler
16608: 
16609: =back
16610: 
16611: =head2 Other
16612: 
16613: =over 4
16614: 
16615: =item *
16616: 
16617: symblist($mapname,%newhash) : update symbolic storage links
16618: 
16619: =back
16620: 
16621: =cut
16622: 

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