File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1483: download - view: text, annotated - select for diffs
Thu Feb 17 22:35:52 2022 UTC (2 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907
  - Link Protectors for deep-linking from launch from LTI Consumer can be
    configured at both a domain level and a course level.
  - Support encryption of link protection secrets set in a domain.
  - Requires perl-Crypt-CBC

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1483 2022/02/17 22:35:52 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use Net::CIDR;
  100: use Sys::Hostname::FQDN();
  101: use LONCAPA qw(:DEFAULT :match);
  102: use LONCAPA::Configuration;
  103: use LONCAPA::lonmetadata;
  104: use LONCAPA::Lond;
  105: use LONCAPA::LWPReq;
  106: use LONCAPA::transliterate;
  107: 
  108: use File::Copy;
  109: 
  110: my $readit;
  111: my $max_connection_retries = 20;     # Or some such value.
  112: 
  113: require Exporter;
  114: 
  115: our @ISA = qw (Exporter);
  116: our @EXPORT = qw(%env);
  117: 
  118: 
  119: # ------------------------------------ Logging (parameters, docs, slots, roles)
  120: {
  121:     my $logid;
  122:     sub write_log {
  123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  124:         if ($context eq 'course') {
  125:             if (($cnum eq '') || ($cdom eq '')) {
  126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  128:             }
  129:         }
  130: 	$logid ++;
  131:         my $now = time();
  132: 	my $id=$now.'00000'.$$.'00000'.$logid;
  133:         my $ip = &get_requestor_ip();
  134:         my $logentry = { 
  135:                           $id => {
  136:                                    'exe_uname' => $env{'user.name'},
  137:                                    'exe_udom'  => $env{'user.domain'},
  138:                                    'exe_time'  => $now,
  139:                                    'exe_ip'    => $ip,
  140:                                    'delflag'   => $delflag,
  141:                                    'logentry'  => $storehash,
  142:                                    'uname'     => $uname,
  143:                                    'udom'      => $udom,
  144:                                   }
  145:                        };
  146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  147:     }
  148: }
  149: 
  150: sub logtouch {
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     unless (-e "$execdir/logs/lonnet.log") {	
  153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  154: 	close $fh;
  155:     }
  156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  158: }
  159: 
  160: sub logthis {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  167: 	print $fh $logstring;
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub logperm {
  174:     my $message=shift;
  175:     my $execdir=$perlvar{'lonDaemons'};
  176:     my $now=time;
  177:     my $local=localtime($now);
  178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  179: 	print $fh "$now:$message:$local\n";
  180: 	close($fh);
  181:     }
  182:     return 1;
  183: }
  184: 
  185: sub create_connection {
  186:     my ($hostname,$lonid) = @_;
  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  188: 				     Type    => SOCK_STREAM,
  189: 				     Timeout => 10);
  190:     return 0 if (!$client);
  191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  192:     my $result = <$client>;
  193:     chomp($result);
  194:     return 1 if ($result eq 'done');
  195:     return 0;
  196: }
  197: 
  198: sub get_server_timezone {
  199:     my ($cnum,$cdom) = @_;
  200:     my $home=&homeserver($cnum,$cdom);
  201:     if ($home ne 'no_host') {
  202:         my $cachetime = 24*3600;
  203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  204:         if (defined($cached)) {
  205:             return $timezone;
  206:         } else {
  207:             my $timezone = &reply('servertimezone',$home);
  208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  209:         }
  210:     }
  211: }
  212: 
  213: sub get_server_distarch {
  214:     my ($lonhost,$ignore_cache) = @_;
  215:     if (defined($lonhost)) {
  216:         if (!defined(&hostname($lonhost))) {
  217:             return;
  218:         }
  219:         my $cachetime = 12*3600;
  220:         if (!$ignore_cache) {
  221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  222:             if (defined($cached)) {
  223:                 return $distarch;
  224:             }
  225:         }
  226:         my $rep = &reply('serverdistarch',$lonhost);
  227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  229:                 $rep eq '') {
  230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  231:         }
  232:     }
  233:     return;
  234: }
  235: 
  236: sub get_servercerts_info {
  237:     my ($lonhost,$hostname,$context) = @_;
  238:     return if ($lonhost eq '');
  239:     if ($hostname eq '') {
  240:         $hostname = &hostname($lonhost);
  241:     }
  242:     return if ($hostname eq '');
  243:     my ($rep,$uselocal);
  244:     if ($context eq 'install') {
  245:         $uselocal = 1;
  246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  247:         $uselocal = 1;
  248:     }
  249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  251:         if ($distro eq '') {
  252:             $uselocal = 0;
  253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  254:             if ($1 < 6) {
  255:                 $uselocal = 0;
  256:             }
  257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  258:             if ($1 < 12) {
  259:                 $uselocal = 0;
  260:             }
  261:         }
  262:     }
  263:     if ($uselocal) {
  264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  265:     } else {
  266:         $rep=&reply('servercerts',$lonhost);
  267:     }
  268:     my ($result,%returnhash);
  269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  270:         ($rep eq 'unknown_cmd')) {
  271:         $result = $rep;
  272:     } else {
  273:         $result = 'ok';
  274:         my @pairs=split(/\&/,$rep);
  275:         foreach my $item (@pairs) {
  276:             my ($key,$value)=split(/=/,$item,2);
  277:             my $what = &unescape($key);
  278:             $returnhash{$what}=&thaw_unescape($value);
  279:         }
  280:     }
  281:     return ($result,\%returnhash);
  282: }
  283: 
  284: sub get_server_loncaparev {
  285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  286:     if (defined($lonhost)) {
  287:         if (!defined(&hostname($lonhost))) {
  288:             undef($lonhost);
  289:         }
  290:     }
  291:     if (!defined($lonhost)) {
  292:         if (defined(&domain($dom,'primary'))) {
  293:             $lonhost=&domain($dom,'primary');
  294:             if ($lonhost eq 'no_host') {
  295:                 undef($lonhost);
  296:             }
  297:         }
  298:     }
  299:     if (defined($lonhost)) {
  300:         my $cachetime = 12*3600;
  301:         if (!$ignore_cache) {
  302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  303:             if (defined($cached)) {
  304:                 return $loncaparev;
  305:             }
  306:         }
  307:         my ($answer,$loncaparev);
  308:         my @ids=&current_machine_ids();
  309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  310:             $answer = $perlvar{'lonVersion'};
  311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  312:                 $loncaparev = $1;
  313:             }
  314:         } else {
  315:             $answer = &reply('serverloncaparev',$lonhost);
  316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  317:                 if ($caller eq 'loncron') {
  318:                     my $hostname = &hostname($lonhost);
  319:                     my $protocol = $protocol{$lonhost};
  320:                     $protocol = 'http' if ($protocol ne 'https');
  321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  322:                     my $request=new HTTP::Request('GET',$url);
  323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  324:                     unless ($response->is_error()) {
  325:                         my $content = $response->content;
  326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  327:                             $loncaparev = $1;
  328:                         }
  329:                     }
  330:                 } else {
  331:                     $loncaparev = $loncaparevs{$lonhost};
  332:                 }
  333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  334:                 $loncaparev = $1;
  335:             }
  336:         }
  337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  338:     }
  339: }
  340: 
  341: sub get_server_homeID {
  342:     my ($hostname,$ignore_cache,$caller) = @_;
  343:     unless ($ignore_cache) {
  344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  345:         if (defined($cached)) {
  346:             return $serverhomeID;
  347:         }
  348:     }
  349:     my $cachetime = 12*3600;
  350:     my $serverhomeID;
  351:     if ($caller eq 'loncron') { 
  352:         my @machine_ids = &machine_ids($hostname);
  353:         foreach my $id (@machine_ids) {
  354:             my $response = &reply('serverhomeID',$id);
  355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  356:                 $serverhomeID = $response;
  357:                 last;
  358:             }
  359:         }
  360:         if ($serverhomeID eq '') {
  361:             $serverhomeID = $machine_ids[-1];
  362:         }
  363:     } else {
  364:         $serverhomeID = $serverhomeIDs{$hostname};
  365:     }
  366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  367: }
  368: 
  369: sub get_remote_globals {
  370:     my ($lonhost,$whathash,$ignore_cache) = @_;
  371:     my ($result,%returnhash,%whatneeded);
  372:     if (ref($whathash) eq 'HASH') {
  373:         foreach my $what (sort(keys(%{$whathash}))) {
  374:             my $hashid = $lonhost.'-'.$what;
  375:             my ($response,$cached);
  376:             unless ($ignore_cache) {
  377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  378:             }
  379:             if (defined($cached)) {
  380:                 $returnhash{$what} = $response;
  381:             } else {
  382:                 $whatneeded{$what} = 1;
  383:             }
  384:         }
  385:         if (keys(%whatneeded) == 0) {
  386:             $result = 'ok';
  387:         } else {
  388:             my $requested = &freeze_escape(\%whatneeded);
  389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  391:                 ($rep eq 'unknown_cmd')) {
  392:                 $result = $rep;
  393:             } else {
  394:                 $result = 'ok';
  395:                 my @pairs=split(/\&/,$rep);
  396:                 foreach my $item (@pairs) {
  397:                     my ($key,$value)=split(/=/,$item,2);
  398:                     my $what = &unescape($key);
  399:                     my $hashid = $lonhost.'-'.$what;
  400:                     $returnhash{$what}=&thaw_unescape($value);
  401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  402:                 }
  403:             }
  404:         }
  405:     }
  406:     return ($result,\%returnhash);
  407: }
  408: 
  409: sub remote_devalidate_cache {
  410:     my ($lonhost,$cachekeys) = @_;
  411:     my $items;
  412:     return unless (ref($cachekeys) eq 'ARRAY');
  413:     my $cachestr = join('&',@{$cachekeys});
  414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  415:     return $response;
  416: }
  417: 
  418: # -------------------------------------------------- Non-critical communication
  419: sub subreply {
  420:     my ($cmd,$server)=@_;
  421:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  422:     #
  423:     #  With loncnew process trimming, there's a timing hole between lonc server
  424:     #  process exit and the master server picking up the listen on the AF_UNIX
  425:     #  socket.  In that time interval, a lock file will exist:
  426: 
  427:     my $lockfile=$peerfile.".lock";
  428:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  429: 	sleep(0.1);
  430:     }
  431:     # At this point, either a loncnew parent is listening or an old lonc
  432:     # or loncnew child is listening so we can connect or everything's dead.
  433:     #
  434:     #   We'll give the connection a few tries before abandoning it.  If
  435:     #   connection is not possible, we'll con_lost back to the client.
  436:     #   
  437:     my $client;
  438:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  439: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  440: 				      Type    => SOCK_STREAM,
  441: 				      Timeout => 10);
  442: 	if ($client) {
  443: 	    last;		# Connected!
  444: 	} else {
  445: 	    &create_connection(&hostname($server),$server);
  446: 	}
  447:         sleep(0.1);	# Try again later if failed connection.
  448:     }
  449:     my $answer;
  450:     if ($client) {
  451: 	print $client "sethost:$server:$cmd\n";
  452: 	$answer=<$client>;
  453: 	if (!$answer) { $answer="con_lost"; }
  454: 	chomp($answer);
  455:     } else {
  456: 	$answer = 'con_lost';	# Failed connection.
  457:     }
  458:     return $answer;
  459: }
  460: 
  461: sub reply {
  462:     my ($cmd,$server)=@_;
  463:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  464:     my $answer=subreply($cmd,$server);
  465:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  466:         my $logged = $cmd;
  467:         if ($cmd =~ /^encrypt:([^:]+):/) {
  468:             my $subcmd = $1;
  469:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  470:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  471:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  472:                 ($subcmd eq 'put')) {
  473:                 (undef,undef,my @rest) = split(/:/,$cmd);
  474:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  475:                     splice(@rest,2,1,'Hidden');
  476:                 } elsif ($subcmd eq 'passwd') {
  477:                     splice(@rest,2,2,('Hidden','Hidden'));
  478:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  479:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  480:                     splice(@rest,3,1,'Hidden');
  481:                 }
  482:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  483:             }
  484:         }
  485:         &logthis("<font color=\"blue\">WARNING:".
  486:                  " $logged to $server returned $answer</font>");
  487:     }
  488:     return $answer;
  489: }
  490: 
  491: # ----------------------------------------------------------- Send USR1 to lonc
  492: 
  493: sub reconlonc {
  494:     my ($lonid) = @_;
  495:     if ($lonid) {
  496:         my $hostname = &hostname($lonid);
  497: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  498: 	if ($hostname && -e $peerfile) {
  499: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  500: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  501: 					     Type    => SOCK_STREAM,
  502: 					     Timeout => 10);
  503: 	    if ($client) {
  504: 		print $client ("reset_retries\n");
  505: 		my $answer=<$client>;
  506: 		#reset just this one.
  507: 	    }
  508: 	}
  509: 	return;
  510:     }
  511: 
  512:     &logthis("Trying to reconnect lonc");
  513:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  514:     if (open(my $fh,"<",$loncfile)) {
  515: 	my $loncpid=<$fh>;
  516:         chomp($loncpid);
  517:         if (kill 0 => $loncpid) {
  518: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  519:             kill USR1 => $loncpid;
  520:             sleep 1;
  521:         } else {
  522: 	    &logthis(
  523:                "<font color=\"blue\">WARNING:".
  524:                " lonc at pid $loncpid not responding, giving up</font>");
  525:         }
  526:     } else {
  527: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  528:     }
  529: }
  530: 
  531: # ------------------------------------------------------ Critical communication
  532: 
  533: sub critical {
  534:     my ($cmd,$server)=@_;
  535:     unless (&hostname($server)) {
  536:         &logthis("<font color=\"blue\">WARNING:".
  537:                " Critical message to unknown server ($server)</font>");
  538:         return 'no_such_host';
  539:     }
  540:     my $answer=reply($cmd,$server);
  541:     if ($answer eq 'con_lost') {
  542: 	&reconlonc($server);
  543: 	my $answer=reply($cmd,$server);
  544:         if ($answer eq 'con_lost') {
  545:             my $now=time;
  546:             my $middlename=$cmd;
  547:             $middlename=substr($middlename,0,16);
  548:             $middlename=~s/\W//g;
  549:             my $dfilename=
  550:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  551:             $dumpcount++;
  552:             {
  553: 		my $dfh;
  554: 		if (open($dfh,">",$dfilename)) {
  555: 		    print $dfh "$cmd\n"; 
  556: 		    close($dfh);
  557: 		}
  558:             }
  559:             sleep 1;
  560:             my $wcmd='';
  561:             {
  562: 		my $dfh;
  563: 		if (open($dfh,"<",$dfilename)) {
  564: 		    $wcmd=<$dfh>; 
  565: 		    close($dfh);
  566: 		}
  567:             }
  568:             chomp($wcmd);
  569:             if ($wcmd eq $cmd) {
  570: 		&logthis("<font color=\"blue\">WARNING: ".
  571:                          "Connection buffer $dfilename: $cmd</font>");
  572:                 &logperm("D:$server:$cmd");
  573: 	        return 'con_delayed';
  574:             } else {
  575:                 &logthis("<font color=\"red\">CRITICAL:"
  576:                         ." Critical connection failed: $server $cmd</font>");
  577:                 &logperm("F:$server:$cmd");
  578:                 return 'con_failed';
  579:             }
  580:         }
  581:     }
  582:     return $answer;
  583: }
  584: 
  585: # ------------------------------------------- check if return value is an error
  586: 
  587: sub error {
  588:     my ($result) = @_;
  589:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  590: 	if ($2 == 2) { return undef; }
  591: 	return $1;
  592:     }
  593:     return undef;
  594: }
  595: 
  596: sub convert_and_load_session_env {
  597:     my ($lonidsdir,$handle)=@_;
  598:     my @profile;
  599:     {
  600: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  601: 	if (!$opened) {
  602: 	    return 0;
  603: 	}
  604: 	flock($idf,LOCK_SH);
  605: 	@profile=<$idf>;
  606: 	close($idf);
  607:     }
  608:     my %temp_env;
  609:     foreach my $line (@profile) {
  610: 	if ($line !~ m/=/) {
  611: 	    return 0;
  612: 	}
  613: 	chomp($line);
  614: 	my ($envname,$envvalue)=split(/=/,$line,2);
  615: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  616:     }
  617:     unlink("$lonidsdir/$handle.id");
  618:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  619: 	    0640)) {
  620: 	%disk_env = %temp_env;
  621: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  622: 	untie(%disk_env);
  623:     }
  624:     return 1;
  625: }
  626: 
  627: # ------------------------------------------- Transfer profile into environment
  628: my $env_loaded;
  629: sub transfer_profile_to_env {
  630:     my ($lonidsdir,$handle,$force_transfer) = @_;
  631:     if (!$force_transfer && $env_loaded) { return; } 
  632: 
  633:     if (!defined($lonidsdir)) {
  634: 	$lonidsdir = $perlvar{'lonIDsDir'};
  635:     }
  636:     if (!defined($handle)) {
  637:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  638:     }
  639: 
  640:     my $convert;
  641:     {
  642:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  643: 	if (!$opened) {
  644: 	    return;
  645: 	}
  646: 	flock($idf,LOCK_SH);
  647: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  648: 		&GDBM_READER(),0640)) {
  649: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  650: 	    untie(%disk_env);
  651: 	} else {
  652: 	    $convert = 1;
  653: 	}
  654:     }
  655:     if ($convert) {
  656: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  657: 	    &logthis("Failed to load session, or convert session.");
  658: 	}
  659:     }
  660: 
  661:     my %remove;
  662:     while ( my $envname = each(%env) ) {
  663:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  664:             if ($time < time-300) {
  665:                 $remove{$key}++;
  666:             }
  667:         }
  668:     }
  669: 
  670:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  671:     $env_loaded=1;
  672:     foreach my $expired_key (keys(%remove)) {
  673:         &delenv($expired_key);
  674:     }
  675: }
  676: 
  677: # ---------------------------------------------------- Check for valid session 
  678: sub check_for_valid_session {
  679:     my ($r,$name,$userhashref,$domref) = @_;
  680:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  681:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  682:     if ($name eq 'lonDAV') {
  683:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  684:     } else {
  685:         $lonidsdir=$r->dir_config('lonIDsDir');
  686:         if ($name eq '') {
  687:             $name = 'lonID';
  688:         }
  689:     }
  690:     if ($name eq 'lonID') {
  691:         $secure = 'lonSID';
  692:         $linkname = 'lonLinkID';
  693:         $pubname = 'lonPubID';
  694:         if (exists($cookies{$secure})) {
  695:             $lonid=$cookies{$secure};
  696:         } elsif (exists($cookies{$name})) {
  697:             $lonid=$cookies{$name};
  698:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  699:             $lonid=$cookies{$linkname};
  700:         } elsif (exists($cookies{$pubname})) {
  701:             $lonid=$cookies{$pubname};
  702:         }
  703:     } else {
  704:         $lonid=$cookies{$name};
  705:     }
  706:     return undef if (!$lonid);
  707: 
  708:     my $handle=&LONCAPA::clean_handle($lonid->value);
  709:     if (-l "$lonidsdir/$handle.id") {
  710:         my $link = readlink("$lonidsdir/$handle.id");
  711:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  712:             $handle = $1;
  713:         }
  714:     }
  715:     if (!-e "$lonidsdir/$handle.id") {
  716:         if ((ref($domref)) && ($name eq 'lonID') && 
  717:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  718:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  719:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  720:                 $$domref = $possudom;
  721:             }
  722:         }
  723:         return undef;
  724:     }
  725: 
  726:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  727:     return undef if (!$opened);
  728: 
  729:     flock($idf,LOCK_SH);
  730:     my %disk_env;
  731:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  732: 	    &GDBM_READER(),0640)) {
  733: 	return undef;	
  734:     }
  735: 
  736:     if (!defined($disk_env{'user.name'})
  737: 	|| !defined($disk_env{'user.domain'})) {
  738:         untie(%disk_env);
  739: 	return undef;
  740:     }
  741: 
  742:     if (ref($userhashref) eq 'HASH') {
  743:         $userhashref->{'name'} = $disk_env{'user.name'};
  744:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  745:         if ($disk_env{'request.role'}) {
  746:             $userhashref->{'role'} = $disk_env{'request.role'};
  747:         }
  748:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  749:         if ($userhashref->{'lti'}) {
  750:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  751:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  752:         }
  753:     }
  754:     untie(%disk_env);
  755: 
  756:     return $handle;
  757: }
  758: 
  759: sub timed_flock {
  760:     my ($file,$lock_type) = @_;
  761:     my $failed=0;
  762:     eval {
  763: 	local $SIG{__DIE__}='DEFAULT';
  764: 	local $SIG{ALRM}=sub {
  765: 	    $failed=1;
  766: 	    die("failed lock");
  767: 	};
  768: 	alarm(13);
  769: 	flock($file,$lock_type);
  770: 	alarm(0);
  771:     };
  772:     if ($failed) {
  773: 	return undef;
  774:     } else {
  775: 	return 1;
  776:     }
  777: }
  778: 
  779: sub get_sessionfile_vars {
  780:     my ($handle,$lonidsdir,$storearr) = @_;
  781:     my %returnhash;
  782:     unless (ref($storearr) eq 'ARRAY') {
  783:         return %returnhash;
  784:     }
  785:     if (-l "$lonidsdir/$handle.id") {
  786:         my $link = readlink("$lonidsdir/$handle.id");
  787:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  788:             $handle = $1;
  789:         }
  790:     }
  791:     if ((-e "$lonidsdir/$handle.id") &&
  792:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  793:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  794:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  795:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  796:                 flock($idf,LOCK_SH);
  797:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  798:                         &GDBM_READER(),0640)) {
  799:                     foreach my $item (@{$storearr}) {
  800:                         $returnhash{$item} = $disk_env{$item};
  801:                     }
  802:                     untie(%disk_env);
  803:                 }
  804:             }
  805:         }
  806:     }
  807:     return %returnhash;
  808: }
  809: 
  810: # ---------------------------------------------------------- Append Environment
  811: 
  812: sub appenv {
  813:     my ($newenv,$roles) = @_;
  814:     if (ref($newenv) eq 'HASH') {
  815:         foreach my $key (keys(%{$newenv})) {
  816:             my $refused = 0;
  817: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  818:                 $refused = 1;
  819:                 if (ref($roles) eq 'ARRAY') {
  820:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  821:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  822:                         $refused = 0;
  823:                     }
  824:                 }
  825:             }
  826:             if ($refused) {
  827:                 &logthis("<font color=\"blue\">WARNING: ".
  828:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  829:                          .'</font>');
  830: 	        delete($newenv->{$key});
  831:             } else {
  832:                 $env{$key}=$newenv->{$key};
  833:             }
  834:         }
  835:         my $lonids = $perlvar{'lonIDsDir'};
  836:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  837:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  838:             if ($opened
  839: 	        && &timed_flock($env_file,LOCK_EX)
  840: 	        &&
  841: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  842: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  843: 	        while (my ($key,$value) = each(%{$newenv})) {
  844: 	            $disk_env{$key} = $value;
  845: 	        }
  846: 	        untie(%disk_env);
  847:             }
  848:         }
  849:     }
  850:     return 'ok';
  851: }
  852: # ----------------------------------------------------- Delete from Environment
  853: 
  854: sub delenv {
  855:     my ($delthis,$regexp,$roles) = @_;
  856:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  857:         my $refused = 1;
  858:         if (ref($roles) eq 'ARRAY') {
  859:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  860:             if (grep(/^\Q$role\E$/,@{$roles})) {
  861:                 $refused = 0;
  862:             }
  863:         }
  864:         if ($refused) {
  865:             &logthis("<font color=\"blue\">WARNING: ".
  866:                      "Attempt to delete from environment ".$delthis);
  867:             return 'error';
  868:         }
  869:     }
  870:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  871:     if ($opened
  872: 	&& &timed_flock($env_file,LOCK_EX)
  873: 	&&
  874: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  875: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  876: 	foreach my $key (keys(%disk_env)) {
  877: 	    if ($regexp) {
  878:                 if ($key=~/^$delthis/) {
  879:                     delete($env{$key});
  880:                     delete($disk_env{$key});
  881:                 } 
  882:             } else {
  883:                 if ($key=~/^\Q$delthis\E/) {
  884: 		    delete($env{$key});
  885: 		    delete($disk_env{$key});
  886: 	        }
  887:             }
  888: 	}
  889: 	untie(%disk_env);
  890:     }
  891:     return 'ok';
  892: }
  893: 
  894: sub get_env_multiple {
  895:     my ($name) = @_;
  896:     my @values;
  897:     if (defined($env{$name})) {
  898:         # exists is it an array
  899:         if (ref($env{$name})) {
  900:             @values=@{ $env{$name} };
  901:         } else {
  902:             $values[0]=$env{$name};
  903:         }
  904:     }
  905:     return(@values);
  906: }
  907: 
  908: # ------------------------------------------------------------------- Locking
  909: 
  910: sub set_lock {
  911:     my ($text)=@_;
  912:     $locknum++;
  913:     my $id=$$.'-'.$locknum;
  914:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  915:              'session.lock.'.$id => $text});
  916:     return $id;
  917: }
  918: 
  919: sub get_locks {
  920:     my $num=0;
  921:     my %texts=();
  922:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  923:        if ($lock=~/\w/) {
  924:           $num++;
  925:           $texts{$lock}=$env{'session.lock.'.$lock};
  926:        }
  927:    }
  928:    return ($num,%texts);
  929: }
  930: 
  931: sub remove_lock {
  932:     my ($id)=@_;
  933:     my $newlocks='';
  934:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  935:        if (($lock=~/\w/) && ($lock ne $id)) {
  936:           $newlocks.=','.$lock;
  937:        }
  938:     }
  939:     &appenv({'session.locks' => $newlocks});
  940:     &delenv('session.lock.'.$id);
  941: }
  942: 
  943: sub remove_all_locks {
  944:     my $activelocks=$env{'session.locks'};
  945:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  946:        if ($lock=~/\w/) {
  947:           &remove_lock($lock);
  948:        }
  949:     }
  950: }
  951: 
  952: 
  953: # ------------------------------------------ Find out current server userload
  954: sub userload {
  955:     my $numusers=0;
  956:     {
  957: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  958: 	my $filename;
  959: 	my $curtime=time;
  960: 	while ($filename=readdir(LONIDS)) {
  961: 	    next if ($filename eq '.' || $filename eq '..');
  962: 	    next if ($filename =~ /publicuser_\d+\.id/);
  963:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  964: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  965: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  966: 	}
  967: 	closedir(LONIDS);
  968:     }
  969:     my $userloadpercent=0;
  970:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  971:     if ($maxuserload) {
  972: 	$userloadpercent=100*$numusers/$maxuserload;
  973:     }
  974:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  975:     return $userloadpercent;
  976: }
  977: 
  978: # ------------------------------ Find server with least workload from spare.tab
  979: 
  980: sub spareserver {
  981:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  982:     my $spare_server;
  983:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  984:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  985:                                                      :  $userloadpercent;
  986:     my ($uint_dom,$remotesessions);
  987:     if (($udom ne '') && (&domain($udom) ne '')) {
  988:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  989:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  990:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  991:         $remotesessions = $udomdefaults{'remotesessions'};
  992:     }
  993:     my $spareshash = &this_host_spares($udom);
  994:     if (ref($spareshash) eq 'HASH') {
  995:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  996:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  997:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  998:                                              $try_server));
  999: 	        ($spare_server, $lowest_load) =
 1000: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1001:             }
 1002:         }
 1003: 
 1004:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1005: 
 1006:         if (!$found_server) {
 1007:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1008: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1009:                     next unless (&spare_can_host($udom,$uint_dom,
 1010:                                                  $remotesessions,$try_server));
 1011: 	            ($spare_server, $lowest_load) =
 1012: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1013:                 }
 1014: 	    }
 1015:         }
 1016:     }
 1017: 
 1018:     if (!$want_server_name) {
 1019:         if (defined($spare_server)) {
 1020:             my $hostname = &hostname($spare_server);
 1021:             if (defined($hostname)) {
 1022:                 my $protocol = 'http';
 1023:                 if ($protocol{$spare_server} eq 'https') {
 1024:                     $protocol = $protocol{$spare_server};
 1025:                 }
 1026:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
 1027:                 $hostname = $alias if ($alias ne '');
 1028: 	        $spare_server = $protocol.'://'.$hostname;
 1029:             }
 1030:         }
 1031:     }
 1032:     return $spare_server;
 1033: }
 1034: 
 1035: sub compare_server_load {
 1036:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1037: 
 1038:     if ($required) {
 1039:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1040:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1041:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1042:         if (($major eq '' && $minor eq '') ||
 1043:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1044:             return ($spare_server,$lowest_load);
 1045:         }
 1046:     }
 1047: 
 1048:     my $loadans     = &reply('load',    $try_server);
 1049:     my $userloadans = &reply('userload',$try_server);
 1050: 
 1051:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1052: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1053:     }
 1054: 
 1055:     my $load;
 1056:     if ($loadans =~ /\d/) {
 1057: 	if ($userloadans =~ /\d/) {
 1058: 	    #both are numbers, pick the bigger one
 1059: 	    $load = ($loadans > $userloadans) ? $loadans 
 1060: 		                              : $userloadans;
 1061: 	} else {
 1062: 	    $load = $loadans;
 1063: 	}
 1064:     } else {
 1065: 	$load = $userloadans;
 1066:     }
 1067: 
 1068:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1069: 	$spare_server = $try_server;
 1070: 	$lowest_load  = $load;
 1071:     }
 1072:     return ($spare_server,$lowest_load);
 1073: }
 1074: 
 1075: # --------------------------- ask offload servers if user already has a session
 1076: sub find_existing_session {
 1077:     my ($udom,$uname) = @_;
 1078:     my $spareshash = &this_host_spares($udom);
 1079:     if (ref($spareshash) eq 'HASH') {
 1080:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1081:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1082:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1083:             }
 1084:         }
 1085:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1086:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1087:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1088:             }
 1089:         }
 1090:     }
 1091:     return;
 1092: }
 1093: 
 1094: sub delusersession {
 1095:     my ($lonid,$udom,$uname) = @_;
 1096:     my $uprimary_id = &domain($udom,'primary');
 1097:     my $uintdom = &internet_dom($uprimary_id);
 1098:     my $intdom = &internet_dom($lonid);
 1099:     my $serverhomedom = &host_domain($lonid);
 1100:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1101:         return &reply(join(':','delusersession',
 1102:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1103:     }
 1104:     return;
 1105: }
 1106: 
 1107: # check if user's browser sent load balancer cookie and server still has session
 1108: # and is not overloaded.
 1109: sub check_for_balancer_cookie {
 1110:     my ($r,$update_mtime) = @_;
 1111:     my ($otherserver,$cookie);
 1112:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1113:     if (exists($cookies{'balanceID'})) {
 1114:         my $balid = $cookies{'balanceID'};
 1115:         $cookie=&LONCAPA::clean_handle($balid->value);
 1116:         my $balancedir=$r->dir_config('lonBalanceDir');
 1117:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1118:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1119:                 my ($possudom,$possuname) = ($1,$2);
 1120:                 my $has_session = 0;
 1121:                 if ((&domain($possudom) ne '') &&
 1122:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1123:                     my $try_server;
 1124:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1125:                     if ($opened) {
 1126:                         flock($idf,LOCK_SH);
 1127:                         while (my $line = <$idf>) {
 1128:                             chomp($line);
 1129:                             if (&hostname($line) ne '') {
 1130:                                 $try_server = $line;
 1131:                                 last;
 1132:                             }
 1133:                         }
 1134:                         close($idf);
 1135:                         if (($try_server) &&
 1136:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1137:                             my $lowest_load = 30000;
 1138:                             ($otherserver,$lowest_load) =
 1139:                                 &compare_server_load($try_server,undef,$lowest_load);
 1140:                             if ($otherserver ne '' && $lowest_load < 100) {
 1141:                                 $has_session = 1;
 1142:                             } else {
 1143:                                 undef($otherserver);
 1144:                             }
 1145:                         }
 1146:                     }
 1147:                 }
 1148:                 if ($has_session) {
 1149:                     if ($update_mtime) {
 1150:                         my $atime = my $mtime = time;
 1151:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1152:                     }
 1153:                 } else {
 1154:                     unlink("$balancedir/$cookie.id");
 1155:                 }
 1156:             }
 1157:         }
 1158:     }
 1159:     return ($otherserver,$cookie);
 1160: }
 1161: 
 1162: sub updatebalcookie {
 1163:     my ($cookie,$balancer,$lastentry)=@_;
 1164:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1165:         my ($udom,$uname) = ($1,$2);
 1166:         my $uprimary_id = &domain($udom,'primary');
 1167:         my $uintdom = &internet_dom($uprimary_id);
 1168:         my $intdom = &internet_dom($balancer);
 1169:         my $serverhomedom = &host_domain($balancer);
 1170:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1171:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1172:         }
 1173:     }
 1174:     return;
 1175: }
 1176: 
 1177: sub delbalcookie {
 1178:     my ($cookie,$balancer) =@_;
 1179:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1180:         my ($udom,$uname) = ($1,$2);
 1181:         my $uprimary_id = &domain($udom,'primary');
 1182:         my $uintdom = &internet_dom($uprimary_id);
 1183:         my $intdom = &internet_dom($balancer);
 1184:         my $serverhomedom = &host_domain($balancer);
 1185:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1186:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1187:         }
 1188:     }
 1189: }
 1190: 
 1191: # -------------------------------- ask if server already has a session for user
 1192: sub has_user_session {
 1193:     my ($lonid,$udom,$uname) = @_;
 1194:     my $result = &reply(join(':','userhassession',
 1195: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1196:     return 1 if ($result eq 'ok');
 1197: 
 1198:     return 0;
 1199: }
 1200: 
 1201: # --------- determine least loaded server in a user's domain which allows login
 1202: 
 1203: sub choose_server {
 1204:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1205:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1206:     my %servers = &get_servers($udom);
 1207:     my $lowest_load = 30000;
 1208:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1209:     if ($skiploadbal) {
 1210:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1211:         unless (defined($cached)) {
 1212:             my $cachetime = 60*60*24;
 1213:             my %domconfig =
 1214:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1215:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1216:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1217:                                            $cachetime);
 1218:             }
 1219:         }
 1220:     }
 1221:     foreach my $lonhost (keys(%servers)) {
 1222:         if ($skiploadbal) {
 1223:             if (ref($balancers) eq 'HASH') {
 1224:                 next if (exists($balancers->{$lonhost}));
 1225:             }
 1226:         }
 1227:         my $loginvia;
 1228:         if ($checkloginvia) {
 1229:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1230:             if ($loginvia) {
 1231:                 my ($server,$path) = split(/:/,$loginvia);
 1232:                 ($login_host, $lowest_load) =
 1233:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1234:                 if ($login_host eq $server) {
 1235:                     $portal_path = $path;
 1236:                     $isredirect = 1;
 1237:                 }
 1238:             } else {
 1239:                 ($login_host, $lowest_load) =
 1240:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1241:                 if ($login_host eq $lonhost) {
 1242:                     $portal_path = '';
 1243:                     $isredirect = ''; 
 1244:                 }
 1245:             }
 1246:         } else {
 1247:             ($login_host, $lowest_load) =
 1248:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1249:         }
 1250:     }
 1251:     if ($login_host ne '') {
 1252:         $hostname = &hostname($login_host);
 1253:     }
 1254:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1255: }
 1256: 
 1257: sub get_course_sessions {
 1258:     my ($cnum,$cdom,$lastactivity) = @_;
 1259:     my %servers = &internet_dom_servers($cdom);
 1260:     my %returnhash;
 1261:     foreach my $server (sort(keys(%servers))) {
 1262:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1263:         my @pairs=split(/\&/,$rep);
 1264:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1265:             foreach my $item (@pairs) {
 1266:                 my ($key,$value)=split(/=/,$item,2);
 1267:                 $key = &unescape($key);
 1268:                 next if ($key =~ /^error: 2 /);
 1269:                 if (exists($returnhash{$key})) {
 1270:                     next if ($value < $returnhash{$key});
 1271:                 }
 1272:                 $returnhash{$key}=$value;
 1273:             }
 1274:         }
 1275:     }
 1276:     return %returnhash;
 1277: }
 1278: 
 1279: # --------------------------------------------- Try to change a user's password
 1280: 
 1281: sub changepass {
 1282:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1283:     $currentpass = &escape($currentpass);
 1284:     $newpass     = &escape($newpass);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1287: 		       $server);
 1288:     if (! $answer) {
 1289: 	&logthis("No reply on password change request to $server ".
 1290: 		 "by $uname in domain $udom.");
 1291:     } elsif ($answer =~ "^ok") {
 1292:         &logthis("$uname in $udom successfully changed their password ".
 1293: 		 "on $server.");
 1294:     } elsif ($answer =~ "^pwchange_failure") {
 1295: 	&logthis("$uname in $udom was unable to change their password ".
 1296: 		 "on $server.  The action was blocked by either lcpasswd ".
 1297: 		 "or pwchange");
 1298:     } elsif ($answer =~ "^non_authorized") {
 1299:         &logthis("$uname in $udom did not get their password correct when ".
 1300: 		 "attempting to change it on $server.");
 1301:     } elsif ($answer =~ "^auth_mode_error") {
 1302:         &logthis("$uname in $udom attempted to change their password despite ".
 1303: 		 "not being locally or internally authenticated on $server.");
 1304:     } elsif ($answer =~ "^unknown_user") {
 1305:         &logthis("$uname in $udom attempted to change their password ".
 1306: 		 "on $server but were unable to because $server is not ".
 1307: 		 "their home server.");
 1308:     } elsif ($answer =~ "^refused") {
 1309: 	&logthis("$server refused to change $uname in $udom password because ".
 1310: 		 "it was sent an unencrypted request to change the password.");
 1311:     } elsif ($answer =~ "invalid_client") {
 1312:         &logthis("$server refused to change $uname in $udom password because ".
 1313:                  "it was a reset by e-mail originating from an invalid server.");
 1314:     } elsif ($answer =~ "^prioruse") {
 1315:        &logthis("$server refused to change $uname in $udom password because ".
 1316:                 "the password had been used before");
 1317:     }
 1318:     return $answer;
 1319: }
 1320: 
 1321: # ----------------------- Try to determine user's current authentication scheme
 1322: 
 1323: sub queryauthenticate {
 1324:     my ($uname,$udom)=@_;
 1325:     my $uhome=&homeserver($uname,$udom);
 1326:     if (!$uhome) {
 1327: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1328: 	return 'no_host';
 1329:     }
 1330:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1331:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1332: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1333:     }
 1334:     return $answer;
 1335: }
 1336: 
 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
 1338: 
 1339: sub authenticate {
 1340:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1341:     $upass=&escape($upass);
 1342:     $uname= &LONCAPA::clean_username($uname);
 1343:     my $uhome=&homeserver($uname,$udom,1);
 1344:     my $newhome;
 1345:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1346: # Maybe the machine was offline and only re-appeared again recently?
 1347:         &reconlonc();
 1348: # One more
 1349: 	$uhome=&homeserver($uname,$udom,1);
 1350:         if (($uhome eq 'no_host') && $checkdefauth) {
 1351:             if (defined(&domain($udom,'primary'))) {
 1352:                 $newhome=&domain($udom,'primary');
 1353:             }
 1354:             if ($newhome ne '') {
 1355:                 $uhome = $newhome;
 1356:             }
 1357:         }
 1358: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1359: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1360: 	    return 'no_host';
 1361:         }
 1362:     }
 1363:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1364:     if ($answer eq 'authorized') {
 1365:         if ($newhome) {
 1366:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1367:             return 'no_account_on_host'; 
 1368:         } else {
 1369:             &logthis("User $uname at $udom authorized by $uhome");
 1370:             return $uhome;
 1371:         }
 1372:     }
 1373:     if ($answer eq 'non_authorized') {
 1374: 	&logthis("User $uname at $udom rejected by $uhome");
 1375: 	return 'no_host'; 
 1376:     }
 1377:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1378:     return 'no_host';
 1379: }
 1380: 
 1381: sub can_host_session {
 1382:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1383:     my $canhost = 1;
 1384:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1385:     if (ref($remotesessions) eq 'HASH') {
 1386:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1388:                 $canhost = 0;
 1389:             } else {
 1390:                 $canhost = 1;
 1391:             }
 1392:         }
 1393:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1394:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1395:                 $canhost = 1;
 1396:             } else {
 1397:                 $canhost = 0;
 1398:             }
 1399:         }
 1400:         if ($canhost) {
 1401:             if ($remotesessions->{'version'} ne '') {
 1402:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1403:                 if ($reqmajor ne '' && $reqminor ne '') {
 1404:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1405:                         my $major = $1;
 1406:                         my $minor = $2;
 1407:                         if (($major < $reqmajor ) ||
 1408:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1409:                             $canhost = 0;
 1410:                         }
 1411:                     } else {
 1412:                         $canhost = 0;
 1413:                     }
 1414:                 }
 1415:             }
 1416:         }
 1417:     }
 1418:     if ($canhost) {
 1419:         if (ref($hostedsessions) eq 'HASH') {
 1420:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1421:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1422:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1423:                 if (($uint_dom ne '') && 
 1424:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1425:                     $canhost = 0;
 1426:                 } else {
 1427:                     $canhost = 1;
 1428:                 }
 1429:             }
 1430:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1431:                 if (($uint_dom ne '') && 
 1432:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1433:                     $canhost = 1;
 1434:                 } else {
 1435:                     $canhost = 0;
 1436:                 }
 1437:             }
 1438:         }
 1439:     }
 1440:     return $canhost;
 1441: }
 1442: 
 1443: sub spare_can_host {
 1444:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1445:     my $canhost=1;
 1446:     my $try_server_hostname = &hostname($try_server);
 1447:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1448:     my $serverhomedom = &host_domain($serverhomeID);
 1449:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1450:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1451:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1452:             $canhost = 0;
 1453:         }
 1454:     }
 1455:     if ($canhost) {
 1456:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1457:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1458:                 unless (&shared_institution($udom,$try_server)) {
 1459:                     $canhost = 0;
 1460:                 }
 1461:             }
 1462:         }
 1463:     }
 1464:     if (($canhost) && ($uint_dom)) {
 1465:         my @intdoms;
 1466:         my $internet_names = &get_internet_names($try_server);
 1467:         if (ref($internet_names) eq 'ARRAY') {
 1468:             @intdoms = @{$internet_names};
 1469:         }
 1470:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1471:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1472:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1473:                                          $remotesessions,
 1474:                                          $defdomdefaults{'hostedsessions'});
 1475:         }
 1476:     }
 1477:     return $canhost;
 1478: }
 1479: 
 1480: sub this_host_spares {
 1481:     my ($dom) = @_;
 1482:     my ($dom_in_use,$lonhost_in_use,$result);
 1483:     my @hosts = &current_machine_ids();
 1484:     foreach my $lonhost (@hosts) {
 1485:         if (&host_domain($lonhost) eq $dom) {
 1486:             $dom_in_use = $dom;
 1487:             $lonhost_in_use = $lonhost;
 1488:             last;
 1489:         }
 1490:     }
 1491:     if ($dom_in_use ne '') {
 1492:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1493:     }
 1494:     if (ref($result) ne 'HASH') {
 1495:         $lonhost_in_use = $perlvar{'lonHostID'};
 1496:         $dom_in_use = &host_domain($lonhost_in_use);
 1497:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1498:         if (ref($result) ne 'HASH') {
 1499:             $result = \%spareid;
 1500:         }
 1501:     }
 1502:     return $result;
 1503: }
 1504: 
 1505: sub spares_for_offload  {
 1506:     my ($dom_in_use,$lonhost_in_use) = @_;
 1507:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1508:     if (defined($cached)) {
 1509:         return $result;
 1510:     } else {
 1511:         my $cachetime = 60*60*24;
 1512:         my %domconfig =
 1513:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1514:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1515:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1516:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1517:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1518:                 }
 1519:             }
 1520:         }
 1521:     }
 1522:     return;
 1523: }
 1524: 
 1525: sub get_lonbalancer_config {
 1526:     my ($servers) = @_;
 1527:     my ($currbalancer,$currtargets);
 1528:     if (ref($servers) eq 'HASH') {
 1529:         foreach my $server (keys(%{$servers})) {
 1530:             my %what = (
 1531:                          spareid => 1,
 1532:                          perlvar => 1,
 1533:                        );
 1534:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1535:             if ($result eq 'ok') {
 1536:                 if (ref($returnhash) eq 'HASH') {
 1537:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1538:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1539:                             $currbalancer = $server;
 1540:                             $currtargets = {};
 1541:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1542:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1543:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1544:                                 }
 1545:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1546:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1547:                                 }
 1548:                             }
 1549:                             last;
 1550:                         }
 1551:                     }
 1552:                 }
 1553:             }
 1554:         }
 1555:     }
 1556:     return ($currbalancer,$currtargets);
 1557: }
 1558: 
 1559: sub check_loadbalancing {
 1560:     my ($uname,$udom,$caller) = @_;
 1561:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1562:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1563:     my $lonhost = $perlvar{'lonHostID'};
 1564:     my @hosts = &current_machine_ids();
 1565:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1566:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1567:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1568:     my $serverhomedom = &host_domain($lonhost);
 1569:     my $domneedscache;
 1570:     my $cachetime = 60*60*24;
 1571: 
 1572:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1573:         $dom_in_use = $udom;
 1574:         $homeintdom = 1;
 1575:     } else {
 1576:         $dom_in_use = $serverhomedom;
 1577:     }
 1578:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1579:     unless (defined($cached)) {
 1580:         my %domconfig =
 1581:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1582:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1583:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1584:         } else {
 1585:             $domneedscache = $dom_in_use;
 1586:         }
 1587:     }
 1588:     if (ref($result) eq 'HASH') {
 1589:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1590:             &check_balancer_result($result,@hosts);
 1591:         if ($is_balancer) {
 1592:             if (ref($currrules) eq 'HASH') {
 1593:                 if ($homeintdom) {
 1594:                     if ($uname ne '') {
 1595:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1596:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1597:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1598:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1599:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1600:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1601:                             }
 1602:                         }
 1603:                         if ($rule_in_effect eq '') {
 1604:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1605:                             if ($userenv{'inststatus'} ne '') {
 1606:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1607:                                 my ($othertitle,$usertypes,$types) =
 1608:                                     &Apache::loncommon::sorted_inst_types($udom);
 1609:                                 if (ref($types) eq 'ARRAY') {
 1610:                                     foreach my $type (@{$types}) {
 1611:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1612:                                             if (exists($currrules->{$type})) {
 1613:                                                 $rule_in_effect = $currrules->{$type};
 1614:                                             }
 1615:                                         }
 1616:                                     }
 1617:                                 }
 1618:                             } else {
 1619:                                 if (exists($currrules->{'default'})) {
 1620:                                     $rule_in_effect = $currrules->{'default'};
 1621:                                 }
 1622:                             }
 1623:                         }
 1624:                     } else {
 1625:                         if (exists($currrules->{'default'})) {
 1626:                             $rule_in_effect = $currrules->{'default'};
 1627:                         }
 1628:                     }
 1629:                 } else {
 1630:                     if ($currrules->{'_LC_external'} ne '') {
 1631:                         $rule_in_effect = $currrules->{'_LC_external'};
 1632:                     }
 1633:                 }
 1634:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1635:                                                        $uname,$udom);
 1636:             }
 1637:         }
 1638:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1639:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1640:         unless (defined($cached)) {
 1641:             my %domconfig =
 1642:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1643:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1644:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1645:             } else {
 1646:                 $domneedscache = $serverhomedom;
 1647:             }
 1648:         }
 1649:         if (ref($result) eq 'HASH') {
 1650:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1651:                 &check_balancer_result($result,@hosts);
 1652:             if ($is_balancer) {
 1653:                 if (ref($currrules) eq 'HASH') {
 1654:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1655:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1656:                     }
 1657:                 }
 1658:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1659:                                                        $uname,$udom);
 1660:             }
 1661:         } else {
 1662:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1663:                 $is_balancer = 1;
 1664:                 $offloadto = &this_host_spares($dom_in_use);
 1665:             }
 1666:             unless (defined($cached)) {
 1667:                 $domneedscache = $serverhomedom;
 1668:             }
 1669:         }
 1670:     } else {
 1671:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1672:             $is_balancer = 1;
 1673:             $offloadto = &this_host_spares($dom_in_use);
 1674:         }
 1675:         unless (defined($cached)) {
 1676:             $domneedscache = $serverhomedom;
 1677:         }
 1678:     }
 1679:     if ($domneedscache) {
 1680:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1681:     }
 1682:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1683:         my $lowest_load = 30000;
 1684:         if (ref($offloadto) eq 'HASH') {
 1685:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1686:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1687:                     ($otherserver,$lowest_load) =
 1688:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1689:                 }
 1690:             }
 1691:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1692: 
 1693:             if (!$found_server) {
 1694:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1695:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1696:                         ($otherserver,$lowest_load) =
 1697:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1698:                     }
 1699:                 }
 1700:             }
 1701:         } elsif (ref($offloadto) eq 'ARRAY') {
 1702:             if (@{$offloadto} == 1) {
 1703:                 $otherserver = $offloadto->[0];
 1704:             } elsif (@{$offloadto} > 1) {
 1705:                 foreach my $try_server (@{$offloadto}) {
 1706:                     ($otherserver,$lowest_load) =
 1707:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1708:                 }
 1709:             }
 1710:         }
 1711:         unless ($caller eq 'login') {
 1712:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1713:                 $is_balancer = 0;
 1714:                 if ($uname ne '' && $udom ne '') {
 1715:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1716:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1717:                                  'user.loadbalcheck.time' => time});
 1718:                     }
 1719:                 }
 1720:             }
 1721:         }
 1722:     }
 1723:     if (($is_balancer) && (!$homeintdom)) {
 1724:         undef($setcookie);
 1725:     }
 1726:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1727: }
 1728: 
 1729: sub check_balancer_result {
 1730:     my ($result,@hosts) = @_;
 1731:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1732:     if (ref($result) eq 'HASH') {
 1733:         if ($result->{'lonhost'} ne '') {
 1734:             my $currbalancer = $result->{'lonhost'};
 1735:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1736:                 $is_balancer = 1;
 1737:                 $currtargets = $result->{'targets'};
 1738:                 $currrules = $result->{'rules'};
 1739:             }
 1740:             $dom_balancers = $currbalancer;
 1741:         } else {
 1742:             if (keys(%{$result})) {
 1743:                 foreach my $key (keys(%{$result})) {
 1744:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1745:                         (ref($result->{$key}) eq 'HASH')) {
 1746:                         $is_balancer = 1;
 1747:                         $currrules = $result->{$key}{'rules'};
 1748:                         $currtargets = $result->{$key}{'targets'};
 1749:                         $setcookie = $result->{$key}{'cookie'};
 1750:                         last;
 1751:                     }
 1752:                 }
 1753:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1754:             }
 1755:         }
 1756:     }
 1757:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1758: }
 1759: 
 1760: sub get_loadbalancer_targets {
 1761:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1762:     my $offloadto;
 1763:     if ($rule_in_effect eq 'none') {
 1764:         return [$perlvar{'lonHostID'}];
 1765:     } elsif ($rule_in_effect eq '') {
 1766:         $offloadto = $currtargets;
 1767:     } else {
 1768:         if ($rule_in_effect eq 'homeserver') {
 1769:             my $homeserver = &homeserver($uname,$udom);
 1770:             if ($homeserver ne 'no_host') {
 1771:                 $offloadto = [$homeserver];
 1772:             }
 1773:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1774:             my %domconfig =
 1775:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1776:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1777:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1778:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1779:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1780:                     }
 1781:                 }
 1782:             } else {
 1783:                 my %servers = &internet_dom_servers($udom);
 1784:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1785:                 if (&hostname($remotebalancer) ne '') {
 1786:                     $offloadto = [$remotebalancer];
 1787:                 }
 1788:             }
 1789:         } elsif (&hostname($rule_in_effect) ne '') {
 1790:             $offloadto = [$rule_in_effect];
 1791:         }
 1792:     }
 1793:     return $offloadto;
 1794: }
 1795: 
 1796: sub internet_dom_servers {
 1797:     my ($dom) = @_;
 1798:     my (%uniqservers,%servers);
 1799:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1800:     my @machinedoms = &machine_domains($primaryserver);
 1801:     foreach my $mdom (@machinedoms) {
 1802:         my %currservers = %servers;
 1803:         my %server = &get_servers($mdom);
 1804:         %servers = (%currservers,%server);
 1805:     }
 1806:     my %by_hostname;
 1807:     foreach my $id (keys(%servers)) {
 1808:         push(@{$by_hostname{$servers{$id}}},$id);
 1809:     }
 1810:     foreach my $hostname (sort(keys(%by_hostname))) {
 1811:         if (@{$by_hostname{$hostname}} > 1) {
 1812:             my $match = 0;
 1813:             foreach my $id (@{$by_hostname{$hostname}}) {
 1814:                 if (&host_domain($id) eq $dom) {
 1815:                     $uniqservers{$id} = $hostname;
 1816:                     $match = 1;
 1817:                 }
 1818:             }
 1819:             unless ($match) {
 1820:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1821:             }
 1822:         } else {
 1823:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1824:         }
 1825:     }
 1826:     return %uniqservers;
 1827: }
 1828: 
 1829: sub trusted_domains {
 1830:     my ($cmdtype,$calldom) = @_;
 1831:     my ($trusted,$untrusted);
 1832:     if (&domain($calldom) eq '') {
 1833:         return ($trusted,$untrusted);
 1834:     }
 1835:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1836:         return ($trusted,$untrusted);
 1837:     }
 1838:     my $callprimary = &domain($calldom,'primary');
 1839:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1840:     if ($intcalldom eq '') {
 1841:         return ($trusted,$untrusted);
 1842:     }
 1843: 
 1844:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1845:     unless (defined($cached)) {
 1846:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1847:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1848:         $trustconfig = $domconfig{'trust'};
 1849:     }
 1850:     if (ref($trustconfig)) {
 1851:         my (%possexc,%possinc,@allexc,@allinc); 
 1852:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1853:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1854:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1855:             }
 1856:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1857:                 $possinc{$intcalldom} = 1;
 1858:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1859:             }
 1860:         }
 1861:         if (keys(%possexc)) {
 1862:             if (keys(%possinc)) {
 1863:                 foreach my $key (sort(keys(%possexc))) {
 1864:                     next if ($key eq $intcalldom);
 1865:                     unless ($possinc{$key}) {
 1866:                         push(@allexc,$key);
 1867:                     }
 1868:                 }
 1869:             } else {
 1870:                 @allexc = sort(keys(%possexc));
 1871:             }
 1872:         }
 1873:         if (keys(%possinc)) {
 1874:             $possinc{$intcalldom} = 1;
 1875:             @allinc = sort(keys(%possinc));
 1876:         }
 1877:         if ((@allexc > 0) || (@allinc > 0)) {
 1878:             my %doms_by_intdom;
 1879:             my %allintdoms = &all_host_intdom();
 1880:             my %alldoms = &all_host_domain();
 1881:             foreach my $key (%allintdoms) {
 1882:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1883:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1884:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1885:                     }
 1886:                 } else {
 1887:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1888:                 }
 1889:             }
 1890:             foreach my $exc (@allexc) {
 1891:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1892:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1893:                 }
 1894:             }
 1895:             foreach my $inc (@allinc) {
 1896:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1897:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1898:                 }
 1899:             }
 1900:         }
 1901:     }
 1902:     return ($trusted,$untrusted);
 1903: }
 1904: 
 1905: sub will_trust {
 1906:     my ($cmdtype,$domain,$possdom) = @_;
 1907:     return 1 if ($domain eq $possdom);
 1908:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1909:     my $willtrust; 
 1910:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1911:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1912:             $willtrust = 1;
 1913:         }
 1914:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1915:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1916:             $willtrust = 1;
 1917:         }
 1918:     } else {
 1919:         $willtrust = 1;
 1920:     }
 1921:     return $willtrust;
 1922: }
 1923: 
 1924: # ---------------------- Find the homebase for a user from domain's lib servers
 1925: 
 1926: my %homecache;
 1927: sub homeserver {
 1928:     my ($uname,$udom,$ignoreBadCache)=@_;
 1929:     my $index="$uname:$udom";
 1930: 
 1931:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1932: 
 1933:     my %servers = &get_servers($udom,'library');
 1934:     foreach my $tryserver (keys(%servers)) {
 1935:         next if ($ignoreBadCache ne 'true' && 
 1936: 		 exists($badServerCache{$tryserver}));
 1937: 
 1938: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1939: 	if ($answer eq 'found') {
 1940: 	    delete($badServerCache{$tryserver}); 
 1941: 	    return $homecache{$index}=$tryserver;
 1942: 	} elsif ($answer eq 'no_host') {
 1943: 	    $badServerCache{$tryserver}=1;
 1944: 	}
 1945:     }    
 1946:     return 'no_host';
 1947: }
 1948: 
 1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1950: 
 1951: sub idget {
 1952:     my ($udom,$idsref,$namespace)=@_;
 1953:     my %returnhash=();
 1954:     my @ids=(); 
 1955:     if (ref($idsref) eq 'ARRAY') {
 1956:         @ids = @{$idsref};
 1957:     } else {
 1958:         return %returnhash; 
 1959:     }
 1960:     if ($namespace eq '') {
 1961:         $namespace = 'ids';
 1962:     }
 1963:     
 1964:     my %servers = &get_servers($udom,'library');
 1965:     foreach my $tryserver (keys(%servers)) {
 1966: 	my $idlist=join('&', map { &escape($_); } @ids);
 1967: 	if ($namespace eq 'ids') {
 1968: 	    $idlist=~tr/A-Z/a-z/;
 1969: 	}
 1970: 	my $reply;
 1971: 	if ($namespace eq 'ids') {
 1972: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1973: 	} else {
 1974: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1975: 	}
 1976: 	my @answer=();
 1977: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1978: 	    @answer=split(/\&/,$reply);
 1979: 	}                    ;
 1980: 	my $i;
 1981: 	for ($i=0;$i<=$#ids;$i++) {
 1982: 	    if ($answer[$i]) {
 1983: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1984: 	    }
 1985: 	}
 1986:     }
 1987:     return %returnhash;
 1988: }
 1989: 
 1990: # ------------------------------------- Find the IDs behind a list of usernames
 1991: 
 1992: sub idrget {
 1993:     my ($udom,@unames)=@_;
 1994:     my %returnhash=();
 1995:     foreach my $uname (@unames) {
 1996:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1997:     }
 1998:     return %returnhash;
 1999: }
 2000: 
 2001: # Store away a list of names and associated student/employee IDs or clicker IDs
 2002: 
 2003: sub idput {
 2004:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2005:     my %servers=();
 2006:     my %ids=();
 2007:     my %byid = ();
 2008:     if (ref($idsref) eq 'HASH') {
 2009:         %ids=%{$idsref};
 2010:     }
 2011:     if ($namespace eq '') {
 2012:         $namespace = 'ids'; 
 2013:     }
 2014:     foreach my $uname (keys(%ids)) {
 2015: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2016:         if ($uhom eq '') {
 2017:             $uhom=&homeserver($uname,$udom);
 2018:         }
 2019:         if ($uhom ne 'no_host') {
 2020:             my $esc_unam=&escape($uname);
 2021:             if ($namespace eq 'ids') {
 2022:                 my $id=&escape($ids{$uname});
 2023:                 $id=~tr/A-Z/a-z/;
 2024:                 my $esc_unam=&escape($uname);
 2025:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2026:             } else {
 2027:                 my @currids = split(/,/,$ids{$uname});
 2028:                 foreach my $id (@currids) {
 2029:                     $byid{$uhom}{$id} .= $uname.',';
 2030:                 }
 2031:             }
 2032:         }
 2033:     }
 2034:     if ($namespace eq 'clickers') {
 2035:         foreach my $server (keys(%byid)) {
 2036:             if (ref($byid{$server}) eq 'HASH') {
 2037:                 foreach my $id (keys(%{$byid{$server}})) {
 2038:                     $byid{$server} =~ s/,$//;
 2039:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2040:                 }
 2041:             }
 2042:         }
 2043:     }
 2044:     foreach my $server (keys(%servers)) {
 2045:         $servers{$server} =~ s/\&$//;
 2046:         if ($namespace eq 'ids') {     
 2047:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2048:         } else {
 2049:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2050:         }
 2051:     }
 2052: }
 2053: 
 2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2055: 
 2056: sub iddel {
 2057:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2058:     my %result=();
 2059:     my %ids=();
 2060:     my %byid = ();
 2061:     if (ref($idshashref) eq 'HASH') {
 2062:         %ids=%{$idshashref};
 2063:     } else {
 2064:         return %result;
 2065:     }
 2066:     if ($namespace eq '') {
 2067:         $namespace = 'ids';
 2068:     }
 2069:     my %servers=();
 2070:     while (my ($id,$unamestr) = each(%ids)) {
 2071:         if ($namespace eq 'ids') {
 2072:             my $uhom = $uhome;
 2073:             if ($uhom eq '') { 
 2074:                 $uhom=&homeserver($unamestr,$udom);
 2075:             }
 2076:             if ($uhom ne 'no_host') {
 2077:                 $servers{$uhom}.='&'.&escape($id);
 2078:             }
 2079:          } else {
 2080:             my @curritems = split(/,/,$ids{$id});
 2081:             foreach my $uname (@curritems) {
 2082:                 my $uhom = $uhome;
 2083:                 if ($uhom eq '') {
 2084:                     $uhom=&homeserver($uname,$udom);
 2085:                 }
 2086:                 if ($uhom ne 'no_host') { 
 2087:                     $byid{$uhom}{$id} .= $uname.',';
 2088:                 }
 2089:             }
 2090:         }
 2091:     }
 2092:     if ($namespace eq 'clickers') {
 2093:         foreach my $server (keys(%byid)) {
 2094:             if (ref($byid{$server}) eq 'HASH') {
 2095:                 foreach my $id (keys(%{$byid{$server}})) {
 2096:                     $byid{$server}{$id} =~ s/,$//;
 2097:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2098:                 }
 2099:             }
 2100:         }
 2101:     }
 2102:     foreach my $server (keys(%servers)) {
 2103:         $servers{$server} =~ s/\&$//;
 2104:         if ($namespace eq 'ids') {
 2105:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2106:         } elsif ($namespace eq 'clickers') {
 2107:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2108:         }
 2109:     }
 2110:     return %result;
 2111: }
 2112: 
 2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2114: 
 2115: sub updateclickers {
 2116:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2117:     my %clickers;
 2118:     if (ref($idshashref) eq 'HASH') {
 2119:         %clickers=%{$idshashref};
 2120:     } else {
 2121:         return;
 2122:     }
 2123:     my $items='';
 2124:     foreach my $item (keys(%clickers)) {
 2125:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2126:     }
 2127:     $items=~s/\&$//;
 2128:     my $request = "updateclickers:$udom:$action:$items";
 2129:     if ($critical) {
 2130:         return &critical($request,$uhome);
 2131:     } else {
 2132:         return &reply($request,$uhome);
 2133:     }
 2134: }
 2135: 
 2136: # ------------------------------dump from db file owned by domainconfig user
 2137: sub dump_dom {
 2138:     my ($namespace, $udom, $regexp) = @_;
 2139: 
 2140:     $udom ||= $env{'user.domain'};
 2141: 
 2142:     return () unless $udom;
 2143: 
 2144:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2145: }
 2146: 
 2147: # ------------------------------------------ get items from domain db files   
 2148: 
 2149: sub get_dom {
 2150:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2151:     return if ($udom eq 'public');
 2152:     my $items='';
 2153:     foreach my $item (@$storearr) {
 2154:         $items.=&escape($item).'&';
 2155:     }
 2156:     $items=~s/\&$//;
 2157:     if (!$udom) {
 2158:         $udom=$env{'user.domain'};
 2159:         return if ($udom eq 'public');
 2160:         if (defined(&domain($udom,'primary'))) {
 2161:             $uhome=&domain($udom,'primary');
 2162:         } else {
 2163:             undef($uhome);
 2164:         }
 2165:     } else {
 2166:         if (!$uhome) {
 2167:             if (defined(&domain($udom,'primary'))) {
 2168:                 $uhome=&domain($udom,'primary');
 2169:             }
 2170:         }
 2171:     }
 2172:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2173:         my $rep;
 2174:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2175:             # domain information is hosted on this machine
 2176:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2177:         } else {
 2178:             if ($encrypt) {
 2179:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2180:             } else {
 2181:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2182:             }
 2183:         }
 2184:         my %returnhash;
 2185:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2186:             return %returnhash;
 2187:         }
 2188:         my @pairs=split(/\&/,$rep);
 2189:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2190:             return @pairs;
 2191:         }
 2192:         my $i=0;
 2193:         foreach my $item (@$storearr) {
 2194:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2195:             $i++;
 2196:         }
 2197:         return %returnhash;
 2198:     } else {
 2199:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2200:     }
 2201: }
 2202: 
 2203: # -------------------------------------------- put items in domain db files 
 2204: 
 2205: sub put_dom {
 2206:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2207:     if (!$udom) {
 2208:         $udom=$env{'user.domain'};
 2209:         if (defined(&domain($udom,'primary'))) {
 2210:             $uhome=&domain($udom,'primary');
 2211:         } else {
 2212:             undef($uhome);
 2213:         }
 2214:     } else {
 2215:         if (!$uhome) {
 2216:             if (defined(&domain($udom,'primary'))) {
 2217:                 $uhome=&domain($udom,'primary');
 2218:             }
 2219:         }
 2220:     } 
 2221:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2222:         my $items='';
 2223:         foreach my $item (keys(%$storehash)) {
 2224:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2225:         }
 2226:         $items=~s/\&$//;
 2227:         if ($encrypt) {
 2228:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2229:         } else {
 2230:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2231:         }
 2232:     } else {
 2233:         &logthis("put_dom failed - no homeserver and/or domain");
 2234:     }
 2235: }
 2236: 
 2237: # --------------------- newput for items in db file owned by domainconfig user
 2238: sub newput_dom {
 2239:     my ($namespace,$storehash,$udom) = @_;
 2240:     my $result;
 2241:     if (!$udom) {
 2242:         $udom=$env{'user.domain'};
 2243:     }
 2244:     if ($udom) {
 2245:         my $uname = &get_domainconfiguser($udom);
 2246:         $result = &newput($namespace,$storehash,$udom,$uname);
 2247:     }
 2248:     return $result;
 2249: }
 2250: 
 2251: # --------------------- delete for items in db file owned by domainconfig user
 2252: sub del_dom {
 2253:     my ($namespace,$storearr,$udom)=@_;
 2254:     if (ref($storearr) eq 'ARRAY') {
 2255:         if (!$udom) {
 2256:             $udom=$env{'user.domain'};
 2257:         }
 2258:         if ($udom) {
 2259:             my $uname = &get_domainconfiguser($udom); 
 2260:             return &del($namespace,$storearr,$udom,$uname);
 2261:         }
 2262:     }
 2263: }
 2264: 
 2265: sub store_dom {
 2266:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
 2267:     $$storehash{'ip'}=&get_requestor_ip();
 2268:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2269:     my $namevalue='';
 2270:     foreach my $key (keys(%{$storehash})) {
 2271:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2272:     }
 2273:     $namevalue=~s/\&$//;
 2274:     if (grep { $_ eq $home } current_machine_ids()) {
 2275:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
 2276:     } else {
 2277:         if ($namespace eq 'private') {
 2278:             return 'refused';
 2279:         } elsif ($encrypt) {
 2280:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
 2281:         } else {
 2282:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
 2283:         }
 2284:     }
 2285: }
 2286: 
 2287: sub restore_dom {
 2288:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
 2289:     my $answer;
 2290:     if (grep { $_ eq $home } current_machine_ids()) {
 2291:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
 2292:     } elsif ($namespace ne 'private') {
 2293:         if ($encrypt) {
 2294:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
 2295:         } else {
 2296:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
 2297:         }
 2298:     }
 2299:     my %returnhash=();
 2300:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
 2301:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
 2302:         foreach my $line (split(/\&/,$answer)) {
 2303:             my ($name,$value)=split(/\=/,$line);
 2304:             $returnhash{&unescape($name)}=&thaw_unescape($value);
 2305:         }
 2306:         my $version;
 2307:         for ($version=1;$version<=$returnhash{'version'};$version++) {
 2308:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2309:                 $returnhash{$item}=$returnhash{$version.':'.$item};
 2310:             }
 2311:         }
 2312:     }
 2313:     return %returnhash;
 2314: }
 2315: 
 2316: # ----------------------------------construct domainconfig user for a domain 
 2317: sub get_domainconfiguser {
 2318:     my ($udom) = @_;
 2319:     return $udom.'-domainconfig';
 2320: }
 2321: 
 2322: sub retrieve_inst_usertypes {
 2323:     my ($udom) = @_;
 2324:     my (%returnhash,@order);
 2325:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2326:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2327:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2328:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2329:     } else {
 2330:         if (defined(&domain($udom,'primary'))) {
 2331:             my $uhome=&domain($udom,'primary');
 2332:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2333:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2334:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2335:                 return (\%returnhash,\@order);
 2336:             }
 2337:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2338:             my @pairs=split(/\&/,$hashitems);
 2339:             foreach my $item (@pairs) {
 2340:                 my ($key,$value)=split(/=/,$item,2);
 2341:                 $key = &unescape($key);
 2342:                 next if ($key =~ /^error: 2 /);
 2343:                 $returnhash{$key}=&thaw_unescape($value);
 2344:             }
 2345:             my @esc_order = split(/\&/,$orderitems);
 2346:             foreach my $item (@esc_order) {
 2347:                 push(@order,&unescape($item));
 2348:             }
 2349:         } else {
 2350:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2351:         }
 2352:         return (\%returnhash,\@order);
 2353:     }
 2354: }
 2355: 
 2356: sub is_domainimage {
 2357:     my ($url) = @_;
 2358:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2359:         if (&domain($1) ne '') {
 2360:             return '1';
 2361:         }
 2362:     }
 2363:     return;
 2364: }
 2365: 
 2366: sub inst_directory_query {
 2367:     my ($srch) = @_;
 2368:     my $udom = $srch->{'srchdomain'};
 2369:     my %results;
 2370:     my $homeserver = &domain($udom,'primary');
 2371:     my $outcome;
 2372:     if ($homeserver ne '') {
 2373:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2374:             if ($srch->{'srchby'} eq 'email') {
 2375:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2376:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2377:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2378:                     (($major == 2) && ($minor < 12))) {
 2379:                     return;
 2380:                 }
 2381:             }
 2382:         }
 2383: 	my $queryid=&reply("querysend:instdirsearch:".
 2384: 			   &escape($srch->{'srchby'}).':'.
 2385: 			   &escape($srch->{'srchterm'}).':'.
 2386: 			   &escape($srch->{'srchtype'}),$homeserver);
 2387: 	my $host=&hostname($homeserver);
 2388: 	if ($queryid !~/^\Q$host\E\_/) {
 2389: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2390: 	    return;
 2391: 	}
 2392: 	my $response = &get_query_reply($queryid);
 2393: 	my $maxtries = 5;
 2394: 	my $tries = 1;
 2395: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2396: 	    $response = &get_query_reply($queryid);
 2397: 	    $tries ++;
 2398: 	}
 2399: 
 2400:         if (!&error($response) && $response ne 'refused') {
 2401:             if ($response eq 'unavailable') {
 2402:                 $outcome = $response;
 2403:             } else {
 2404:                 $outcome = 'ok';
 2405:                 my @matches = split(/\n/,$response);
 2406:                 foreach my $match (@matches) {
 2407:                     my ($key,$value) = split(/=/,$match);
 2408:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2409:                 }
 2410:             }
 2411:         }
 2412:     }
 2413:     return ($outcome,%results);
 2414: }
 2415: 
 2416: sub usersearch {
 2417:     my ($srch) = @_;
 2418:     my $dom = $srch->{'srchdomain'};
 2419:     my %results;
 2420:     my %libserv = &all_library();
 2421:     my $query = 'usersearch';
 2422:     foreach my $tryserver (keys(%libserv)) {
 2423:         if (&host_domain($tryserver) eq $dom) {
 2424:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2425:                 if ($srch->{'srchby'} eq 'email') {
 2426:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2427:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2428:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2429:                              (($major == 2) && ($minor < 12)));
 2430:                 }
 2431:             }
 2432:             my $host=&hostname($tryserver);
 2433:             my $queryid=
 2434:                 &reply("querysend:".&escape($query).':'.
 2435:                        &escape($srch->{'srchby'}).':'.
 2436:                        &escape($srch->{'srchtype'}).':'.
 2437:                        &escape($srch->{'srchterm'}),$tryserver);
 2438:             if ($queryid !~/^\Q$host\E\_/) {
 2439:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2440:                 next;
 2441:             }
 2442:             my $reply = &get_query_reply($queryid);
 2443:             my $maxtries = 1;
 2444:             my $tries = 1;
 2445:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2446:                 $reply = &get_query_reply($queryid);
 2447:                 $tries ++;
 2448:             }
 2449:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2450:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2451:             } else {
 2452:                 my @matches;
 2453:                 if ($reply =~ /\n/) {
 2454:                     @matches = split(/\n/,$reply);
 2455:                 } else {
 2456:                     @matches = split(/\&/,$reply);
 2457:                 }
 2458:                 foreach my $match (@matches) {
 2459:                     my ($uname,$udom,%userhash);
 2460:                     foreach my $entry (split(/:/,$match)) {
 2461:                         my ($key,$value) =
 2462:                             map {&unescape($_);} split(/=/,$entry);
 2463:                         $userhash{$key} = $value;
 2464:                         if ($key eq 'username') {
 2465:                             $uname = $value;
 2466:                         } elsif ($key eq 'domain') {
 2467:                             $udom = $value;
 2468:                         }
 2469:                     }
 2470:                     $results{$uname.':'.$udom} = \%userhash;
 2471:                 }
 2472:             }
 2473:         }
 2474:     }
 2475:     return %results;
 2476: }
 2477: 
 2478: sub get_instuser {
 2479:     my ($udom,$uname,$id) = @_;
 2480:     my $homeserver = &domain($udom,'primary');
 2481:     my ($outcome,%results);
 2482:     if ($homeserver ne '') {
 2483:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2484:                            &escape($id).':'.&escape($udom),$homeserver);
 2485:         my $host=&hostname($homeserver);
 2486:         if ($queryid !~/^\Q$host\E\_/) {
 2487:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2488:             return;
 2489:         }
 2490:         my $response = &get_query_reply($queryid);
 2491:         my $maxtries = 5;
 2492:         my $tries = 1;
 2493:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2494:             $response = &get_query_reply($queryid);
 2495:             $tries ++;
 2496:         }
 2497:         if (!&error($response) && $response ne 'refused') {
 2498:             if ($response eq 'unavailable') {
 2499:                 $outcome = $response;
 2500:             } else {
 2501:                 $outcome = 'ok';
 2502:                 my @matches = split(/\n/,$response);
 2503:                 foreach my $match (@matches) {
 2504:                     my ($key,$value) = split(/=/,$match);
 2505:                     $results{&unescape($key)} = &thaw_unescape($value);
 2506:                 }
 2507:             }
 2508:         }
 2509:     }
 2510:     my %userinfo;
 2511:     if (ref($results{$uname}) eq 'HASH') {
 2512:         %userinfo = %{$results{$uname}};
 2513:     } 
 2514:     return ($outcome,%userinfo);
 2515: }
 2516: 
 2517: sub get_multiple_instusers {
 2518:     my ($udom,$users,$caller) = @_;
 2519:     my ($outcome,$results);
 2520:     if (ref($users) eq 'HASH') {
 2521:         my $count = keys(%{$users}); 
 2522:         my $requested = &freeze_escape($users);
 2523:         my $homeserver = &domain($udom,'primary');
 2524:         if ($homeserver ne '') {
 2525:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2526:             my $host=&hostname($homeserver);
 2527:             if ($queryid !~/^\Q$host\E\_/) {
 2528:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2529:                          ' for host: '.$homeserver.'in domain '.$udom);
 2530:                 return ($outcome,$results);
 2531:             }
 2532:             my $response = &get_query_reply($queryid);
 2533:             my $maxtries = 5;
 2534:             if ($count > 100) {
 2535:                 $maxtries = 1+int($count/20);
 2536:             }
 2537:             my $tries = 1;
 2538:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2539:                 $response = &get_query_reply($queryid);
 2540:                 $tries ++;
 2541:             }
 2542:             if ($response eq '') {
 2543:                 $results = {};
 2544:                 foreach my $key (keys(%{$users})) {
 2545:                     my ($uname,$id);
 2546:                     if ($caller eq 'id') {
 2547:                         $id = $key;
 2548:                     } else {
 2549:                         $uname = $key;
 2550:                     }
 2551:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2552:                     $outcome = $resp;
 2553:                     if ($resp eq 'ok') {
 2554:                         %{$results} = (%{$results}, %info);
 2555:                     } else {
 2556:                         last;
 2557:                     }
 2558:                 }
 2559:             } elsif(!&error($response) && ($response ne 'refused')) {
 2560:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2561:                     $outcome = $response;
 2562:                 } else {
 2563:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2564:                     if ($outcome eq 'ok') {
 2565:                         $results = &thaw_unescape($userdata); 
 2566:                     }
 2567:                 }
 2568:             }
 2569:         }
 2570:     }
 2571:     return ($outcome,$results);
 2572: }
 2573: 
 2574: sub inst_rulecheck {
 2575:     my ($udom,$uname,$id,$item,$rules) = @_;
 2576:     my %returnhash;
 2577:     if ($udom ne '') {
 2578:         if (ref($rules) eq 'ARRAY') {
 2579:             @{$rules} = map {&escape($_);} (@{$rules});
 2580:             my $rulestr = join(':',@{$rules});
 2581:             my $homeserver=&domain($udom,'primary');
 2582:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2583:                 my $response;
 2584:                 if ($item eq 'username') {                
 2585:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2586:                                               ':'.&escape($uname).':'.$rulestr,
 2587:                                               $homeserver));
 2588:                 } elsif ($item eq 'id') {
 2589:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2590:                                               ':'.&escape($id).':'.$rulestr,
 2591:                                               $homeserver));
 2592:                 } elsif ($item eq 'selfcreate') {
 2593:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2594:                                                &escape($udom).':'.&escape($uname).
 2595:                                               ':'.$rulestr,$homeserver));
 2596:                 }
 2597:                 if ($response ne 'refused') {
 2598:                     my @pairs=split(/\&/,$response);
 2599:                     foreach my $item (@pairs) {
 2600:                         my ($key,$value)=split(/=/,$item,2);
 2601:                         $key = &unescape($key);
 2602:                         next if ($key =~ /^error: 2 /);
 2603:                         $returnhash{$key}=&thaw_unescape($value);
 2604:                     }
 2605:                 }
 2606:             }
 2607:         }
 2608:     }
 2609:     return %returnhash;
 2610: }
 2611: 
 2612: sub inst_userrules {
 2613:     my ($udom,$check) = @_;
 2614:     my (%ruleshash,@ruleorder);
 2615:     if ($udom ne '') {
 2616:         my $homeserver=&domain($udom,'primary');
 2617:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2618:             my $response;
 2619:             if ($check eq 'id') {
 2620:                 $response=&reply('instidrules:'.&escape($udom),
 2621:                                  $homeserver);
 2622:             } elsif ($check eq 'email') {
 2623:                 $response=&reply('instemailrules:'.&escape($udom),
 2624:                                  $homeserver);
 2625:             } else {
 2626:                 $response=&reply('instuserrules:'.&escape($udom),
 2627:                                  $homeserver);
 2628:             }
 2629:             if (($response ne 'refused') && ($response ne 'error') && 
 2630:                 ($response ne 'unknown_cmd') && 
 2631:                 ($response ne 'no_such_host')) {
 2632:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2633:                 my @pairs=split(/\&/,$hashitems);
 2634:                 foreach my $item (@pairs) {
 2635:                     my ($key,$value)=split(/=/,$item,2);
 2636:                     $key = &unescape($key);
 2637:                     next if ($key =~ /^error: 2 /);
 2638:                     $ruleshash{$key}=&thaw_unescape($value);
 2639:                 }
 2640:                 my @esc_order = split(/\&/,$orderitems);
 2641:                 foreach my $item (@esc_order) {
 2642:                     push(@ruleorder,&unescape($item));
 2643:                 }
 2644:             }
 2645:         }
 2646:     }
 2647:     return (\%ruleshash,\@ruleorder);
 2648: }
 2649: 
 2650: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2651: 
 2652: sub get_domain_defaults {
 2653:     my ($domain,$ignore_cache) = @_;
 2654:     return if (($domain eq '') || ($domain eq 'public'));
 2655:     my $cachetime = 60*60*24;
 2656:     unless ($ignore_cache) {
 2657:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2658:         if (defined($cached)) {
 2659:             if (ref($result) eq 'HASH') {
 2660:                 return %{$result};
 2661:             }
 2662:         }
 2663:     }
 2664:     my %domdefaults;
 2665:     my %domconfig =
 2666:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2667:                                   'requestcourses','inststatus',
 2668:                                   'coursedefaults','usersessions',
 2669:                                   'requestauthor','selfenrollment',
 2670:                                   'coursecategories','ssl','autoenroll',
 2671:                                   'trust','helpsettings','wafproxy','ltisec'],$domain);
 2672:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2673:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2674:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2675:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2676:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2677:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2678:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2679:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2680:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2681:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2682:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2683:     } else {
 2684:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2685:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2686:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2687:     }
 2688:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2689:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2690:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2691:         } else {
 2692:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2693:         }
 2694:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2695:         foreach my $item (@usertools) {
 2696:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2697:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2698:             }
 2699:         }
 2700:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2701:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2702:         }
 2703:     }
 2704:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2705:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2706:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2707:         }
 2708:     }
 2709:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2710:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2711:     }
 2712:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2713:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2714:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2715:         }
 2716:     }
 2717:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2718:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2719:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2720:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2721:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2722:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2723:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2724:         }
 2725:         foreach my $type (@coursetypes) {
 2726:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2727:                 unless ($type eq 'community') {
 2728:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2729:                 }
 2730:             }
 2731:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2732:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2733:             }
 2734:             if ($domdefaults{'postsubmit'} eq 'on') {
 2735:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2736:                     $domdefaults{$type.'postsubtimeout'} = 
 2737:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2738:                 }
 2739:             }
 2740:         }
 2741:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2742:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2743:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2744:                 if (@clonecodes) {
 2745:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2746:                 }
 2747:             }
 2748:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2749:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2750:         }
 2751:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2752:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2753:         }
 2754:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2755:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2756:         }
 2757:     }
 2758:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2759:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2760:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2761:         }
 2762:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2763:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2764:         }
 2765:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2766:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2767:         }
 2768:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2769:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2770:         }
 2771:     }
 2772:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2773:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2774:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2775:                             'approval','limit');
 2776:             foreach my $type (@coursetypes) {
 2777:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2778:                     my @mgrdc = ();
 2779:                     foreach my $item (@settings) {
 2780:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2781:                             push(@mgrdc,$item);
 2782:                         }
 2783:                     }
 2784:                     if (@mgrdc) {
 2785:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2786:                     }
 2787:                 }
 2788:             }
 2789:         }
 2790:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2791:             foreach my $type (@coursetypes) {
 2792:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2793:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2794:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2795:                     }
 2796:                 }
 2797:             }
 2798:         }
 2799:     }
 2800:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2801:         $domdefaults{'catauth'} = 'std';
 2802:         $domdefaults{'catunauth'} = 'std';
 2803:         if ($domconfig{'coursecategories'}{'auth'}) {
 2804:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2805:         }
 2806:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2807:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2808:         }
 2809:     }
 2810:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2811:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2812:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2813:         }
 2814:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2815:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2816:         }
 2817:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2818:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2819:         }
 2820:     }
 2821:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2822:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2823:         foreach my $prefix (@prefixes) {
 2824:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2825:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2826:             }
 2827:         }
 2828:     }
 2829:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2830:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2831:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2832:     }
 2833:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2834:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2835:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2836:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2837:         }
 2838:     }
 2839:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2840:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2841:             if ($domconfig{'wafproxy'}{$item}) {
 2842:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2843:             }
 2844:         }
 2845:     }
 2846:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2847:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2848:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2849:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2850:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2851:         }
 2852:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2853:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2854:                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2855:             }
 2856:         }
 2857:     }
 2858:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2859:     return %domdefaults;
 2860: }
 2861: 
 2862: sub get_dom_cats {
 2863:     my ($dom) = @_;
 2864:     return unless (&domain($dom));
 2865:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2866:     unless (defined($cached)) {
 2867:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2868:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2869:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2870:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2871:             } else {
 2872:                 $cats = {};
 2873:             }
 2874:         } else {
 2875:             $cats = {};
 2876:         }
 2877:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2878:     }
 2879:     return $cats;
 2880: }
 2881: 
 2882: sub get_dom_instcats {
 2883:     my ($dom) = @_;
 2884:     return unless (&domain($dom));
 2885:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2886:     unless (defined($cached)) {
 2887:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2888:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2889:         if ($totcodes > 0) {
 2890:             my $caller = 'global';
 2891:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2892:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2893:                 $instcats = {
 2894:                                 codes => \%codes,
 2895:                                 codetitles => \@codetitles,
 2896:                                 cat_titles => \%cat_titles,
 2897:                                 cat_order => \%cat_order,
 2898:                             };
 2899:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2900:             }
 2901:         }
 2902:     }
 2903:     return $instcats;
 2904: }
 2905: 
 2906: sub retrieve_instcodes {
 2907:     my ($coursecodes,$dom) = @_;
 2908:     my $totcodes;
 2909:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2910:     foreach my $course (keys(%courses)) {
 2911:         if (ref($courses{$course}) eq 'HASH') {
 2912:             if ($courses{$course}{'inst_code'} ne '') {
 2913:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2914:                 $totcodes ++;
 2915:             }
 2916:         }
 2917:     }
 2918:     return $totcodes;
 2919: }
 2920: 
 2921: sub course_portal_url {
 2922:     my ($cnum,$cdom,$r) = @_;
 2923:     my $chome = &homeserver($cnum,$cdom);
 2924:     my $hostname = &hostname($chome);
 2925:     my $protocol = $protocol{$chome};
 2926:     $protocol = 'http' if ($protocol ne 'https');
 2927:     my %domdefaults = &get_domain_defaults($cdom);
 2928:     my $firsturl;
 2929:     if ($domdefaults{'portal_def'}) {
 2930:         $firsturl = $domdefaults{'portal_def'};
 2931:     } else {
 2932:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
 2933:         $hostname = $alias if ($alias ne '');
 2934:         $firsturl = $protocol.'://'.$hostname;
 2935:     }
 2936:     return $firsturl;
 2937: }
 2938: 
 2939: # --------------------------------------------- Get domain config for passwords
 2940: 
 2941: sub get_passwdconf {
 2942:     my ($dom) = @_;
 2943:     my (%passwdconf,$gotconf,$lookup);
 2944:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2945:     if (defined($cached)) {
 2946:         if (ref($result) eq 'HASH') {
 2947:             %passwdconf = %{$result};
 2948:             $gotconf = 1;
 2949:         }
 2950:     }
 2951:     unless ($gotconf) {
 2952:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2953:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2954:             %passwdconf = %{$domconfig{'passwords'}};
 2955:         }
 2956:         my $cachetime = 24*60*60;
 2957:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2958:     }
 2959:     return %passwdconf;
 2960: }
 2961: 
 2962: # --------------------------------------------------- Assign a key to a student
 2963: 
 2964: sub assign_access_key {
 2965: #
 2966: # a valid key looks like uname:udom#comments
 2967: # comments are being appended
 2968: #
 2969:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2970:     $kdom=
 2971:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2972:     $knum=
 2973:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2974:     $cdom=
 2975:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2976:     $cnum=
 2977:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2978:     $udom=$env{'user.name'} unless (defined($udom));
 2979:     $uname=$env{'user.domain'} unless (defined($uname));
 2980:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2981:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2982:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2983:                                                   # assigned to this person
 2984:                                                   # - this should not happen,
 2985:                                                   # unless something went wrong
 2986:                                                   # the first time around
 2987: # ready to assign
 2988:         $logentry=$1.'; '.$logentry;
 2989:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2990:                                                  $kdom,$knum) eq 'ok') {
 2991: # key now belongs to user
 2992: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2993:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2994:                 &appenv({'environment.'.$envkey => $ckey});
 2995:                 return 'ok';
 2996:             } else {
 2997:                 return 
 2998:   'error: Count not permanently assign key, will need to be re-entered later.';
 2999: 	    }
 3000:         } else {
 3001:             return 'error: Could not assign key, try again later.';
 3002:         }
 3003:     } elsif (!$existing{$ckey}) {
 3004: # the key does not exist
 3005: 	return 'error: The key does not exist';
 3006:     } else {
 3007: # the key is somebody else's
 3008: 	return 'error: The key is already in use';
 3009:     }
 3010: }
 3011: 
 3012: # ------------------------------------------ put an additional comment on a key
 3013: 
 3014: sub comment_access_key {
 3015: #
 3016: # a valid key looks like uname:udom#comments
 3017: # comments are being appended
 3018: #
 3019:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3020:     $cdom=
 3021:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3022:     $cnum=
 3023:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3024:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3025:     if ($existing{$ckey}) {
 3026:         $existing{$ckey}.='; '.$logentry;
 3027: # ready to assign
 3028:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3029:                                                  $cdom,$cnum) eq 'ok') {
 3030: 	    return 'ok';
 3031:         } else {
 3032: 	    return 'error: Count not store comment.';
 3033:         }
 3034:     } else {
 3035: # the key does not exist
 3036: 	return 'error: The key does not exist';
 3037:     }
 3038: }
 3039: 
 3040: # ------------------------------------------------------ Generate a set of keys
 3041: 
 3042: sub generate_access_keys {
 3043:     my ($number,$cdom,$cnum,$logentry)=@_;
 3044:     $cdom=
 3045:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3046:     $cnum=
 3047:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3048:     unless (&allowed('mky',$cdom)) { return 0; }
 3049:     unless (($cdom) && ($cnum)) { return 0; }
 3050:     if ($number>10000) { return 0; }
 3051:     sleep(2); # make sure don't get same seed twice
 3052:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3053:     my $total=0;
 3054:     for (my $i=1;$i<=$number;$i++) {
 3055:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3056:                   sprintf("%lx",int(100000*rand)).'-'.
 3057:                   sprintf("%lx",int(100000*rand));
 3058:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3059:        $newkey=~s/0/h/g; # and also 0 and O
 3060:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3061:        if ($existing{$newkey}) {
 3062:            $i--;
 3063:        } else {
 3064: 	  if (&put('accesskeys',
 3065:               { $newkey => '# generated '.localtime().
 3066:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3067:                            '; '.$logentry },
 3068: 		   $cdom,$cnum) eq 'ok') {
 3069:               $total++;
 3070: 	  }
 3071:        }
 3072:     }
 3073:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3074:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3075:     return $total;
 3076: }
 3077: 
 3078: # ------------------------------------------------------- Validate an accesskey
 3079: 
 3080: sub validate_access_key {
 3081:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3082:     $cdom=
 3083:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3084:     $cnum=
 3085:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3086:     $udom=$env{'user.domain'} unless (defined($udom));
 3087:     $uname=$env{'user.name'} unless (defined($uname));
 3088:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3089:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3090: }
 3091: 
 3092: # ------------------------------------- Find the section of student in a course
 3093: sub devalidate_getsection_cache {
 3094:     my ($udom,$unam,$courseid)=@_;
 3095:     my $hashid="$udom:$unam:$courseid";
 3096:     &devalidate_cache_new('getsection',$hashid);
 3097: }
 3098: 
 3099: sub courseid_to_courseurl {
 3100:     my ($courseid) = @_;
 3101:     #already url style courseid
 3102:     return $courseid if ($courseid =~ m{^/});
 3103: 
 3104:     if (exists($env{'course.'.$courseid.'.num'})) {
 3105: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3106: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3107: 	return "/$cdom/$cnum";
 3108:     }
 3109: 
 3110:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3111:     if (exists($courseinfo{'num'})) {
 3112: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3113:     }
 3114: 
 3115:     return undef;
 3116: }
 3117: 
 3118: sub getsection {
 3119:     my ($udom,$unam,$courseid)=@_;
 3120:     my $cachetime=1800;
 3121: 
 3122:     my $hashid="$udom:$unam:$courseid";
 3123:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3124:     if (defined($cached)) { return $result; }
 3125: 
 3126:     my %Pending; 
 3127:     my %Expired;
 3128:     #
 3129:     # Each role can either have not started yet (pending), be active, 
 3130:     #    or have expired.
 3131:     #
 3132:     # If there is an active role, we are done.
 3133:     #
 3134:     # If there is more than one role which has not started yet, 
 3135:     #     choose the one which will start sooner
 3136:     # If there is one role which has not started yet, return it.
 3137:     #
 3138:     # If there is more than one expired role, choose the one which ended last.
 3139:     # If there is a role which has expired, return it.
 3140:     #
 3141:     $courseid = &courseid_to_courseurl($courseid);
 3142:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3143:     foreach my $key (keys(%roleshash)) {
 3144:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3145:         my $section=$1;
 3146:         if ($key eq $courseid.'_st') { $section=''; }
 3147:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3148:         my $now=time;
 3149:         if (defined($end) && $end && ($now > $end)) {
 3150:             $Expired{$end}=$section;
 3151:             next;
 3152:         }
 3153:         if (defined($start) && $start && ($now < $start)) {
 3154:             $Pending{$start}=$section;
 3155:             next;
 3156:         }
 3157:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3158:     }
 3159:     #
 3160:     # Presumedly there will be few matching roles from the above
 3161:     # loop and the sorting time will be negligible.
 3162:     if (scalar(keys(%Pending))) {
 3163:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3164:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3165:     } 
 3166:     if (scalar(keys(%Expired))) {
 3167:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3168:         my $time = pop(@sorted);
 3169:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3170:     }
 3171:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3172: }
 3173: 
 3174: sub save_cache {
 3175:     &purge_remembered();
 3176:     #&Apache::loncommon::validate_page();
 3177:     undef(%env);
 3178:     undef($env_loaded);
 3179: }
 3180: 
 3181: my $to_remember=-1;
 3182: my %remembered;
 3183: my %accessed;
 3184: my $kicks=0;
 3185: my $hits=0;
 3186: sub make_key {
 3187:     my ($name,$id) = @_;
 3188:     if (length($id) > 65 
 3189: 	&& length(&escape($id)) > 200) {
 3190: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3191:     }
 3192:     return &escape($name.':'.$id);
 3193: }
 3194: 
 3195: sub devalidate_cache_new {
 3196:     my ($name,$id,$debug) = @_;
 3197:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3198:     my $remembered_id=$name.':'.$id;
 3199:     $id=&make_key($name,$id);
 3200:     $memcache->delete($id);
 3201:     delete($remembered{$remembered_id});
 3202:     delete($accessed{$remembered_id});
 3203: }
 3204: 
 3205: sub is_cached_new {
 3206:     my ($name,$id,$debug) = @_;
 3207:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3208:     if (exists($remembered{$remembered_id})) {
 3209: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3210: 	$accessed{$remembered_id}=[&gettimeofday()];
 3211: 	$hits++;
 3212: 	return ($remembered{$remembered_id},1);
 3213:     }
 3214:     $id=&make_key($name,$id);
 3215:     my $value = $memcache->get($id);
 3216:     if (!(defined($value))) {
 3217: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3218: 	return (undef,undef);
 3219:     }
 3220:     if ($value eq '__undef__') {
 3221: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3222: 	$value=undef;
 3223:     }
 3224:     &make_room($remembered_id,$value,$debug);
 3225:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3226:     return ($value,1);
 3227: }
 3228: 
 3229: sub do_cache_new {
 3230:     my ($name,$id,$value,$time,$debug) = @_;
 3231:     my $remembered_id=$name.':'.$id;
 3232:     $id=&make_key($name,$id);
 3233:     my $setvalue=$value;
 3234:     if (!defined($setvalue)) {
 3235: 	$setvalue='__undef__';
 3236:     }
 3237:     if (!defined($time) ) {
 3238: 	$time=600;
 3239:     }
 3240:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3241:     my $result = $memcache->set($id,$setvalue,$time);
 3242:     if (! $result) {
 3243: 	&logthis("caching of id -> $id  failed");
 3244: 	$memcache->disconnect_all();
 3245:     }
 3246:     # need to make a copy of $value
 3247:     &make_room($remembered_id,$value,$debug);
 3248:     return $value;
 3249: }
 3250: 
 3251: sub make_room {
 3252:     my ($remembered_id,$value,$debug)=@_;
 3253: 
 3254:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3255:                                     : $value;
 3256:     if ($to_remember<0) { return; }
 3257:     $accessed{$remembered_id}=[&gettimeofday()];
 3258:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3259:     my $to_kick;
 3260:     my $max_time=0;
 3261:     foreach my $other (keys(%accessed)) {
 3262: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3263: 	    $to_kick=$other;
 3264: 	    $max_time=&tv_interval($accessed{$other});
 3265: 	}
 3266:     }
 3267:     delete($remembered{$to_kick});
 3268:     delete($accessed{$to_kick});
 3269:     $kicks++;
 3270:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3271:     return;
 3272: }
 3273: 
 3274: sub purge_remembered {
 3275:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3276:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3277:     undef(%remembered);
 3278:     undef(%accessed);
 3279: }
 3280: # ------------------------------------- Read an entry from a user's environment
 3281: 
 3282: sub userenvironment {
 3283:     my ($udom,$unam,@what)=@_;
 3284:     my $items;
 3285:     foreach my $item (@what) {
 3286:         $items.=&escape($item).'&';
 3287:     }
 3288:     $items=~s/\&$//;
 3289:     my %returnhash=();
 3290:     my $uhome = &homeserver($unam,$udom);
 3291:     unless ($uhome eq 'no_host') {
 3292:         my @answer=split(/\&/, 
 3293:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3294:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3295:             return %returnhash;
 3296:         }
 3297:         my $i;
 3298:         for ($i=0;$i<=$#what;$i++) {
 3299: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3300:         }
 3301:     }
 3302:     return %returnhash;
 3303: }
 3304: 
 3305: # ---------------------------------------------------------- Get a studentphoto
 3306: sub studentphoto {
 3307:     my ($udom,$unam,$ext) = @_;
 3308:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3309:     if (defined($env{'request.course.id'})) {
 3310:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3311:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3312:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3313:             } else {
 3314:                 my ($result,$perm_reqd)=
 3315: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3316:                 if ($result eq 'ok') {
 3317:                     if (!($perm_reqd eq 'yes')) {
 3318:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3319:                     }
 3320:                 }
 3321:             }
 3322:         }
 3323:     } else {
 3324:         my ($result,$perm_reqd) = 
 3325: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3326:         if ($result eq 'ok') {
 3327:             if (!($perm_reqd eq 'yes')) {
 3328:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3329:             }
 3330:         }
 3331:     }
 3332:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3333: }
 3334: 
 3335: sub retrievestudentphoto {
 3336:     my ($udom,$unam,$ext,$type) = @_;
 3337:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3338:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3339:     if ($ret eq 'ok') {
 3340:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3341:         if ($type eq 'thumbnail') {
 3342:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3343:         }
 3344:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3345:         return $tokenurl;
 3346:     } else {
 3347:         if ($type eq 'thumbnail') {
 3348:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3349:         } else { 
 3350:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3351:         }
 3352:     }
 3353: }
 3354: 
 3355: # -------------------------------------------------------------------- New chat
 3356: 
 3357: sub chatsend {
 3358:     my ($newentry,$anon,$group)=@_;
 3359:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3360:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3361:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3362:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3363: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3364: 		   &escape($newentry)).':'.$group,$chome);
 3365: }
 3366: 
 3367: # ------------------------------------------ Find current version of a resource
 3368: 
 3369: sub getversion {
 3370:     my $fname=&clutter(shift);
 3371:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3372:     return &currentversion(&filelocation('',$fname));
 3373: }
 3374: 
 3375: sub currentversion {
 3376:     my $fname=shift;
 3377:     my $author=$fname;
 3378:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3379:     my ($udom,$uname)=split(/\//,$author);
 3380:     my $home=&homeserver($uname,$udom);
 3381:     if ($home eq 'no_host') { 
 3382:         return -1; 
 3383:     }
 3384:     my $answer=&reply("currentversion:$fname",$home);
 3385:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3386: 	return -1;
 3387:     }
 3388:     return $answer;
 3389: }
 3390: 
 3391: #
 3392: # Return special version number of resource if set by override, empty otherwise
 3393: #
 3394: sub usedversion {
 3395:     my $fname=shift;
 3396:     unless ($fname) { $fname=$env{'request.uri'}; }
 3397:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3398:     if ($urlversion) { return $urlversion; }
 3399:     return '';
 3400: }
 3401: 
 3402: # ----------------------------- Subscribe to a resource, return URL if possible
 3403: 
 3404: sub subscribe {
 3405:     my $fname=shift;
 3406:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3407:     $fname=~s/[\n\r]//g;
 3408:     my $author=$fname;
 3409:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3410:     my ($udom,$uname)=split(/\//,$author);
 3411:     my $home=homeserver($uname,$udom);
 3412:     if ($home eq 'no_host') {
 3413:         return 'not_found';
 3414:     }
 3415:     my $answer=reply("sub:$fname",$home);
 3416:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3417: 	$answer.=' by '.$home;
 3418:     }
 3419:     return $answer;
 3420: }
 3421:     
 3422: # -------------------------------------------------------------- Replicate file
 3423: 
 3424: sub repcopy {
 3425:     my $filename=shift;
 3426:     $filename=~s/\/+/\//g;
 3427:     my $londocroot = $perlvar{'lonDocRoot'};
 3428:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3429:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3430:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3431: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3432: 	return &repcopy_userfile($filename);
 3433:     }
 3434:     $filename=~s/[\n\r]//g;
 3435:     my $transname="$filename.in.transfer";
 3436: # FIXME: this should flock
 3437:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3438:     my $remoteurl=subscribe($filename);
 3439:     if ($remoteurl =~ /^con_lost by/) {
 3440: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3441:            return 'unavailable';
 3442:     } elsif ($remoteurl eq 'not_found') {
 3443: 	   #&logthis("Subscribe returned not_found: $filename");
 3444: 	   return 'not_found';
 3445:     } elsif ($remoteurl =~ /^rejected by/) {
 3446: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3447:            return 'forbidden';
 3448:     } elsif ($remoteurl eq 'directory') {
 3449:            return 'ok';
 3450:     } else {
 3451:         my $author=$filename;
 3452:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3453:         my ($udom,$uname)=split(/\//,$author);
 3454:         my $home=homeserver($uname,$udom);
 3455:         unless ($home eq $perlvar{'lonHostID'}) {
 3456:            my @parts=split(/\//,$filename);
 3457:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3458:            if ($path ne "$londocroot/res") {
 3459:                &logthis("Malconfiguration for replication: $filename");
 3460: 	       return 'bad_request';
 3461:            }
 3462:            my $count;
 3463:            for ($count=5;$count<$#parts;$count++) {
 3464:                $path.="/$parts[$count]";
 3465:                if ((-e $path)!=1) {
 3466: 		   mkdir($path,0777);
 3467:                }
 3468:            }
 3469:            my $request=new HTTP::Request('GET',"$remoteurl");
 3470:            my $response;
 3471:            if ($remoteurl =~ m{/raw/}) {
 3472:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3473:            } else {
 3474:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3475:            }
 3476:            if ($response->is_error()) {
 3477: 	       unlink($transname);
 3478:                my $message=$response->status_line;
 3479:                &logthis("<font color=\"blue\">WARNING:"
 3480:                        ." LWP get: $message: $filename</font>");
 3481:                return 'unavailable';
 3482:            } else {
 3483: 	       if ($remoteurl!~/\.meta$/) {
 3484:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3485:                   my $mresponse;
 3486:                   if ($remoteurl =~ m{/raw/}) {
 3487:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3488:                   } else {
 3489:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3490:                   }
 3491:                   if ($mresponse->is_error()) {
 3492: 		      unlink($filename.'.meta');
 3493:                       &logthis(
 3494:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3495:                   }
 3496: 	       }
 3497:                rename($transname,$filename);
 3498:                return 'ok';
 3499:            }
 3500:        }
 3501:     }
 3502: }
 3503: 
 3504: # ------------------------------------------------- Unsubscribe from a resource
 3505: 
 3506: sub unsubscribe {
 3507:     my ($fname) = @_;
 3508:     my $answer;
 3509:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3510:     $fname=~s/[\n\r]//g;
 3511:     my $author=$fname;
 3512:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3513:     my ($udom,$uname)=split(/\//,$author);
 3514:     my $home=homeserver($uname,$udom);
 3515:     if ($home eq 'no_host') {
 3516:         $answer = 'no_host';
 3517:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3518:         $answer = 'home';
 3519:     } else {
 3520:         my $defdom = $perlvar{'lonDefDomain'};
 3521:         if (&will_trust('content',$defdom,$udom)) {
 3522:             $answer = reply("unsub:$fname",$home);
 3523:         } else {
 3524:             $answer = 'untrusted';
 3525:         }
 3526:     }
 3527:     return $answer;
 3528: }
 3529: 
 3530: # ------------------------------------------------ Get server side include body
 3531: sub ssi_body {
 3532:     my ($filelink,%form)=@_;
 3533:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3534:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3535:     }
 3536:     my $output='';
 3537:     my $response;
 3538:     if ($filelink=~/^https?\:/) {
 3539:        ($output,$response)=&externalssi($filelink);
 3540:     } else {
 3541:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3542:        $filelink .= 'inhibitmenu=yes';
 3543:        ($output,$response)=&ssi($filelink,%form);
 3544:     }
 3545:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3546:     $output=~s/^.*?\<body[^\>]*\>//si;
 3547:     $output=~s/\<\/body\s*\>.*?$//si;
 3548:     if (wantarray) {
 3549:         return ($output, $response);
 3550:     } else {
 3551:         return $output;
 3552:     }
 3553: }
 3554: 
 3555: # --------------------------------------------------------- Server Side Include
 3556: 
 3557: sub absolute_url {
 3558:     my ($host_name,$unalias,$keep_proto) = @_;
 3559:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3560:     if ($host_name eq '') {
 3561: 	$host_name = $ENV{'SERVER_NAME'};
 3562:     }
 3563:     if ($unalias) {
 3564:         my $alias = &get_proxy_alias();
 3565:         if ($alias eq $host_name) {
 3566:             my $lonhost = $perlvar{'lonHostID'};
 3567:             my $hostname = &hostname($lonhost);
 3568:             my $lcproto; 
 3569:             if (($keep_proto) || ($hostname eq '')) {
 3570:                 $lcproto = $protocol;
 3571:             } else {
 3572:                 $lcproto = $protocol{$lonhost};
 3573:                 $lcproto = 'http' if ($lcproto ne 'https');
 3574:                 $lcproto .= '://';
 3575:             }
 3576:             unless ($hostname eq '') {
 3577:                 return $lcproto.$hostname;
 3578:             }
 3579:         }
 3580:     }
 3581:     return $protocol.$host_name;
 3582: }
 3583: 
 3584: #
 3585: #   Server side include.
 3586: # Parameters:
 3587: #  fn     Possibly encrypted resource name/id.
 3588: #  form   Hash that describes how the rendering should be done
 3589: #         and other things.
 3590: # Returns:
 3591: #   Scalar context: The content of the response.
 3592: #   Array context:  2 element list of the content and the full response object.
 3593: #     
 3594: sub ssi {
 3595: 
 3596:     my ($fn,%form)=@_;
 3597:     my ($host,$request,$response);
 3598:     $host = &absolute_url('',1);
 3599: 
 3600:     $form{'no_update_last_known'}=1;
 3601:     &Apache::lonenc::check_encrypt(\$fn);
 3602:     if (%form) {
 3603:       $request=new HTTP::Request('POST',$host.$fn);
 3604:       $request->content(join('&',map { 
 3605:             my $name = escape($_);
 3606:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3607:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3608:             : &escape($form{$_}) );    
 3609:         } keys(%form)));
 3610:     } else {
 3611:       $request=new HTTP::Request('GET',$host.$fn);
 3612:     }
 3613: 
 3614:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3615:     my $lonhost = $perlvar{'lonHostID'};
 3616:     my $islocal;
 3617:     if (($env{'request.course.id'}) &&
 3618:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3619:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3620:         ($form{'grade_symb'} ne '') &&
 3621:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3622:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3623:         $islocal = 1;
 3624:     }
 3625:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3626:                                              '','','',$islocal);
 3627: 
 3628:     if (wantarray) {
 3629: 	return ($response->content, $response);
 3630:     } else {
 3631: 	return $response->content;
 3632:     }
 3633: }
 3634: 
 3635: sub externalssi {
 3636:     my ($url)=@_;
 3637:     my $request=new HTTP::Request('GET',$url);
 3638:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3639:     if (wantarray) {
 3640:         return ($response->content, $response);
 3641:     } else {
 3642:         return $response->content;
 3643:     }
 3644: }
 3645: 
 3646: 
 3647: # If the local copy of a replicated resource is outdated, trigger a  
 3648: # connection from the homeserver to flush the delayed queue. If no update 
 3649: # happens, remove local copies of outdated resource (and corresponding
 3650: # metadata file).
 3651: 
 3652: sub remove_stale_resfile {
 3653:     my ($url) = @_;
 3654:     my $removed;
 3655:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3656:         my $audom = $1;
 3657:         my $auname = $2;
 3658:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3659:             my $homeserver = &homeserver($auname,$audom);
 3660:             unless (($homeserver eq 'no_host') ||
 3661:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3662:                 my $fname = &filelocation('',$url);
 3663:                 if (-e $fname) {
 3664:                     my $hostname = &hostname($homeserver);
 3665:                     if ($hostname) {
 3666:                         my $protocol = $protocol{$homeserver};
 3667:                         $protocol = 'http' if ($protocol ne 'https');
 3668:                         my $uri = &declutter($url);
 3669:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3670:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3671:                         if ($response->is_success()) {
 3672:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3673:                             my $locmodtime = (stat($fname))[9];
 3674:                             if ($locmodtime < $remmodtime) {
 3675:                                 my $stale;
 3676:                                 my $answer = &reply('pong',$homeserver);
 3677:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3678:                                     sleep(0.2);
 3679:                                     $locmodtime = (stat($fname))[9];
 3680:                                     if ($locmodtime < $remmodtime) {
 3681:                                         my $posstransfer = $fname.'.in.transfer';
 3682:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3683:                                             $removed = 1;
 3684:                                         } else {
 3685:                                             $stale = 1;
 3686:                                         }
 3687:                                     } else {
 3688:                                         $removed = 1;
 3689:                                     }
 3690:                                 } else {
 3691:                                     $stale = 1;
 3692:                                 }
 3693:                                 if ($stale) {
 3694:                                     if (unlink($fname)) {
 3695:                                         if ($uri!~/\.meta$/) {
 3696:                                             if (-e $fname.'.meta') {
 3697:                                                 unlink($fname.'.meta');
 3698:                                             }
 3699:                                         }
 3700:                                         my $unsubresult = &unsubscribe($fname);
 3701:                                         unless ($unsubresult eq 'ok') {
 3702:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3703:                                         }
 3704:                                         $removed = 1;
 3705:                                     }
 3706:                                 }
 3707:                             }
 3708:                         }
 3709:                     }
 3710:                 }
 3711:             }
 3712:         }
 3713:     }
 3714:     return $removed;
 3715: }
 3716: 
 3717: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3718: 
 3719: sub allowuploaded {
 3720:     my ($srcurl,$url)=@_;
 3721:     $url=&clutter(&declutter($url));
 3722:     my $dir=$url;
 3723:     $dir=~s/\/[^\/]+$//;
 3724:     my %httpref=();
 3725:     my $httpurl=&hreflocation('',$url);
 3726:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3727:     &Apache::lonnet::appenv(\%httpref);
 3728: }
 3729: 
 3730: #
 3731: # Determine if the current user should be able to edit a particular resource,
 3732: # when viewing in course context.
 3733: # (a) When viewing resource used to determine if "Edit" item is included in 
 3734: #     Functions.
 3735: # (b) When displaying folder contents in course editor, used to determine if
 3736: #     "Edit" link will be displayed alongside resource.
 3737: #
 3738: #  input: six args -- filename (decluttered), course number, course domain,
 3739: #                   url, symb (if registered) and group (if this is a group
 3740: #                   item -- e.g., bulletin board, group page etc.).
 3741: #  output: array of five scalars -- 
 3742: #          $cfile -- url for file editing if editable on current server
 3743: #          $home -- homeserver of resource (i.e., for author if published,
 3744: #                                           or course if uploaded.).
 3745: #          $switchserver --  1 if server switch will be needed.
 3746: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3747: #          $forceview -- 1 if icon/link should be to go to view mode
 3748: #
 3749: 
 3750: sub can_edit_resource {
 3751:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3752:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3753: #
 3754: # For aboutme pages user can only edit his/her own.
 3755: #
 3756:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3757:         my ($sdom,$sname) = ($1,$2);
 3758:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3759:             $home = $env{'user.home'};
 3760:             $cfile = $resurl;
 3761:             if ($env{'form.forceedit'}) {
 3762:                 $forceview = 1;
 3763:             } else {
 3764:                 $forceedit = 1;
 3765:             }
 3766:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3767:         } else {
 3768:             return;
 3769:         }
 3770:     }
 3771: 
 3772:     if ($env{'request.course.id'}) {
 3773:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3774:         if ($group ne '') {
 3775: # if this is a group homepage or group bulletin board, check group privs
 3776:             my $allowed = 0;
 3777:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3778:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3779:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3780:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3781:                     $allowed = 1;
 3782:                 }
 3783:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3784:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3785:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3786:                     $allowed = 1;
 3787:                 }
 3788:             }
 3789:             if ($allowed) {
 3790:                 $home=&homeserver($cnum,$cdom);
 3791:                 if ($env{'form.forceedit'}) {
 3792:                     $forceview = 1;
 3793:                 } else {
 3794:                     $forceedit = 1;
 3795:                 }
 3796:                 $cfile = $resurl;
 3797:             } else {
 3798:                 return;
 3799:             }
 3800:         } else {
 3801:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3802:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3803:                     return;
 3804:                 }
 3805:             } elsif (!$crsedit) {
 3806: #
 3807: # No edit allowed where CC has switched to student role.
 3808: #
 3809:                 return;
 3810:             }
 3811:         }
 3812:     }
 3813: 
 3814:     if ($file ne '') {
 3815:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3816:             if (&is_course_upload($file,$cnum,$cdom)) {
 3817:                 $uploaded = 1;
 3818:                 $incourse = 1;
 3819:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3820:                     $cfile = &hreflocation('',$file);
 3821:                     if ($env{'form.forceedit'}) {
 3822:                         $forceview = 1;
 3823:                     } else {
 3824:                         $forceedit = 1;
 3825:                     }
 3826:                 }
 3827:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3828:                 $incourse = 1;
 3829:                 if ($env{'form.forceedit'}) {
 3830:                     $forceview = 1;
 3831:                 } else {
 3832:                     $forceedit = 1;
 3833:                 }
 3834:                 $cfile = $resurl;
 3835:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3836:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3837:                     $incourse = 1;
 3838:                     if ($env{'form.forceedit'}) {
 3839:                         $forceview = 1;
 3840:                     } else {
 3841:                         $forceedit = 1;
 3842:                     }
 3843:                     $cfile = $resurl;
 3844:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3845:                     $incourse = 1;
 3846:                     $cfile = $resurl.'/smpedit';
 3847:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3848:                     $incourse = 1;
 3849:                     if ($env{'form.forceedit'}) {
 3850:                         $forceview = 1;
 3851:                     } else {
 3852:                         $forceedit = 1;
 3853:                     }
 3854:                     $cfile = $resurl;
 3855:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3856:                     my ($map,$id,$res) = &decode_symb($symb);
 3857:                     if ($map =~ /\.page$/) {
 3858:                         $incourse = 1;
 3859:                         if ($env{'form.forceedit'}) {
 3860:                             $forceview = 1;
 3861:                             $cfile = $map;
 3862:                         } else {
 3863:                             $forceedit = 1;
 3864:                             $cfile =  '/adm/wrapper'.$resurl;
 3865:                         }
 3866:                     }
 3867:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3868:                     $incourse = 1;
 3869:                     if ($env{'form.forceedit'}) {
 3870:                         $forceview = 1;
 3871:                     } else {
 3872:                         $forceedit = 1;
 3873:                     }
 3874:                     $cfile = $resurl;
 3875:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3876:                     $incourse = 1;
 3877:                     if ($env{'form.forceedit'}) {
 3878:                         $forceview = 1;
 3879:                     } else {
 3880:                         $forceedit = 1;
 3881:                     }
 3882:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3883:                 }
 3884:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3885:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3886:                 if (&is_on_map($template)) { 
 3887:                     $incourse = 1;
 3888:                     $forceview = 1;
 3889:                     $cfile = $template;
 3890:                 }
 3891:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3892:                 $incourse = 1;
 3893:                 if ($env{'form.forceedit'}) {
 3894:                     $forceview = 1;
 3895:                 } else {
 3896:                     $forceedit = 1;
 3897:                 }
 3898:                 $cfile = $resurl;
 3899:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3900:                 $incourse = 1;
 3901:                 if ($env{'form.forceedit'}) {
 3902:                     $forceview = 1;
 3903:                 } else {
 3904:                     $forceedit = 1;
 3905:                 }
 3906:                 $cfile = $resurl;
 3907:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3908:                 $incourse = 1;
 3909:                 $forceview = 1;
 3910:                 if ($symb) {
 3911:                     my ($map,$id,$res)=&decode_symb($symb);
 3912:                     $env{'request.symb'} = $symb;
 3913:                     $cfile = &clutter($res);
 3914:                 } else {
 3915:                     $cfile = $env{'form.suppurl'};
 3916:                     my $escfile = &unescape($cfile);
 3917:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3918:                         $cfile = '/adm/wrapper'.$escfile;
 3919:                     } else {
 3920:                         $escfile =~ s{^http://}{};
 3921:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3922:                     }
 3923:                 }
 3924:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3925:                 if ($env{'form.forceedit'}) {
 3926:                     $forceview = 1;
 3927:                 } else {
 3928:                     $forceedit = 1;
 3929:                 }
 3930:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3931:             }
 3932:         }
 3933:         if ($uploaded || $incourse) {
 3934:             $home=&homeserver($cnum,$cdom);
 3935:         } elsif ($file !~ m{/$}) {
 3936:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3937:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3938:             # Check that the user has permission to edit this resource
 3939:             my $setpriv = 1;
 3940:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3941:             if (defined($cfudom)) {
 3942:                 $home=&homeserver($cfuname,$cfudom);
 3943:                 $cfile=$file;
 3944:             }
 3945:         }
 3946:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3947:             (($home ne '') && ($home ne 'no_host'))) {
 3948:             my @ids=&current_machine_ids();
 3949:             unless (grep(/^\Q$home\E$/,@ids)) {
 3950:                 $switchserver=1;
 3951:             }
 3952:         }
 3953:     }
 3954:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3955: }
 3956: 
 3957: sub is_course_upload {
 3958:     my ($file,$cnum,$cdom) = @_;
 3959:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3960:     $uploadpath =~ s{^\/}{};
 3961:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3962:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3963:         return 1;
 3964:     }
 3965:     return;
 3966: }
 3967: 
 3968: sub in_course {
 3969:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3970:     if ($hideprivileged) {
 3971:         my $skipuser;
 3972:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3973:         my @possdoms = ($cdom);  
 3974:         if ($coursehash{'checkforpriv'}) { 
 3975:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3976:         }
 3977:         if (&privileged($uname,$udom,\@possdoms)) {
 3978:             $skipuser = 1;
 3979:             if ($coursehash{'nothideprivileged'}) {
 3980:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3981:                     my $user;
 3982:                     if ($item =~ /:/) {
 3983:                         $user = $item;
 3984:                     } else {
 3985:                         $user = join(':',split(/[\@]/,$item));
 3986:                     }
 3987:                     if ($user eq $uname.':'.$udom) {
 3988:                         undef($skipuser);
 3989:                         last;
 3990:                     }
 3991:                 }
 3992:             }
 3993:             if ($skipuser) {
 3994:                 return 0;
 3995:             }
 3996:         }
 3997:     }
 3998:     $type ||= 'any';
 3999:     if (!defined($cdom) || !defined($cnum)) {
 4000:         my $cid  = $env{'request.course.id'};
 4001:         $cdom = $env{'course.'.$cid.'.domain'};
 4002:         $cnum = $env{'course.'.$cid.'.num'};
 4003:     }
 4004:     my $typesref;
 4005:     if (($type eq 'any') || ($type eq 'all')) {
 4006:         $typesref = ['active','previous','future'];
 4007:     } elsif ($type eq 'previous' || $type eq 'future') {
 4008:         $typesref = [$type];
 4009:     }
 4010:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4011:                               $typesref,undef,[$cdom]);
 4012:     my ($tmp) = keys(%roles);
 4013:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4014:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4015:     if (@course_roles > 0) {
 4016:         return 1;
 4017:     }
 4018:     return 0;
 4019: }
 4020: 
 4021: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4022: # input: action, courseID, current domain, intended
 4023: #        path to file, source of file, instruction to parse file for objects,
 4024: #        ref to hash for embedded objects,
 4025: #        ref to hash for codebase of java objects.
 4026: #        reference to scalar to accommodate mime type determined
 4027: #          from File::MMagic if $parser = parse.
 4028: #
 4029: # output: url to file (if action was uploaddoc), 
 4030: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4031: #
 4032: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4033: # course.
 4034: #
 4035: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4036: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4037: #          course's home server.
 4038: #
 4039: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4040: #          be copied from $source (current location) to 
 4041: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4042: #         and will then be copied to
 4043: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4044: #         course's home server.
 4045: #
 4046: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4047: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4048: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4049: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4050: #         in course's home server.
 4051: #
 4052: 
 4053: sub process_coursefile {
 4054:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4055:         $mimetype)=@_;
 4056:     my $fetchresult;
 4057:     my $home=&homeserver($docuname,$docudom);
 4058:     if ($action eq 'propagate') {
 4059:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4060: 			     $home);
 4061:     } else {
 4062:         my $fpath = '';
 4063:         my $fname = $file;
 4064:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4065:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4066:         my $filepath = &build_filepath($fpath);
 4067:         if ($action eq 'copy') {
 4068:             if ($source eq '') {
 4069:                 $fetchresult = 'no source file';
 4070:                 return $fetchresult;
 4071:             } else {
 4072:                 my $destination = $filepath.'/'.$fname;
 4073:                 rename($source,$destination);
 4074:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4075:                                  $home);
 4076:             }
 4077:         } elsif ($action eq 'uploaddoc') {
 4078:             open(my $fh,'>',$filepath.'/'.$fname);
 4079:             print $fh $env{'form.'.$source};
 4080:             close($fh);
 4081:             if ($parser eq 'parse') {
 4082:                 my $mm = new File::MMagic;
 4083:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4084:                 if ($type eq 'text/html') {
 4085:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4086:                     unless ($parse_result eq 'ok') {
 4087:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4088:                     }
 4089:                 }
 4090:                 if (ref($mimetype)) {
 4091:                     $$mimetype = $type;
 4092:                 } 
 4093:             }
 4094:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4095:                                  $home);
 4096:             if ($fetchresult eq 'ok') {
 4097:                 return '/uploaded/'.$fpath.'/'.$fname;
 4098:             } else {
 4099:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4100:                         ' to host '.$home.': '.$fetchresult);
 4101:                 return '/adm/notfound.html';
 4102:             }
 4103:         }
 4104:     }
 4105:     unless ( $fetchresult eq 'ok') {
 4106:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4107:              ' to host '.$home.': '.$fetchresult);
 4108:     }
 4109:     return $fetchresult;
 4110: }
 4111: 
 4112: sub build_filepath {
 4113:     my ($fpath) = @_;
 4114:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4115:     unless ($fpath eq '') {
 4116:         my @parts=split('/',$fpath);
 4117:         foreach my $part (@parts) {
 4118:             $filepath.= '/'.$part;
 4119:             if ((-e $filepath)!=1) {
 4120:                 mkdir($filepath,0777);
 4121:             }
 4122:         }
 4123:     }
 4124:     return $filepath;
 4125: }
 4126: 
 4127: sub store_edited_file {
 4128:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4129:     my $file = $primary_url;
 4130:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4131:     my $fpath = '';
 4132:     my $fname = $file;
 4133:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4134:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4135:     my $filepath = &build_filepath($fpath);
 4136:     open(my $fh,'>',$filepath.'/'.$fname);
 4137:     print $fh $content;
 4138:     close($fh);
 4139:     my $home=&homeserver($docuname,$docudom);
 4140:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4141: 			  $home);
 4142:     if ($$fetchresult eq 'ok') {
 4143:         return '/uploaded/'.$fpath.'/'.$fname;
 4144:     } else {
 4145:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4146: 		 ' to host '.$home.': '.$$fetchresult);
 4147:         return '/adm/notfound.html';
 4148:     }
 4149: }
 4150: 
 4151: sub clean_filename {
 4152:     my ($fname,$args)=@_;
 4153: # Replace Windows backslashes by forward slashes
 4154:     $fname=~s/\\/\//g;
 4155:     if (!$args->{'keep_path'}) {
 4156:         # Get rid of everything but the actual filename
 4157: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4158:     }
 4159: # Replace spaces by underscores
 4160:     $fname=~s/\s+/\_/g;
 4161: # Transliterate non-ascii text to ascii
 4162:     my $lang = &Apache::lonlocal::current_language();
 4163:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4164: # Replace all other weird characters by nothing
 4165:     $fname=~s{[^/\w\.\-]}{}g;
 4166: # Replace all .\d. sequences with _\d. so they no longer look like version
 4167: # numbers
 4168:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4169: # Replace three or more adjacent underscores with one for consistency 
 4170: # with loncfile::filename_check() so complete url can be extracted by
 4171: # lonnet::decode_symb()
 4172:     $fname=~s/_{3,}/_/g;
 4173:     return $fname;
 4174: }
 4175: 
 4176: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4177: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4178: # image with the same aspect ratio as the original, but with dimensions which do 
 4179: # not exceed $resizewidth and $resizeheight.
 4180:  
 4181: sub resizeImage {
 4182:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4183:     my $ima = Image::Magick->new;
 4184:     my $resized;
 4185:     if (-e $img_path) {
 4186:         $ima->Read($img_path);
 4187:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4188:             my $width = $ima->Get('width');
 4189:             my $height = $ima->Get('height');
 4190:             if ($width > $resizewidth) {
 4191: 	        my $factor = $width/$resizewidth;
 4192:                 my $newheight = $height/$factor;
 4193:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4194:                 $resized = 1;
 4195:             }
 4196:         }
 4197:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4198:             my $width = $ima->Get('width');
 4199:             my $height = $ima->Get('height');
 4200:             if ($height > $resizeheight) {
 4201:                 my $factor = $height/$resizeheight;
 4202:                 my $newwidth = $width/$factor;
 4203:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4204:                 $resized = 1;
 4205:             }
 4206:         }
 4207:         if ($resized) {
 4208:             $ima->Write($img_path);
 4209:         }
 4210:     }
 4211:     return;
 4212: }
 4213: 
 4214: # --------------- Take an uploaded file and put it into the userfiles directory
 4215: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4216: #                    the desired filename is in $env{"form.$formname.filename"}
 4217: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4218: #                                    canceloverwrite, scantron or ''.
 4219: #                   if 'coursedoc': upload to the current course
 4220: #                   if 'existingfile': write file to tmp/overwrites directory 
 4221: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4222: #                   $context is passed as argument to &finishuserfileupload
 4223: #        $subdir - directory in userfile to store the file into
 4224: #        $parser - instruction to parse file for objects ($parser = parse) or
 4225: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4226: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4227: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4228: #        $allfiles - reference to hash for embedded objects
 4229: #        $codebase - reference to hash for codebase of java objects
 4230: #        $desuname - username for permanent storage of uploaded file
 4231: #        $dsetudom - domain for permanaent storage of uploaded file
 4232: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4233: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4234: #        $resizewidth - width (pixels) to which to resize uploaded image
 4235: #        $resizeheight - height (pixels) to which to resize uploaded image
 4236: #        $mimetype - reference to scalar to accommodate mime type determined
 4237: #                    from File::MMagic.
 4238: # 
 4239: # output: url of file in userspace, or error: <message> 
 4240: #             or /adm/notfound.html if failure to upload occurse
 4241: 
 4242: sub userfileupload {
 4243:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4244:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4245:     if (!defined($subdir)) { $subdir='unknown'; }
 4246:     my $fname=$env{'form.'.$formname.'.filename'};
 4247:     $fname=&clean_filename($fname);
 4248:     # See if there is anything left
 4249:     unless ($fname) { return 'error: no uploaded file'; }
 4250:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4251:     if ($fname =~ /^\./) {
 4252:         my ($s,$usec) = &gettimeofday();
 4253:         while (length($usec) < 6) {
 4254:             $usec = '0'.$usec;
 4255:         }
 4256:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4257:     }
 4258:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4259:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4260:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4261:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4262:         my $now = time;
 4263:         my $filepath;
 4264:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4265:              $filepath = 'tmp/helprequests/'.$now;
 4266:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4267:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4268:                          '_'.$env{'user.domain'}.'/pending';
 4269:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4270:             my ($docuname,$docudom);
 4271:             if ($destudom =~ /^$match_domain$/) {
 4272:                 $docudom = $destudom;
 4273:             } else {
 4274:                 $docudom = $env{'user.domain'};
 4275:             }
 4276:             if ($destuname =~ /^$match_username$/) {
 4277:                 $docuname = $destuname;
 4278:             } else {
 4279:                 $docuname = $env{'user.name'};
 4280:             }
 4281:             if (exists($env{'form.group'})) {
 4282:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4283:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4284:             }
 4285:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4286:             if ($context eq 'canceloverwrite') {
 4287:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4288:                 if (-e  $tempfile) {
 4289:                     my @info = stat($tempfile);
 4290:                     if ($info[9] eq $env{'form.timestamp'}) {
 4291:                         unlink($tempfile);
 4292:                     }
 4293:                 }
 4294:                 return;
 4295:             }
 4296:         }
 4297:         # Create the directory if not present
 4298:         my @parts=split(/\//,$filepath);
 4299:         my $fullpath = $perlvar{'lonDaemons'};
 4300:         for (my $i=0;$i<@parts;$i++) {
 4301:             $fullpath .= '/'.$parts[$i];
 4302:             if ((-e $fullpath)!=1) {
 4303:                 mkdir($fullpath,0777);
 4304:             }
 4305:         }
 4306:         open(my $fh,'>',$fullpath.'/'.$fname);
 4307:         print $fh $env{'form.'.$formname};
 4308:         close($fh);
 4309:         if ($context eq 'existingfile') {
 4310:             my @info = stat($fullpath.'/'.$fname);
 4311:             return ($fullpath.'/'.$fname,$info[9]);
 4312:         } else {
 4313:             return $fullpath.'/'.$fname;
 4314:         }
 4315:     }
 4316:     if ($subdir eq 'scantron') {
 4317:         $fname = 'scantron_orig_'.$fname;
 4318:     } else {
 4319:         $fname="$subdir/$fname";
 4320:     }
 4321:     if ($context eq 'coursedoc') {
 4322: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4323: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4324:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4325:             return &finishuserfileupload($docuname,$docudom,
 4326: 					 $formname,$fname,$parser,$allfiles,
 4327: 					 $codebase,$thumbwidth,$thumbheight,
 4328:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4329:         } else {
 4330:             if ($env{'form.folder'}) {
 4331:                 $fname=$env{'form.folder'}.'/'.$fname;
 4332:             }
 4333:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4334: 				       $fname,$formname,$parser,
 4335: 				       $allfiles,$codebase,$mimetype);
 4336:         }
 4337:     } elsif (defined($destuname)) {
 4338:         my $docuname=$destuname;
 4339:         my $docudom=$destudom;
 4340: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4341: 				     $parser,$allfiles,$codebase,
 4342:                                      $thumbwidth,$thumbheight,
 4343:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4344:     } else {
 4345:         my $docuname=$env{'user.name'};
 4346:         my $docudom=$env{'user.domain'};
 4347:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4348:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4349:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4350:         }
 4351: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4352: 				     $parser,$allfiles,$codebase,
 4353:                                      $thumbwidth,$thumbheight,
 4354:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4355:     }
 4356: }
 4357: 
 4358: sub finishuserfileupload {
 4359:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4360:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4361:     my $path=$docudom.'/'.$docuname.'/';
 4362:     my $filepath=$perlvar{'lonDocRoot'};
 4363:   
 4364:     my ($fnamepath,$file,$fetchthumb);
 4365:     $file=$fname;
 4366:     if ($fname=~m|/|) {
 4367:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4368: 	$path.=$fnamepath.'/';
 4369:     }
 4370:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4371:     my $count;
 4372:     for ($count=4;$count<=$#parts;$count++) {
 4373:         $filepath.="/$parts[$count]";
 4374:         if ((-e $filepath)!=1) {
 4375: 	    mkdir($filepath,0777);
 4376:         }
 4377:     }
 4378: 
 4379: # Save the file
 4380:     {
 4381: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4382: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4383: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4384: 	    return '/adm/notfound.html';
 4385: 	}
 4386:         if ($context eq 'overwrite') {
 4387:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4388:             my $target = $filepath.'/'.$file;
 4389:             if (-e $source) {
 4390:                 my @info = stat($source);
 4391:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4392:                     unless (&File::Copy::move($source,$target)) {
 4393:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4394:                         return "Moving from $source failed";
 4395:                     }
 4396:                 } else {
 4397:                     return "Temporary file: $source had unexpected date/time for last modification";
 4398:                 }
 4399:             } else {
 4400:                 return "Temporary file: $source missing";
 4401:             }
 4402:         } elsif (!print FH ($env{'form.'.$formname})) {
 4403: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4404: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4405: 	    return '/adm/notfound.html';
 4406: 	}
 4407: 	close(FH);
 4408:         if ($resizewidth && $resizeheight) {
 4409:             my $mm = new File::MMagic;
 4410:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4411:             if ($mime_type =~ m{^image/}) {
 4412: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4413:             }  
 4414: 	}
 4415:     }
 4416:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4417:         if (ref($mimetype)) {
 4418:             if ($$mimetype eq '') {
 4419:                 my $mm = new File::MMagic;
 4420:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4421:                 $$mimetype = $type;
 4422:             }
 4423:         }
 4424:     }
 4425:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4426:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4427:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4428:                                                        $allfiles,$codebase);
 4429:             unless ($parse_result eq 'ok') {
 4430:                 &logthis('Failed to parse '.$filepath.$file.
 4431: 	   	         ' for embedded media: '.$parse_result); 
 4432:             }
 4433:         }
 4434:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4435:         my $format = $env{'form.scantron_format'};
 4436:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4437:     }
 4438:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4439:         my $input = $filepath.'/'.$file;
 4440:         my $output = $filepath.'/'.'tn-'.$file;
 4441:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4442:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4443:         system({$args[0]} @args);
 4444:         if (-e $filepath.'/'.'tn-'.$file) {
 4445:             $fetchthumb  = 1; 
 4446:         }
 4447:     }
 4448:  
 4449: # Notify homeserver to grep it
 4450: #
 4451:     my $docuhome=&homeserver($docuname,$docudom);	
 4452:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4453:     if ($fetchresult eq 'ok') {
 4454:         if ($fetchthumb) {
 4455:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4456:             if ($thumbresult ne 'ok') {
 4457:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4458:                          $docuhome.': '.$thumbresult);
 4459:             }
 4460:         }
 4461: #
 4462: # Return the URL to it
 4463:         return '/uploaded/'.$path.$file;
 4464:     } else {
 4465:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4466: 		 ': '.$fetchresult);
 4467:         return '/adm/notfound.html';
 4468:     }
 4469: }
 4470: 
 4471: sub extract_embedded_items {
 4472:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4473:     my @state = ();
 4474:     my (%lastids,%related,%shockwave,%flashvars);
 4475:     my %javafiles = (
 4476:                       codebase => '',
 4477:                       code => '',
 4478:                       archive => ''
 4479:                     );
 4480:     my %mediafiles = (
 4481:                       src => '',
 4482:                       movie => '',
 4483:                      );
 4484:     my $p;
 4485:     if ($content) {
 4486:         $p = HTML::LCParser->new($content);
 4487:     } else {
 4488:         $p = HTML::LCParser->new($fullpath);
 4489:     }
 4490:     while (my $t=$p->get_token()) {
 4491: 	if ($t->[0] eq 'S') {
 4492: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4493: 	    push(@state, $tagname);
 4494:             if (lc($tagname) eq 'allow') {
 4495:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4496:             }
 4497: 	    if (lc($tagname) eq 'img') {
 4498: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4499: 	    }
 4500: 	    if (lc($tagname) eq 'a') {
 4501:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4502:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4503:                 }
 4504: 	    }
 4505:             if (lc($tagname) eq 'script') {
 4506:                 my $src;
 4507:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4508:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4509:                 } else {
 4510:                     if ($attr->{'src'} ne '') {
 4511:                         $src = $attr->{'src'};
 4512:                         &add_filetype($allfiles,$src,'src');
 4513:                     }
 4514:                 }
 4515:                 my $text = $p->get_trimmed_text();
 4516:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4517:                     my @swfargs = split(/,/,$1);
 4518:                     foreach my $item (@swfargs) {
 4519:                         $item =~ s/["']//g;
 4520:                         $item =~ s/^\s+//;
 4521:                         $item =~ s/\s+$//;
 4522:                     }
 4523:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4524:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4525:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4526:                         } else {
 4527:                             $related{$swfargs[0]} = [$swfargs[2]];
 4528:                         }
 4529:                     }
 4530:                 }
 4531:             }
 4532:             if (lc($tagname) eq 'link') {
 4533:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4534:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4535:                 }
 4536:             }
 4537: 	    if (lc($tagname) eq 'object' ||
 4538: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4539: 		foreach my $item (keys(%javafiles)) {
 4540: 		    $javafiles{$item} = '';
 4541: 		}
 4542:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4543:                     $lastids{lc($tagname)} = $attr->{'id'};
 4544:                 }
 4545: 	    }
 4546: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4547: 		my $name = lc($attr->{'name'});
 4548: 		foreach my $item (keys(%javafiles)) {
 4549: 		    if ($name eq $item) {
 4550: 			$javafiles{$item} = $attr->{'value'};
 4551: 			last;
 4552: 		    }
 4553: 		}
 4554:                 my $pathfrom;
 4555: 		foreach my $item (keys(%mediafiles)) {
 4556: 		    if ($name eq $item) {
 4557:                         $pathfrom = $attr->{'value'};
 4558:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4559: 			&add_filetype($allfiles,$pathfrom,$name);
 4560: 			last;
 4561: 		    }
 4562: 		}
 4563:                 if ($name eq 'flashvars') {
 4564:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4565:                 }
 4566:                 if ($pathfrom ne '') {
 4567:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4568:                                          $pathfrom);
 4569:                 }
 4570: 	    }
 4571: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4572: 		foreach my $item (keys(%javafiles)) {
 4573: 		    if ($attr->{$item}) {
 4574: 			$javafiles{$item} = $attr->{$item};
 4575: 			last;
 4576: 		    }
 4577: 		}
 4578: 		foreach my $item (keys(%mediafiles)) {
 4579: 		    if ($attr->{$item}) {
 4580: 			&add_filetype($allfiles,$attr->{$item},$item);
 4581: 			last;
 4582: 		    }
 4583: 		}
 4584:                 if (lc($tagname) eq 'embed') {
 4585:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4586:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4587:                                              $attr->{'src'});
 4588:                     }
 4589:                 }
 4590: 	    }
 4591:             if (lc($tagname) eq 'iframe') {
 4592:                 my $src = $attr->{'src'} ;
 4593:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4594:                     &add_filetype($allfiles,$src,'src');
 4595:                 } elsif ($src =~ m{^/}) {
 4596:                     if ($env{'request.course.id'}) {
 4597:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4598:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4599:                         my $url = &hreflocation('',$fullpath);
 4600:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4601:                             my $relpath = $1;
 4602:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4603:                                 &add_filetype($allfiles,$1,'src');
 4604:                             }
 4605:                         }
 4606:                     }
 4607:                 }
 4608:             }
 4609:             if ($t->[4] =~ m{/>$}) {
 4610:                 pop(@state);
 4611:             }
 4612: 	} elsif ($t->[0] eq 'E') {
 4613: 	    my ($tagname) = ($t->[1]);
 4614: 	    if ($javafiles{'codebase'} ne '') {
 4615: 		$javafiles{'codebase'} .= '/';
 4616: 	    }  
 4617: 	    if (lc($tagname) eq 'applet' ||
 4618: 		lc($tagname) eq 'object' ||
 4619: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4620: 		) {
 4621: 		foreach my $item (keys(%javafiles)) {
 4622: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4623: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4624: 			&add_filetype($allfiles,$file,$item);
 4625: 		    }
 4626: 		}
 4627: 	    } 
 4628: 	    pop @state;
 4629: 	}
 4630:     }
 4631:     foreach my $id (sort(keys(%flashvars))) {
 4632:         if ($shockwave{$id} ne '') {
 4633:             my @pairs = split(/\&/,$flashvars{$id});
 4634:             foreach my $pair (@pairs) {
 4635:                 my ($key,$value) = split(/\=/,$pair);
 4636:                 if ($key eq 'thumb') {
 4637:                     &add_filetype($allfiles,$value,$key);
 4638:                 } elsif ($key eq 'content') {
 4639:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4640:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4641:                     if ($ext ne '') {
 4642:                         &add_filetype($allfiles,$path.$value,$ext);
 4643:                     }
 4644:                 }
 4645:             }
 4646:         }
 4647:     }
 4648:     return 'ok';
 4649: }
 4650: 
 4651: sub add_filetype {
 4652:     my ($allfiles,$file,$type)=@_;
 4653:     if (exists($allfiles->{$file})) {
 4654: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4655: 	    push(@{$allfiles->{$file}}, &escape($type));
 4656: 	}
 4657:     } else {
 4658: 	@{$allfiles->{$file}} = (&escape($type));
 4659:     }
 4660: }
 4661: 
 4662: sub embedded_dependency {
 4663:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4664:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4665:         if (($identifier ne '') &&
 4666:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4667:             ($pathfrom ne '')) {
 4668:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4669:             foreach my $dep (@{$related->{$identifier}}) {
 4670:                 &add_filetype($allfiles,$path.$dep,'object');
 4671:             }
 4672:         }
 4673:     }
 4674:     return;
 4675: }
 4676: 
 4677: sub bubblesheet_converter {
 4678:     my ($cdom,$fullpath,$config,$format) = @_;
 4679:     if ((&domain($cdom) ne '') &&
 4680:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4681:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4682:         my (%csvcols,%csvoptions);
 4683:         if (ref($config->{'fields'}) eq 'HASH') {  
 4684:             %csvcols = %{$config->{'fields'}};
 4685:         }
 4686:         if (ref($config->{'options'}) eq 'HASH') {
 4687:             %csvoptions = %{$config->{'options'}};
 4688:         }
 4689:         my %csvbynum = reverse(%csvcols);
 4690:         my %scantronconf = &get_scantron_config($format,$cdom);
 4691:         if (keys(%scantronconf)) {
 4692:             my %bynum = (
 4693:                           $scantronconf{CODEstart} => 'CODEstart',
 4694:                           $scantronconf{IDstart}   => 'IDstart',
 4695:                           $scantronconf{PaperID}   => 'PaperID',
 4696:                           $scantronconf{FirstName} => 'FirstName',
 4697:                           $scantronconf{LastName}  => 'LastName',
 4698:                           $scantronconf{Qstart}    => 'Qstart',
 4699:                         );
 4700:             my @ordered;
 4701:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4702:                 push(@ordered,$bynum{$item});
 4703:             }
 4704:             my %mapstart = (
 4705:                               CODEstart => 'CODE',
 4706:                               IDstart   => 'ID',
 4707:                               PaperID   => 'PaperID',
 4708:                               FirstName => 'FirstName',
 4709:                               LastName  => 'LastName',
 4710:                               Qstart    => 'FirstQuestion',
 4711:                            );
 4712:             my %maplength = (
 4713:                               CODEstart => 'CODElength',
 4714:                               IDstart   => 'IDlength',
 4715:                               PaperID   => 'PaperIDlength',
 4716:                               FirstName => 'FirstNamelength',
 4717:                               LastName  => 'LastNamelength',
 4718:             );
 4719:             if (open(my $fh,'<',$fullpath)) {
 4720:                 my $output;
 4721:                 my %lettdig = &letter_to_digits();
 4722:                 my %diglett = reverse(%lettdig);
 4723:                 my $numletts = scalar(keys(%lettdig));
 4724:                 my $num = 0;
 4725:                 while (my $line=<$fh>) {
 4726:                     $num ++;
 4727:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4728:                     $line =~ s{[\r\n]+$}{};
 4729:                     my %found;
 4730:                     my @values = split(/,/,$line,-1);
 4731:                     my ($qstart,$record);
 4732:                     for (my $i=0; $i<@values; $i++) {
 4733:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4734:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4735:                             if ($values[$i] eq '') {
 4736:                                 $values[$i] = $scantronconf{'Qoff'};
 4737:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4738:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4739:                                     $values[$i] = $lettdig{uc($values[$i])};
 4740:                                 }
 4741:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4742:                                 if ($values[$i] =~ /^[0-9]$/) {
 4743:                                     $values[$i] = $diglett{$values[$i]};
 4744:                                 }
 4745:                             } else {
 4746:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4747:                                     my $digit;
 4748:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4749:                                         $digit = $lettdig{uc($values[$i])}-1;
 4750:                                         if ($values[$i] eq 'J') {
 4751:                                             $digit += $numletts;
 4752:                                         }
 4753:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4754:                                         $digit = $values[$i]-1;
 4755:                                         if ($values[$i] eq '0') {
 4756:                                             $digit += $numletts;
 4757:                                         }
 4758:                                     }
 4759:                                     my $qval='';
 4760:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4761:                                         if ($j == $digit) {
 4762:                                             $qval .= $scantronconf{'Qon'};
 4763:                                         } else {
 4764:                                             $qval .= $scantronconf{'Qoff'};
 4765:                                         }
 4766:                                     }
 4767:                                     $values[$i] = $qval;
 4768:                                 }
 4769:                             }
 4770:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4771:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4772:                             }
 4773:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4774:                             if ($numblank > 0) {
 4775:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4776:                             }
 4777:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4778:                                 $qstart = $i;
 4779:                                 $found{$csvbynum{$i}} = $values[$i];
 4780:                             } else {
 4781:                                 $found{'FirstQuestion'} .= $values[$i];
 4782:                             }
 4783:                         } elsif (exists($csvbynum{$i})) {
 4784:                             if ($csvoptions{'rem'}) {
 4785:                                 $values[$i] =~ s/^\s+//;
 4786:                             }
 4787:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4788:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4789:                                     $values[$i] = '0'.$values[$i];
 4790:                                 }
 4791:                             }
 4792:                             $found{$csvbynum{$i}} = $values[$i];
 4793:                         }
 4794:                     }
 4795:                     foreach my $item (@ordered) {
 4796:                         my $currlength = 1+length($record);
 4797:                         my $numspaces = $scantronconf{$item} - $currlength;
 4798:                         if ($numspaces > 0) {
 4799:                             $record .= (' ' x $numspaces);
 4800:                         }
 4801:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4802:                             unless ($item eq 'Qstart') {
 4803:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4804:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4805:                                 }
 4806:                             }
 4807:                             $record .= $found{$mapstart{$item}};
 4808:                         }
 4809:                     }
 4810:                     $output .= "$record\n";
 4811:                 }
 4812:                 close($fh);
 4813:                 if ($output) {
 4814:                     if (open(my $fh,'>',$fullpath)) {
 4815:                         print $fh $output;
 4816:                         close($fh);
 4817:                     }
 4818:                 }
 4819:             }
 4820:         }
 4821:         return;
 4822:     }
 4823: }
 4824: 
 4825: sub letter_to_digits {
 4826:     my %lettdig = (
 4827:                     A => 1,
 4828:                     B => 2,
 4829:                     C => 3,
 4830:                     D => 4,
 4831:                     E => 5,
 4832:                     F => 6,
 4833:                     G => 7,
 4834:                     H => 8,
 4835:                     I => 9,
 4836:                     J => 0,
 4837:                   );
 4838:     return %lettdig;
 4839: }
 4840: 
 4841: sub get_scantron_config {
 4842:     my ($which,$cdom) = @_;
 4843:     my @lines = &get_scantronformat_file($cdom);
 4844:     my %config;
 4845:     #FIXME probably should move to XML it has already gotten a bit much now
 4846:     foreach my $line (@lines) {
 4847:         my ($name,$descrip)=split(/:/,$line);
 4848:         if ($name ne $which ) { next; }
 4849:         chomp($line);
 4850:         my @config=split(/:/,$line);
 4851:         $config{'name'}=$config[0];
 4852:         $config{'description'}=$config[1];
 4853:         $config{'CODElocation'}=$config[2];
 4854:         $config{'CODEstart'}=$config[3];
 4855:         $config{'CODElength'}=$config[4];
 4856:         $config{'IDstart'}=$config[5];
 4857:         $config{'IDlength'}=$config[6];
 4858:         $config{'Qstart'}=$config[7];
 4859:         $config{'Qlength'}=$config[8];
 4860:         $config{'Qoff'}=$config[9];
 4861:         $config{'Qon'}=$config[10];
 4862:         $config{'PaperID'}=$config[11];
 4863:         $config{'PaperIDlength'}=$config[12];
 4864:         $config{'FirstName'}=$config[13];
 4865:         $config{'FirstNamelength'}=$config[14];
 4866:         $config{'LastName'}=$config[15];
 4867:         $config{'LastNamelength'}=$config[16];
 4868:         $config{'BubblesPerRow'}=$config[17];
 4869:         last;
 4870:     }
 4871:     return %config;
 4872: }
 4873: 
 4874: sub get_scantronformat_file {
 4875:     my ($cdom) = @_;
 4876:     if ($cdom eq '') {
 4877:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4878:     }
 4879:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4880:     my $gottab = 0;
 4881:     my @lines;
 4882:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4883:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4884:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4885:             if ($formatfile ne '-1') {
 4886:                 @lines = split("\n",$formatfile,-1);
 4887:                 $gottab = 1;
 4888:             }
 4889:         }
 4890:     }
 4891:     if (!$gottab) {
 4892:         my $confname = $cdom.'-domainconfig';
 4893:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4894:         my $formatfile = &getfile($default);
 4895:         if ($formatfile ne '-1') {
 4896:             @lines = split("\n",$formatfile,-1);
 4897:             $gottab = 1;
 4898:         }
 4899:     }
 4900:     if (!$gottab) {
 4901:         my @domains = &current_machine_domains();
 4902:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4903:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4904:                 @lines = <$fh>;
 4905:                 close($fh);
 4906:             }
 4907:         } else {
 4908:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4909:                 @lines = <$fh>;
 4910:                 close($fh);
 4911:             }
 4912:         }
 4913:     }
 4914:     return @lines;
 4915: }
 4916: 
 4917: sub removeuploadedurl {
 4918:     my ($url)=@_;	
 4919:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4920:     return &removeuserfile($uname,$udom,$fname);
 4921: }
 4922: 
 4923: sub removeuserfile {
 4924:     my ($docuname,$docudom,$fname)=@_;
 4925:     my $home=&homeserver($docuname,$docudom);    
 4926:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4927:     if ($result eq 'ok') {	
 4928:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4929:             my $metafile = $fname.'.meta';
 4930:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4931: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4932:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4933:             my $sqlresult = 
 4934:                 &update_portfolio_table($docuname,$docudom,$file,
 4935:                                         'portfolio_metadata',$group,
 4936:                                         'delete');
 4937:         }
 4938:     }
 4939:     return $result;
 4940: }
 4941: 
 4942: sub mkdiruserfile {
 4943:     my ($docuname,$docudom,$dir)=@_;
 4944:     my $home=&homeserver($docuname,$docudom);
 4945:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4946: }
 4947: 
 4948: sub renameuserfile {
 4949:     my ($docuname,$docudom,$old,$new)=@_;
 4950:     my $home=&homeserver($docuname,$docudom);
 4951:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4952:                         &escape("$old").':'.&escape("$new"),$home);
 4953:     if ($result eq 'ok') {
 4954:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4955:             my $oldmeta = $old.'.meta';
 4956:             my $newmeta = $new.'.meta';
 4957:             my $metaresult = 
 4958:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4959: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4960:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4961:             my $sqlresult = 
 4962:                 &update_portfolio_table($docuname,$docudom,$file,
 4963:                                         'portfolio_metadata',$group,
 4964:                                         'delete');
 4965:         }
 4966:     }
 4967:     return $result;
 4968: }
 4969: 
 4970: # ------------------------------------------------------------------------- Log
 4971: 
 4972: sub log {
 4973:     my ($dom,$nam,$hom,$what)=@_;
 4974:     return critical("log:$dom:$nam:$what",$hom);
 4975: }
 4976: 
 4977: # ------------------------------------------------------------------ Course Log
 4978: #
 4979: # This routine flushes several buffers of non-mission-critical nature
 4980: #
 4981: 
 4982: sub flushcourselogs {
 4983:     &logthis('Flushing log buffers');
 4984: #
 4985: # course logs
 4986: # This is a log of all transactions in a course, which can be used
 4987: # for data mining purposes
 4988: #
 4989: # It also collects the courseid database, which lists last transaction
 4990: # times and course titles for all courseids
 4991: #
 4992:     my %courseidbuffer=();
 4993:     foreach my $crsid (keys(%courselogs)) {
 4994:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4995: 		          &escape($courselogs{$crsid}),
 4996: 		          $coursehombuf{$crsid}) eq 'ok') {
 4997: 	    delete $courselogs{$crsid};
 4998:         } else {
 4999:             &logthis('Failed to flush log buffer for '.$crsid);
 5000:             if (length($courselogs{$crsid})>40000) {
 5001:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5002:                         " exceeded maximum size, deleting.</font>");
 5003:                delete $courselogs{$crsid};
 5004:             }
 5005:         }
 5006:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5007:             'description' => $coursedescrbuf{$crsid},
 5008:             'inst_code'    => $courseinstcodebuf{$crsid},
 5009:             'type'        => $coursetypebuf{$crsid},
 5010:             'owner'       => $courseownerbuf{$crsid},
 5011:         };
 5012:     }
 5013: #
 5014: # Write course id database (reverse lookup) to homeserver of courses 
 5015: # Is used in pickcourse
 5016: #
 5017:     foreach my $crs_home (keys(%courseidbuffer)) {
 5018:         my $response = &courseidput(&host_domain($crs_home),
 5019:                                     $courseidbuffer{$crs_home},
 5020:                                     $crs_home,'timeonly');
 5021:     }
 5022: #
 5023: # File accesses
 5024: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5025: #
 5026:     foreach my $entry (keys(%accesshash)) {
 5027:         if ($entry =~ /___count$/) {
 5028:             my ($dom,$name);
 5029:             ($dom,$name,undef)=
 5030: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5031:             if (! defined($dom) || $dom eq '' || 
 5032:                 ! defined($name) || $name eq '') {
 5033:                 my $cid = $env{'request.course.id'};
 5034: #
 5035: # FIXME 11/29/2021
 5036: # Typo in rev. 1.458 (2003/12/09)??
 5037: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5038: #
 5039: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5040: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5041: # in a nohist_accesscount.db file for the user rather than the course.
 5042: #
 5043: # That said there is a lot of noise in the data being stored.
 5044: # So counts for prtspool/  and adm/ etc. are recorded.
 5045: #
 5046: # A review of which items ending '___count' are written to %accesshash should likely be 
 5047: # made before deciding whether to set these to 'course.' instead of 'request.'
 5048: #
 5049: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5050: # accesses for things which are not published resources, regardless of course, and
 5051: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5052: # anyone in the course for things which are not published resources.
 5053: #
 5054: # For an author, nohist_accesscount.db ends up having records for other items
 5055: # mixed up with the legitimate access counts for the author's published resources.
 5056: #
 5057:                 $dom  = $env{'request.'.$cid.'.domain'};
 5058:                 $name = $env{'request.'.$cid.'.num'};
 5059:             }
 5060:             my $value = $accesshash{$entry};
 5061:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5062:             my %temphash=($url => $value);
 5063:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5064:             if ($result eq 'ok') {
 5065:                 delete $accesshash{$entry};
 5066:             }
 5067:         } else {
 5068:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5069:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5070:             my %temphash=($entry => $accesshash{$entry});
 5071:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5072:                 delete $accesshash{$entry};
 5073:             }
 5074:         }
 5075:     }
 5076: #
 5077: # Roles
 5078: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5079: #
 5080:     foreach my $entry (keys(%userrolehash)) {
 5081:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5082: 	    split(/\:/,$entry);
 5083:         if (&Apache::lonnet::put('nohist_userroles',
 5084:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5085:                 $rudom,$runame) eq 'ok') {
 5086: 	    delete $userrolehash{$entry};
 5087:         }
 5088:     }
 5089: #
 5090: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5091: #
 5092:     my %domrolebuffer = ();
 5093:     foreach my $entry (keys(%domainrolehash)) {
 5094:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5095:         if ($domrolebuffer{$rudom}) {
 5096:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5097:                       '='.&escape($domainrolehash{$entry});
 5098:         } else {
 5099:             $domrolebuffer{$rudom}.=&escape($entry).
 5100:                       '='.&escape($domainrolehash{$entry});
 5101:         }
 5102:         delete $domainrolehash{$entry};
 5103:     }
 5104:     foreach my $dom (keys(%domrolebuffer)) {
 5105: 	my %servers;
 5106: 	if (defined(&domain($dom,'primary'))) {
 5107: 	    my $primary=&domain($dom,'primary');
 5108: 	    my $hostname=&hostname($primary);
 5109: 	    $servers{$primary} = $hostname;
 5110: 	} else { 
 5111: 	    %servers = &get_servers($dom,'library');
 5112: 	}
 5113: 	foreach my $tryserver (keys(%servers)) {
 5114: 	    if (&reply('domroleput:'.$dom.':'.
 5115: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5116: 		last;
 5117: 	    } else {  
 5118: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5119: 	    }
 5120:         }
 5121:     }
 5122:     $dumpcount++;
 5123: }
 5124: 
 5125: sub courselog {
 5126:     my $what=shift;
 5127:     $what=time.':'.$what;
 5128:     unless ($env{'request.course.id'}) { return ''; }
 5129:     $coursedombuf{$env{'request.course.id'}}=
 5130:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5131:     $coursenumbuf{$env{'request.course.id'}}=
 5132:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5133:     $coursehombuf{$env{'request.course.id'}}=
 5134:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5135:     $coursedescrbuf{$env{'request.course.id'}}=
 5136:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5137:     $courseinstcodebuf{$env{'request.course.id'}}=
 5138:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5139:     $courseownerbuf{$env{'request.course.id'}}=
 5140:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5141:     $coursetypebuf{$env{'request.course.id'}}=
 5142:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5143:     if (defined $courselogs{$env{'request.course.id'}}) {
 5144: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5145:     } else {
 5146: 	$courselogs{$env{'request.course.id'}}.=$what;
 5147:     }
 5148:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5149: 	&flushcourselogs();
 5150:     }
 5151: }
 5152: 
 5153: sub courseacclog {
 5154:     my $fnsymb=shift;
 5155:     unless ($env{'request.course.id'}) { return ''; }
 5156:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5157:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5158:         $what.=':POST';
 5159:         # FIXME: Probably ought to escape things....
 5160: 	foreach my $key (keys(%env)) {
 5161:             if ($key=~/^form\.(.*)/) {
 5162:                 my $formitem = $1;
 5163:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5164:                     $what.=':'.$formitem.'='.$env{$key};
 5165:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5166:                     if ($formitem eq 'proctorpassword') {
 5167:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5168:                     } else {
 5169:                         $what.=':'.$formitem.'='.$env{$key};
 5170:                     }
 5171:                 }
 5172:             }
 5173:         }
 5174:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5175:         # FIXME: We should not be depending on a form parameter that someone
 5176:         # editing lonsearchcat.pm might change in the future.
 5177:         if ($env{'form.phase'} eq 'course_search') {
 5178:             $what.= ':POST';
 5179:             # FIXME: Probably ought to escape things....
 5180:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5181:                                  'crsdiscuss') {
 5182:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5183:             }
 5184:         }
 5185:     }
 5186:     &courselog($what);
 5187: }
 5188: 
 5189: sub countacc {
 5190:     my $url=&declutter(shift);
 5191:     return if (! defined($url) || $url eq '');
 5192:     unless ($env{'request.course.id'}) { return ''; }
 5193: #
 5194: # Mark that this url was used in this course
 5195: #
 5196:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5197: #
 5198: # Increase the access count for this resource in this child process
 5199: #
 5200:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5201:     $accesshash{$key}++;
 5202: }
 5203: 
 5204: sub linklog {
 5205:     my ($from,$to)=@_;
 5206:     $from=&declutter($from);
 5207:     $to=&declutter($to);
 5208:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5209:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5210: }
 5211: 
 5212: sub statslog {
 5213:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5214:     if ($users<2) { return; }
 5215:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5216:             'course'       => $env{'request.course.id'},
 5217:             'sections'     => '"all"',
 5218:             'num_students' => $users,
 5219:             'part'         => $part,
 5220:             'symb'         => $symb,
 5221:             'mean_tries'   => $av_attempts,
 5222:             'deg_of_diff'  => $degdiff});
 5223:     foreach my $key (keys(%dynstore)) {
 5224:         $accesshash{$key}=$dynstore{$key};
 5225:     }
 5226: }
 5227:   
 5228: sub userrolelog {
 5229:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5230:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5231:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5232:        $userrolehash
 5233:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5234:                     =$tend.':'.$tstart;
 5235:     }
 5236:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5237:        $userrolehash
 5238:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5239:                     =$tend.':'.$tstart;
 5240:     }
 5241:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5242:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5243:        $domainrolehash
 5244:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5245:                     = $tend.':'.$tstart;
 5246:     }
 5247: }
 5248: 
 5249: sub courserolelog {
 5250:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5251:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5252:         my $cdom = $1;
 5253:         my $cnum = $2;
 5254:         my $sec = $3;
 5255:         my $namespace = 'rolelog';
 5256:         my %storehash = (
 5257:                            role    => $trole,
 5258:                            start   => $tstart,
 5259:                            end     => $tend,
 5260:                            selfenroll => $selfenroll,
 5261:                            context    => $context,
 5262:                         );
 5263:         if ($trole eq 'gr') {
 5264:             $namespace = 'groupslog';
 5265:             $storehash{'group'} = $sec;
 5266:         } else {
 5267:             $storehash{'section'} = $sec;
 5268:         }
 5269:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5270:                    $domain,$cnum,$cdom);
 5271:         if (($trole ne 'st') || ($sec ne '')) {
 5272:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5273:         }
 5274:     }
 5275:     return;
 5276: }
 5277: 
 5278: sub domainrolelog {
 5279:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5280:     if ($area =~ m{^/($match_domain)/$}) {
 5281:         my $cdom = $1;
 5282:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5283:         my $namespace = 'rolelog';
 5284:         my %storehash = (
 5285:                            role    => $trole,
 5286:                            start   => $tstart,
 5287:                            end     => $tend,
 5288:                            context => $context,
 5289:                         );
 5290:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5291:                    $domain,$domconfiguser,$cdom);
 5292:     }
 5293:     return;
 5294: 
 5295: }
 5296: 
 5297: sub coauthorrolelog {
 5298:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5299:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5300:         my $audom = $1;
 5301:         my $auname = $2;
 5302:         my $namespace = 'rolelog';
 5303:         my %storehash = (
 5304:                            role    => $trole,
 5305:                            start   => $tstart,
 5306:                            end     => $tend,
 5307:                            context => $context,
 5308:                         );
 5309:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5310:                    $domain,$auname,$audom);
 5311:     }
 5312:     return;
 5313: }
 5314: 
 5315: sub get_course_adv_roles {
 5316:     my ($cid,$codes) = @_;
 5317:     $cid=$env{'request.course.id'} unless (defined($cid));
 5318:     my %coursehash=&coursedescription($cid);
 5319:     my $crstype = &Apache::loncommon::course_type($cid);
 5320:     my %nothide=();
 5321:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5322:         if ($user !~ /:/) {
 5323: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5324:         } else {
 5325:             $nothide{$user}=1;
 5326:         }
 5327:     }
 5328:     my @possdoms = ($coursehash{'domain'});
 5329:     if ($coursehash{'checkforpriv'}) {
 5330:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5331:     }
 5332:     my %returnhash=();
 5333:     my %dumphash=
 5334:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5335:     my $now=time;
 5336:     my %privileged;
 5337:     foreach my $entry (keys(%dumphash)) {
 5338: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5339:         if (($tstart) && ($tstart<0)) { next; }
 5340:         if (($tend) && ($tend<$now)) { next; }
 5341:         if (($tstart) && ($now<$tstart)) { next; }
 5342:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5343: 	if ($username eq '' || $domain eq '') { next; }
 5344:         if ((&privileged($username,$domain,\@possdoms)) &&
 5345:             (!$nothide{$username.':'.$domain})) { next; }
 5346: 	if ($role eq 'cr') { next; }
 5347:         if ($codes) {
 5348:             if ($section) { $role .= ':'.$section; }
 5349:             if ($returnhash{$role}) {
 5350:                 $returnhash{$role}.=','.$username.':'.$domain;
 5351:             } else {
 5352:                 $returnhash{$role}=$username.':'.$domain;
 5353:             }
 5354:         } else {
 5355:             my $key=&plaintext($role,$crstype);
 5356:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5357:             if ($returnhash{$key}) {
 5358: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5359:             } else {
 5360:                 $returnhash{$key}=$username.':'.$domain;
 5361:             }
 5362:         }
 5363:     }
 5364:     return %returnhash;
 5365: }
 5366: 
 5367: sub get_my_roles {
 5368:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5369:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5370:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5371:     my (%dumphash,%nothide);
 5372:     if ($context eq 'userroles') {
 5373:         %dumphash = &dump('roles',$udom,$uname);
 5374:     } else {
 5375:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5376:         if ($hidepriv) {
 5377:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5378:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5379:                 if ($user !~ /:/) {
 5380:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5381:                 } else {
 5382:                     $nothide{$user} = 1;
 5383:                 }
 5384:             }
 5385:         }
 5386:     }
 5387:     my %returnhash=();
 5388:     my $now=time;
 5389:     my %privileged;
 5390:     foreach my $entry (keys(%dumphash)) {
 5391:         my ($role,$tend,$tstart);
 5392:         if ($context eq 'userroles') {
 5393:             next if ($entry =~ /^rolesdef/);
 5394: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5395:         } else {
 5396:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5397:         }
 5398:         if (($tstart) && ($tstart<0)) { next; }
 5399:         my $status = 'active';
 5400:         if (($tend) && ($tend<=$now)) {
 5401:             $status = 'previous';
 5402:         } 
 5403:         if (($tstart) && ($now<$tstart)) {
 5404:             $status = 'future';
 5405:         }
 5406:         if (ref($types) eq 'ARRAY') {
 5407:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5408:                 next;
 5409:             } 
 5410:         } else {
 5411:             if ($status ne 'active') {
 5412:                 next;
 5413:             }
 5414:         }
 5415:         my ($rolecode,$username,$domain,$section,$area);
 5416:         if ($context eq 'userroles') {
 5417:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5418:             (undef,$domain,$username,$section) = split(/\//,$area);
 5419:         } else {
 5420:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5421:         }
 5422:         if (ref($roledoms) eq 'ARRAY') {
 5423:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5424:                 next;
 5425:             }
 5426:         }
 5427:         if (ref($roles) eq 'ARRAY') {
 5428:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5429:                 if ($role =~ /^cr\//) {
 5430:                     if (!grep(/^cr$/,@{$roles})) {
 5431:                         next;
 5432:                     }
 5433:                 } elsif ($role =~ /^gr\//) {
 5434:                     if (!grep(/^gr$/,@{$roles})) {
 5435:                         next;
 5436:                     }
 5437:                 } else {
 5438:                     next;
 5439:                 }
 5440:             }
 5441:         }
 5442:         if ($hidepriv) {
 5443:             my @privroles = ('dc','su');
 5444:             if ($context eq 'userroles') {
 5445:                 next if (grep(/^\Q$role\E$/,@privroles));
 5446:             } else {
 5447:                 my $possdoms = [$domain];
 5448:                 if (ref($roledoms) eq 'ARRAY') {
 5449:                    push(@{$possdoms},@{$roledoms}); 
 5450:                 }
 5451:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5452:                     if (!$nothide{$username.':'.$domain}) {
 5453:                         next;
 5454:                     }
 5455:                 }
 5456:             }
 5457:         }
 5458:         if ($withsec) {
 5459:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5460:                 $tstart.':'.$tend;
 5461:         } else {
 5462:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5463:         }
 5464:     }
 5465:     return %returnhash;
 5466: }
 5467: 
 5468: sub get_all_adhocroles {
 5469:     my ($dom) = @_;
 5470:     my @roles_by_num = ();
 5471:     my %domdefaults = &get_domain_defaults($dom);
 5472:     my (%description,%access_in_dom,%access_info);
 5473:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5474:         my $count = 0;
 5475:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5476:         my %ordered;
 5477:         foreach my $role (sort(keys(%domcurrent))) {
 5478:             my ($order,$desc,$access_in_dom);
 5479:             if (ref($domcurrent{$role}) eq 'HASH') {
 5480:                 $order = $domcurrent{$role}{'order'};
 5481:                 $desc = $domcurrent{$role}{'desc'};
 5482:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5483:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5484:             }
 5485:             if ($order eq '') {
 5486:                 $order = $count;
 5487:             }
 5488:             $ordered{$order} = $role;
 5489:             if ($desc ne '') {
 5490:                 $description{$role} = $desc;
 5491:             } else {
 5492:                 $description{$role}= $role;
 5493:             }
 5494:             $count++;
 5495:         }
 5496:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5497:             push(@roles_by_num,$ordered{$item});
 5498:         }
 5499:     }
 5500:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5501: }
 5502: 
 5503: sub get_my_adhocroles {
 5504:     my ($cid,$checkreg) = @_;
 5505:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5506:     if ($env{'request.course.id'} eq $cid) {
 5507:         $cdom = $env{'course.'.$cid.'.domain'};
 5508:         $cnum = $env{'course.'.$cid.'.num'};
 5509:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5510:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5511:         $cdom = $1;
 5512:         $cnum = $2;
 5513:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5514:                                      $cdom,$cnum);
 5515:     }
 5516:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5517:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5518:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5519:         if ($rosterhash{$user} ne '') {
 5520:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5521:             return ([],{}) if ($type eq 'auto');
 5522:         }
 5523:     }
 5524:     if (($cdom ne '') && ($cnum ne ''))  {
 5525:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5526:             my $then=$env{'user.login.time'};
 5527:             my $update=$env{'user.update.time'};
 5528:             if (!$update) {
 5529:                 $update = $then;
 5530:             }
 5531:             my @liveroles;
 5532:             foreach my $role ('dh','da') {
 5533:                 if ($env{"user.role.$role./$cdom/"}) {
 5534:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5535:                     my $limit = $update;
 5536:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5537:                         $limit = $then;
 5538:                     }
 5539:                     my $activerole = 1;
 5540:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5541:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5542:                     if ($activerole) {
 5543:                         push(@liveroles,$role);
 5544:                     }
 5545:                 }
 5546:             }
 5547:             if (@liveroles) {
 5548:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5549:                     my ($accessref,$accessinfo,%access_in_dom);
 5550:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5551:                     if (ref($roles_by_num) eq 'ARRAY') {
 5552:                         if (@{$roles_by_num}) {
 5553:                             my %settings;
 5554:                             if ($env{'request.course.id'} eq $cid) {
 5555:                                 foreach my $envkey (keys(%env)) {
 5556:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5557:                                         $settings{$1} = $env{$envkey};
 5558:                                     }
 5559:                                 }
 5560:                             } else {
 5561:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5562:                             }
 5563:                             my %setincrs;
 5564:                             if ($settings{'internal.adhocaccess'}) {
 5565:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5566:                             }
 5567:                             my @statuses;
 5568:                             if ($env{'environment.inststatus'}) {
 5569:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5570:                             }
 5571:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5572:                             if (ref($accessref) eq 'HASH') {
 5573:                                 %access_in_dom = %{$accessref};
 5574:                             }
 5575:                             foreach my $role (@{$roles_by_num}) {
 5576:                                 my ($curraccess,@okstatus,@personnel);
 5577:                                 if ($setincrs{$role}) {
 5578:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5579:                                     if ($curraccess eq 'status') {
 5580:                                         @okstatus = split(/\&/,$rest);
 5581:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5582:                                         @personnel = split(/\&/,$rest);
 5583:                                     }
 5584:                                 } else {
 5585:                                     $curraccess = $access_in_dom{$role};
 5586:                                     if (ref($accessinfo) eq 'HASH') {
 5587:                                         if ($curraccess eq 'status') {
 5588:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5589:                                                 @okstatus = @{$accessinfo->{$role}};
 5590:                                             }
 5591:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5592:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5593:                                                 @personnel = @{$accessinfo->{$role}};
 5594:                                             }
 5595:                                         }
 5596:                                     }
 5597:                                 }
 5598:                                 if ($curraccess eq 'none') {
 5599:                                     next;
 5600:                                 } elsif ($curraccess eq 'all') {
 5601:                                     push(@possroles,$role);
 5602:                                 } elsif ($curraccess eq 'dh') {
 5603:                                     if (grep(/^dh$/,@liveroles)) {
 5604:                                         push(@possroles,$role);
 5605:                                     } else {
 5606:                                         next;
 5607:                                     }
 5608:                                 } elsif ($curraccess eq 'da') {
 5609:                                     if (grep(/^da$/,@liveroles)) {
 5610:                                         push(@possroles,$role);
 5611:                                     } else {
 5612:                                         next;
 5613:                                     }
 5614:                                 } elsif ($curraccess eq 'status') {
 5615:                                     if (@okstatus) {
 5616:                                         if (!@statuses) {
 5617:                                             if (grep(/^default$/,@okstatus)) {
 5618:                                                 push(@possroles,$role);
 5619:                                             }
 5620:                                         } else {
 5621:                                             foreach my $status (@okstatus) {
 5622:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5623:                                                     push(@possroles,$role);
 5624:                                                     last;
 5625:                                                 }
 5626:                                             }
 5627:                                         }
 5628:                                     }
 5629:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5630:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5631:                                         if ($curraccess eq 'exc') {
 5632:                                             push(@possroles,$role);
 5633:                                         }
 5634:                                     } elsif ($curraccess eq 'inc') {
 5635:                                         push(@possroles,$role);
 5636:                                     }
 5637:                                 }
 5638:                             }
 5639:                         }
 5640:                     }
 5641:                 }
 5642:             }
 5643:         }
 5644:     }
 5645:     unless (ref($description) eq 'HASH') {
 5646:         if (ref($roles_by_num) eq 'ARRAY') {
 5647:             my %desc;
 5648:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5649:             $description = \%desc;
 5650:         } else {
 5651:             $description = {};
 5652:         }
 5653:     }
 5654:     return (\@possroles,$description);
 5655: }
 5656: 
 5657: # ----------------------------------------------------- Frontpage Announcements
 5658: #
 5659: #
 5660: 
 5661: sub postannounce {
 5662:     my ($server,$text)=@_;
 5663:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5664:     unless ($text=~/\w/) { $text=''; }
 5665:     return &reply('setannounce:'.&escape($text),$server);
 5666: }
 5667: 
 5668: sub getannounce {
 5669: 
 5670:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5671: 	my $announcement='';
 5672: 	while (my $line = <$fh>) { $announcement .= $line; }
 5673: 	close($fh);
 5674: 	if ($announcement=~/\w/) { 
 5675: 	    return 
 5676:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5677:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5678: 	} else {
 5679: 	    return '';
 5680: 	}
 5681:     } else {
 5682: 	return '';
 5683:     }
 5684: }
 5685: 
 5686: # ---------------------------------------------------------- Course ID routines
 5687: # Deal with domain's nohist_courseid.db files
 5688: #
 5689: 
 5690: sub courseidput {
 5691:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5692:     return unless (ref($storehash) eq 'HASH');
 5693:     my $outcome;
 5694:     if ($caller eq 'timeonly') {
 5695:         my $cids = '';
 5696:         foreach my $item (keys(%$storehash)) {
 5697:             $cids.=&escape($item).'&';
 5698:         }
 5699:         $cids=~s/\&$//;
 5700:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5701:                           $coursehome);       
 5702:     } else {
 5703:         my $items = '';
 5704:         foreach my $item (keys(%$storehash)) {
 5705:             $items.= &escape($item).'='.
 5706:                      &freeze_escape($$storehash{$item}).'&';
 5707:         }
 5708:         $items=~s/\&$//;
 5709:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5710:                           $coursehome);
 5711:     }
 5712:     if ($outcome eq 'unknown_cmd') {
 5713:         my $what;
 5714:         foreach my $cid (keys(%$storehash)) {
 5715:             $what .= &escape($cid).'=';
 5716:             foreach my $item ('description','inst_code','owner','type') {
 5717:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5718:             }
 5719:             $what =~ s/\:$/&/;
 5720:         }
 5721:         $what =~ s/\&$//;  
 5722:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5723:     } else {
 5724:         return $outcome;
 5725:     }
 5726: }
 5727: 
 5728: sub courseiddump {
 5729:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5730:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5731:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5732:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5733:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5734:     my $as_hash = 1;
 5735:     my %returnhash;
 5736:     if (!$domfilter) { $domfilter=''; }
 5737:     my %libserv = &all_library();
 5738:     foreach my $tryserver (keys(%libserv)) {
 5739:         if ( (  $hostidflag == 1 
 5740: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5741: 	     || (!defined($hostidflag)) ) {
 5742: 
 5743: 	    if (($domfilter eq '') ||
 5744: 		(&host_domain($tryserver) eq $domfilter)) {
 5745:                 my $rep;
 5746:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5747:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5748:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5749:                                 &escape($descfilter), &escape($instcodefilter), 
 5750:                                 &escape($ownerfilter), &escape($coursefilter),
 5751:                                 &escape($typefilter), &escape($regexp_ok), 
 5752:                                 $as_hash, &escape($selfenrollonly), 
 5753:                                 &escape($catfilter), $showhidden, $caller, 
 5754:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5755:                                 &escape($createdbefore), &escape($createdafter), 
 5756:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5757:                                 $reqcrsdom,&escape($reqinstcode))));
 5758:                 } else {
 5759:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5760:                              $sincefilter.':'.&escape($descfilter).':'.
 5761:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5762:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5763:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5764:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5765:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5766:                              &escape($cc_clone).':'.$cloneonly.':'.
 5767:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5768:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5769:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5770:                 }
 5771:                      
 5772:                 my @pairs=split(/\&/,$rep);
 5773:                 foreach my $item (@pairs) {
 5774:                     my ($key,$value)=split(/\=/,$item,2);
 5775:                     $key = &unescape($key);
 5776:                     next if ($key =~ /^error: 2 /);
 5777:                     my $result = &thaw_unescape($value);
 5778:                     if (ref($result) eq 'HASH') {
 5779:                         $returnhash{$key}=$result;
 5780:                     } else {
 5781:                         my @responses = split(/:/,$value);
 5782:                         my @items = ('description','inst_code','owner','type');
 5783:                         for (my $i=0; $i<@responses; $i++) {
 5784:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5785:                         }
 5786:                     }
 5787:                 }
 5788:             }
 5789:         }
 5790:     }
 5791:     return %returnhash;
 5792: }
 5793: 
 5794: sub courselastaccess {
 5795:     my ($cdom,$cnum,$hostidref) = @_;
 5796:     my %returnhash;
 5797:     if ($cdom && $cnum) {
 5798:         my $chome = &homeserver($cnum,$cdom);
 5799:         if ($chome ne 'no_host') {
 5800:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5801:             &extract_lastaccess(\%returnhash,$rep);
 5802:         }
 5803:     } else {
 5804:         if (!$cdom) { $cdom=''; }
 5805:         my %libserv = &all_library();
 5806:         foreach my $tryserver (keys(%libserv)) {
 5807:             if (ref($hostidref) eq 'ARRAY') {
 5808:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5809:             } 
 5810:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5811:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5812:                 &extract_lastaccess(\%returnhash,$rep);
 5813:             }
 5814:         }
 5815:     }
 5816:     return %returnhash;
 5817: }
 5818: 
 5819: sub extract_lastaccess {
 5820:     my ($returnhash,$rep) = @_;
 5821:     if (ref($returnhash) eq 'HASH') {
 5822:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5823:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5824:                  $rep eq '') {
 5825:             my @pairs=split(/\&/,$rep);
 5826:             foreach my $item (@pairs) {
 5827:                 my ($key,$value)=split(/\=/,$item,2);
 5828:                 $key = &unescape($key);
 5829:                 next if ($key =~ /^error: 2 /);
 5830:                 $returnhash->{$key} = &thaw_unescape($value);
 5831:             }
 5832:         }
 5833:     }
 5834:     return;
 5835: }
 5836: 
 5837: # ---------------------------------------------------------- DC e-mail
 5838: 
 5839: sub dcmailput {
 5840:     my ($domain,$msgid,$message,$server)=@_;
 5841:     my $status = &Apache::lonnet::critical(
 5842:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5843:        &escape($message),$server);
 5844:     return $status;
 5845: }
 5846: 
 5847: sub dcmaildump {
 5848:     my ($dom,$startdate,$enddate,$senders) = @_;
 5849:     my %returnhash=();
 5850: 
 5851:     if (defined(&domain($dom,'primary'))) {
 5852:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5853:                                                          &escape($enddate).':';
 5854: 	my @esc_senders=map { &escape($_)} @$senders;
 5855: 	$cmd.=&escape(join('&',@esc_senders));
 5856: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5857:             my ($key,$value) = split(/\=/,$line,2);
 5858:             if (($key) && ($value)) {
 5859:                 $returnhash{&unescape($key)} = &unescape($value);
 5860:             }
 5861:         }
 5862:     }
 5863:     return %returnhash;
 5864: }
 5865: # ---------------------------------------------------------- Domain roles
 5866: 
 5867: sub get_domain_roles {
 5868:     my ($dom,$roles,$startdate,$enddate)=@_;
 5869:     if ((!defined($startdate)) || ($startdate eq '')) {
 5870:         $startdate = '.';
 5871:     }
 5872:     if ((!defined($enddate)) || ($enddate eq '')) {
 5873:         $enddate = '.';
 5874:     }
 5875:     my $rolelist;
 5876:     if (ref($roles) eq 'ARRAY') {
 5877:         $rolelist = join('&',@{$roles});
 5878:     }
 5879:     my %personnel = ();
 5880: 
 5881:     my %servers = &get_servers($dom,'library');
 5882:     foreach my $tryserver (keys(%servers)) {
 5883: 	%{$personnel{$tryserver}}=();
 5884: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5885: 					    &escape($startdate).':'.
 5886: 					    &escape($enddate).':'.
 5887: 					    &escape($rolelist), $tryserver))) {
 5888: 	    my ($key,$value) = split(/\=/,$line,2);
 5889: 	    if (($key) && ($value)) {
 5890: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5891: 	    }
 5892: 	}
 5893:     }
 5894:     return %personnel;
 5895: }
 5896: 
 5897: sub get_active_domroles {
 5898:     my ($dom,$roles) = @_;
 5899:     return () unless (ref($roles) eq 'ARRAY');
 5900:     my $now = time;
 5901:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5902:     my %domroles;
 5903:     foreach my $server (keys(%dompersonnel)) {
 5904:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5905:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5906:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5907:         }
 5908:     }
 5909:     return %domroles;
 5910: }
 5911: 
 5912: # ----------------------------------------------------------- Interval timing 
 5913: 
 5914: {
 5915: # Caches needed for speedup of navmaps
 5916: # We don't want to cache this for very long at all (5 seconds at most)
 5917: # 
 5918: # The user for whom we cache
 5919: my $cachedkey='';
 5920: # The cached times for this user
 5921: my %cachedtimes=();
 5922: # When this was last done
 5923: my $cachedtime='';
 5924: 
 5925: sub load_all_first_access {
 5926:     my ($uname,$udom,$ignorecache)=@_;
 5927:     if (($cachedkey eq $uname.':'.$udom) &&
 5928:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5929:         (!$ignorecache)) {
 5930:         return;
 5931:     }
 5932:     $cachedtime=time;
 5933:     $cachedkey=$uname.':'.$udom;
 5934:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5935: }
 5936: 
 5937: sub get_first_access {
 5938:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5939:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5940:     if ($argsymb) { $symb=$argsymb; }
 5941:     my ($map,$id,$res)=&decode_symb($symb);
 5942:     if ($argmap) { $map = $argmap; }
 5943:     if ($type eq 'course') {
 5944: 	$res='course';
 5945:     } elsif ($type eq 'map') {
 5946: 	$res=&symbread($map);
 5947:     } else {
 5948: 	$res=$symb;
 5949:     }
 5950:     &load_all_first_access($uname,$udom,$ignorecache);
 5951:     return $cachedtimes{"$courseid\0$res"};
 5952: }
 5953: 
 5954: sub set_first_access {
 5955:     my ($type,$interval)=@_;
 5956:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5957:     my ($map,$id,$res)=&decode_symb($symb);
 5958:     if ($type eq 'course') {
 5959: 	$res='course';
 5960:     } elsif ($type eq 'map') {
 5961: 	$res=&symbread($map);
 5962:     } else {
 5963: 	$res=$symb;
 5964:     }
 5965:     $cachedkey='';
 5966:     my $firstaccess=&get_first_access($type,$symb,$map);
 5967:     if ($firstaccess) {
 5968:         &logthis("First access time already set ($firstaccess) when attempting ".
 5969:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5970:                  "in $courseid");
 5971:         return 'already_set';
 5972:     } else {
 5973:         my $start = time;
 5974: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5975:                           $udom,$uname);
 5976:         if ($putres eq 'ok') {
 5977:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5978:                  $udom,$uname); 
 5979:             &appenv(
 5980:                      {
 5981:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5982:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5983:                      }
 5984:                   );
 5985:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5986:                 $cachedtimes{"$courseid\0$res"} = $start;
 5987:             }
 5988:         } elsif ($putres ne 'refused') {
 5989:             &logthis("Result: $putres when attempting to set first access time ".
 5990:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5991:         }
 5992:         return $putres;
 5993:     }
 5994:     return 'already_set';
 5995: }
 5996: }
 5997: 
 5998: # --------------------------------------------- Set Expire Date for Spreadsheet
 5999: 
 6000: sub expirespread {
 6001:     my ($uname,$udom,$stype,$usymb)=@_;
 6002:     my $cid=$env{'request.course.id'}; 
 6003:     if ($cid) {
 6004:        my $now=time;
 6005:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6006:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6007:                             $env{'course.'.$cid.'.num'}.
 6008: 	        	    ':nohist_expirationdates:'.
 6009:                             &escape($key).'='.$now,
 6010:                             $env{'course.'.$cid.'.home'})
 6011:     }
 6012:     return 'ok';
 6013: }
 6014: 
 6015: # ----------------------------------------------------- Devalidate Spreadsheets
 6016: 
 6017: sub devalidate {
 6018:     my ($symb,$uname,$udom)=@_;
 6019:     my $cid=$env{'request.course.id'}; 
 6020:     if ($cid) {
 6021:         # delete the stored spreadsheets for
 6022:         # - the student level sheet of this user in course's homespace
 6023:         # - the assessment level sheet for this resource 
 6024:         #   for this user in user's homespace
 6025: 	# - current conditional state info
 6026: 	my $key=$uname.':'.$udom.':';
 6027:         my $status=
 6028: 	    &del('nohist_calculatedsheets',
 6029: 		 [$key.'studentcalc:'],
 6030: 		 $env{'course.'.$cid.'.domain'},
 6031: 		 $env{'course.'.$cid.'.num'})
 6032: 		.' '.
 6033: 	    &del('nohist_calculatedsheets_'.$cid,
 6034: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6035:         unless ($status eq 'ok ok') {
 6036:            &logthis('Could not devalidate spreadsheet '.
 6037:                     $uname.' at '.$udom.' for '.
 6038: 		    $symb.': '.$status);
 6039:         }
 6040: 	&delenv('user.state.'.$cid);
 6041:     }
 6042: }
 6043: 
 6044: sub get_scalar {
 6045:     my ($string,$end) = @_;
 6046:     my $value;
 6047:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6048: 	$value = $1;
 6049:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6050: 	$value = $1;
 6051:     }
 6052:     return &unescape($value);
 6053: }
 6054: 
 6055: sub array2str {
 6056:   my (@array) = @_;
 6057:   my $result=&arrayref2str(\@array);
 6058:   $result=~s/^__ARRAY_REF__//;
 6059:   $result=~s/__END_ARRAY_REF__$//;
 6060:   return $result;
 6061: }
 6062: 
 6063: sub arrayref2str {
 6064:   my ($arrayref) = @_;
 6065:   my $result='__ARRAY_REF__';
 6066:   foreach my $elem (@$arrayref) {
 6067:     if(ref($elem) eq 'ARRAY') {
 6068:       $result.=&arrayref2str($elem).'&';
 6069:     } elsif(ref($elem) eq 'HASH') {
 6070:       $result.=&hashref2str($elem).'&';
 6071:     } elsif(ref($elem)) {
 6072:       #print("Got a ref of ".(ref($elem))." skipping.");
 6073:     } else {
 6074:       $result.=&escape($elem).'&';
 6075:     }
 6076:   }
 6077:   $result=~s/\&$//;
 6078:   $result .= '__END_ARRAY_REF__';
 6079:   return $result;
 6080: }
 6081: 
 6082: sub hash2str {
 6083:   my (%hash) = @_;
 6084:   my $result=&hashref2str(\%hash);
 6085:   $result=~s/^__HASH_REF__//;
 6086:   $result=~s/__END_HASH_REF__$//;
 6087:   return $result;
 6088: }
 6089: 
 6090: sub hashref2str {
 6091:   my ($hashref)=@_;
 6092:   my $result='__HASH_REF__';
 6093:   foreach my $key (sort(keys(%$hashref))) {
 6094:     if (ref($key) eq 'ARRAY') {
 6095:       $result.=&arrayref2str($key).'=';
 6096:     } elsif (ref($key) eq 'HASH') {
 6097:       $result.=&hashref2str($key).'=';
 6098:     } elsif (ref($key)) {
 6099:       $result.='=';
 6100:       #print("Got a ref of ".(ref($key))." skipping.");
 6101:     } else {
 6102: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6103:     }
 6104: 
 6105:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6106:       $result.=&arrayref2str($hashref->{$key}).'&';
 6107:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6108:       $result.=&hashref2str($hashref->{$key}).'&';
 6109:     } elsif(ref($hashref->{$key})) {
 6110:        $result.='&';
 6111:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6112:     } else {
 6113:       $result.=&escape($hashref->{$key}).'&';
 6114:     }
 6115:   }
 6116:   $result=~s/\&$//;
 6117:   $result .= '__END_HASH_REF__';
 6118:   return $result;
 6119: }
 6120: 
 6121: sub str2hash {
 6122:     my ($string)=@_;
 6123:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6124:     return %$hash;
 6125: }
 6126: 
 6127: sub str2hashref {
 6128:   my ($string) = @_;
 6129: 
 6130:   my %hash;
 6131: 
 6132:   if($string !~ /^__HASH_REF__/) {
 6133:       if (! ($string eq '' || !defined($string))) {
 6134: 	  $hash{'error'}='Not hash reference';
 6135:       }
 6136:       return (\%hash, $string);
 6137:   }
 6138: 
 6139:   $string =~ s/^__HASH_REF__//;
 6140: 
 6141:   while($string !~ /^__END_HASH_REF__/) {
 6142:       #key
 6143:       my $key='';
 6144:       if($string =~ /^__HASH_REF__/) {
 6145:           ($key, $string)=&str2hashref($string);
 6146:           if(defined($key->{'error'})) {
 6147:               $hash{'error'}='Bad data';
 6148:               return (\%hash, $string);
 6149:           }
 6150:       } elsif($string =~ /^__ARRAY_REF__/) {
 6151:           ($key, $string)=&str2arrayref($string);
 6152:           if($key->[0] eq 'Array reference error') {
 6153:               $hash{'error'}='Bad data';
 6154:               return (\%hash, $string);
 6155:           }
 6156:       } else {
 6157:           $string =~ s/^(.*?)=//;
 6158: 	  $key=&unescape($1);
 6159:       }
 6160:       $string =~ s/^=//;
 6161: 
 6162:       #value
 6163:       my $value='';
 6164:       if($string =~ /^__HASH_REF__/) {
 6165:           ($value, $string)=&str2hashref($string);
 6166:           if(defined($value->{'error'})) {
 6167:               $hash{'error'}='Bad data';
 6168:               return (\%hash, $string);
 6169:           }
 6170:       } elsif($string =~ /^__ARRAY_REF__/) {
 6171:           ($value, $string)=&str2arrayref($string);
 6172:           if($value->[0] eq 'Array reference error') {
 6173:               $hash{'error'}='Bad data';
 6174:               return (\%hash, $string);
 6175:           }
 6176:       } else {
 6177: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6178:       }
 6179:       $string =~ s/^&//;
 6180: 
 6181:       $hash{$key}=$value;
 6182:   }
 6183: 
 6184:   $string =~ s/^__END_HASH_REF__//;
 6185: 
 6186:   return (\%hash, $string);
 6187: }
 6188: 
 6189: sub str2array {
 6190:     my ($string)=@_;
 6191:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6192:     return @$array;
 6193: }
 6194: 
 6195: sub str2arrayref {
 6196:   my ($string) = @_;
 6197:   my @array;
 6198: 
 6199:   if($string !~ /^__ARRAY_REF__/) {
 6200:       if (! ($string eq '' || !defined($string))) {
 6201: 	  $array[0]='Array reference error';
 6202:       }
 6203:       return (\@array, $string);
 6204:   }
 6205: 
 6206:   $string =~ s/^__ARRAY_REF__//;
 6207: 
 6208:   while($string !~ /^__END_ARRAY_REF__/) {
 6209:       my $value='';
 6210:       if($string =~ /^__HASH_REF__/) {
 6211:           ($value, $string)=&str2hashref($string);
 6212:           if(defined($value->{'error'})) {
 6213:               $array[0] ='Array reference error';
 6214:               return (\@array, $string);
 6215:           }
 6216:       } elsif($string =~ /^__ARRAY_REF__/) {
 6217:           ($value, $string)=&str2arrayref($string);
 6218:           if($value->[0] eq 'Array reference error') {
 6219:               $array[0] ='Array reference error';
 6220:               return (\@array, $string);
 6221:           }
 6222:       } else {
 6223: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6224:       }
 6225:       $string =~ s/^&//;
 6226: 
 6227:       push(@array, $value);
 6228:   }
 6229: 
 6230:   $string =~ s/^__END_ARRAY_REF__//;
 6231: 
 6232:   return (\@array, $string);
 6233: }
 6234: 
 6235: # -------------------------------------------------------------------Temp Store
 6236: 
 6237: sub tmpreset {
 6238:   my ($symb,$namespace,$domain,$stuname) = @_;
 6239:   if (!$symb) {
 6240:     $symb=&symbread();
 6241:     if (!$symb) { $symb= $env{'request.url'}; }
 6242:   }
 6243:   $symb=escape($symb);
 6244: 
 6245:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6246:   $namespace=~s/\//\_/g;
 6247:   $namespace=~s/\W//g;
 6248: 
 6249:   if (!$domain) { $domain=$env{'user.domain'}; }
 6250:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6251:   if ($domain eq 'public' && $stuname eq 'public') {
 6252:       $stuname=&get_requestor_ip();
 6253:   }
 6254:   my $path=LONCAPA::tempdir();
 6255:   my %hash;
 6256:   if (tie(%hash,'GDBM_File',
 6257: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6258: 	  &GDBM_WRCREAT(),0640)) {
 6259:     foreach my $key (keys(%hash)) {
 6260:       if ($key=~ /:$symb/) {
 6261: 	delete($hash{$key});
 6262:       }
 6263:     }
 6264:   }
 6265: }
 6266: 
 6267: sub tmpstore {
 6268:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6269: 
 6270:   if (!$symb) {
 6271:     $symb=&symbread();
 6272:     if (!$symb) { $symb= $env{'request.url'}; }
 6273:   }
 6274:   $symb=escape($symb);
 6275: 
 6276:   if (!$namespace) {
 6277:     # I don't think we would ever want to store this for a course.
 6278:     # it seems this will only be used if we don't have a course.
 6279:     #$namespace=$env{'request.course.id'};
 6280:     #if (!$namespace) {
 6281:       $namespace=$env{'request.state'};
 6282:     #}
 6283:   }
 6284:   $namespace=~s/\//\_/g;
 6285:   $namespace=~s/\W//g;
 6286:   if (!$domain) { $domain=$env{'user.domain'}; }
 6287:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6288:   if ($domain eq 'public' && $stuname eq 'public') {
 6289:       $stuname=&get_requestor_ip();
 6290:   }
 6291:   my $now=time;
 6292:   my %hash;
 6293:   my $path=LONCAPA::tempdir();
 6294:   if (tie(%hash,'GDBM_File',
 6295: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6296: 	  &GDBM_WRCREAT(),0640)) {
 6297:     $hash{"version:$symb"}++;
 6298:     my $version=$hash{"version:$symb"};
 6299:     my $allkeys=''; 
 6300:     foreach my $key (keys(%$storehash)) {
 6301:       $allkeys.=$key.':';
 6302:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6303:     }
 6304:     $hash{"$version:$symb:timestamp"}=$now;
 6305:     $allkeys.='timestamp';
 6306:     $hash{"$version:keys:$symb"}=$allkeys;
 6307:     if (untie(%hash)) {
 6308:       return 'ok';
 6309:     } else {
 6310:       return "error:$!";
 6311:     }
 6312:   } else {
 6313:     return "error:$!";
 6314:   }
 6315: }
 6316: 
 6317: # -----------------------------------------------------------------Temp Restore
 6318: 
 6319: sub tmprestore {
 6320:   my ($symb,$namespace,$domain,$stuname) = @_;
 6321: 
 6322:   if (!$symb) {
 6323:     $symb=&symbread();
 6324:     if (!$symb) { $symb= $env{'request.url'}; }
 6325:   }
 6326:   $symb=escape($symb);
 6327: 
 6328:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6329: 
 6330:   if (!$domain) { $domain=$env{'user.domain'}; }
 6331:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6332:   if ($domain eq 'public' && $stuname eq 'public') {
 6333:       $stuname=&get_requestor_ip();
 6334:   }
 6335:   my %returnhash;
 6336:   $namespace=~s/\//\_/g;
 6337:   $namespace=~s/\W//g;
 6338:   my %hash;
 6339:   my $path=LONCAPA::tempdir();
 6340:   if (tie(%hash,'GDBM_File',
 6341: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6342: 	  &GDBM_READER(),0640)) {
 6343:     my $version=$hash{"version:$symb"};
 6344:     $returnhash{'version'}=$version;
 6345:     my $scope;
 6346:     for ($scope=1;$scope<=$version;$scope++) {
 6347:       my $vkeys=$hash{"$scope:keys:$symb"};
 6348:       my @keys=split(/:/,$vkeys);
 6349:       my $key;
 6350:       $returnhash{"$scope:keys"}=$vkeys;
 6351:       foreach $key (@keys) {
 6352: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6353: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6354:       }
 6355:     }
 6356:     if (!(untie(%hash))) {
 6357:       return "error:$!";
 6358:     }
 6359:   } else {
 6360:     return "error:$!";
 6361:   }
 6362:   return %returnhash;
 6363: }
 6364: 
 6365: # ----------------------------------------------------------------------- Store
 6366: 
 6367: sub store {
 6368:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6369:     my $home='';
 6370: 
 6371:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6372: 
 6373:     $symb=&symbclean($symb);
 6374:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6375: 
 6376:     if (!$domain) { $domain=$env{'user.domain'}; }
 6377:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6378: 
 6379:     &devalidate($symb,$stuname,$domain);
 6380: 
 6381:     $symb=escape($symb);
 6382:     if (!$namespace) { 
 6383:        unless ($namespace=$env{'request.course.id'}) { 
 6384:           return ''; 
 6385:        } 
 6386:     }
 6387:     if (!$home) { $home=$env{'user.home'}; }
 6388: 
 6389:     $$storehash{'ip'}=&get_requestor_ip();
 6390:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6391: 
 6392:     my $namevalue='';
 6393:     foreach my $key (keys(%$storehash)) {
 6394:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6395:     }
 6396:     $namevalue=~s/\&$//;
 6397:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6398:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6399: }
 6400: 
 6401: # -------------------------------------------------------------- Critical Store
 6402: 
 6403: sub cstore {
 6404:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6405:     my $home='';
 6406: 
 6407:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6408: 
 6409:     $symb=&symbclean($symb);
 6410:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6411: 
 6412:     if (!$domain) { $domain=$env{'user.domain'}; }
 6413:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6414: 
 6415:     &devalidate($symb,$stuname,$domain);
 6416: 
 6417:     $symb=escape($symb);
 6418:     if (!$namespace) { 
 6419:        unless ($namespace=$env{'request.course.id'}) { 
 6420:           return ''; 
 6421:        } 
 6422:     }
 6423:     if (!$home) { $home=$env{'user.home'}; }
 6424: 
 6425:     $$storehash{'ip'}=&get_requestor_ip();
 6426:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6427: 
 6428:     my $namevalue='';
 6429:     foreach my $key (keys(%$storehash)) {
 6430:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6431:     }
 6432:     $namevalue=~s/\&$//;
 6433:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6434:     return critical
 6435:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6436: }
 6437: 
 6438: # --------------------------------------------------------------------- Restore
 6439: 
 6440: sub restore {
 6441:     my ($symb,$namespace,$domain,$stuname) = @_;
 6442:     my $home='';
 6443: 
 6444:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6445: 
 6446:     if (!$symb) {
 6447:         return if ($namespace eq 'courserequests');
 6448:         unless ($symb=escape(&symbread())) { return ''; }
 6449:     } else {
 6450:         unless ($namespace eq 'courserequests') {
 6451:             $symb=&escape(&symbclean($symb));
 6452:         }
 6453:     }
 6454:     if (!$namespace) { 
 6455:        unless ($namespace=$env{'request.course.id'}) { 
 6456:           return ''; 
 6457:        } 
 6458:     }
 6459:     if (!$domain) { $domain=$env{'user.domain'}; }
 6460:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6461:     if (!$home) { $home=$env{'user.home'}; }
 6462:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6463: 
 6464:     my %returnhash=();
 6465:     foreach my $line (split(/\&/,$answer)) {
 6466: 	my ($name,$value)=split(/\=/,$line);
 6467:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6468:     }
 6469:     my $version;
 6470:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6471:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6472:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6473:        }
 6474:     }
 6475:     return %returnhash;
 6476: }
 6477: 
 6478: # ---------------------------------------------------------- Course Description
 6479: #
 6480: #  
 6481: 
 6482: sub coursedescription {
 6483:     my ($courseid,$args)=@_;
 6484:     $courseid=~s/^\///;
 6485:     $courseid=~s/\_/\//g;
 6486:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6487:     my $chome=&homeserver($cnum,$cdomain);
 6488:     my $normalid=$cdomain.'_'.$cnum;
 6489:     # need to always cache even if we get errors otherwise we keep 
 6490:     # trying and trying and trying to get the course description.
 6491:     my %envhash=();
 6492:     my %returnhash=();
 6493:     
 6494:     my $expiretime=600;
 6495:     if ($env{'request.course.id'} eq $normalid) {
 6496: 	$expiretime=120;
 6497:     }
 6498: 
 6499:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6500:     if (!$args->{'freshen_cache'}
 6501: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6502: 	foreach my $key (keys(%env)) {
 6503: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6504: 	    my ($setting) = $1;
 6505: 	    $returnhash{$setting} = $env{$key};
 6506: 	}
 6507: 	return %returnhash;
 6508:     }
 6509: 
 6510:     # get the data again
 6511: 
 6512:     if (!$args->{'one_time'}) {
 6513: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6514:     }
 6515: 
 6516:     if ($chome ne 'no_host') {
 6517:        %returnhash=&dump('environment',$cdomain,$cnum);
 6518:        if (!exists($returnhash{'con_lost'})) {
 6519: 	   my $username = $env{'user.name'}; # Defult username
 6520: 	   if(defined $args->{'user'}) {
 6521: 	       $username = $args->{'user'};
 6522: 	   }
 6523:            $returnhash{'home'}= $chome;
 6524: 	   $returnhash{'domain'} = $cdomain;
 6525: 	   $returnhash{'num'} = $cnum;
 6526:            if (!defined($returnhash{'type'})) {
 6527:                $returnhash{'type'} = 'Course';
 6528:            }
 6529:            while (my ($name,$value) = each %returnhash) {
 6530:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6531:            }
 6532:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6533:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6534: 	       $username.'_'.$cdomain.'_'.$cnum;
 6535:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6536:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6537:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6538:        }
 6539:     }
 6540:     if (!$args->{'one_time'}) {
 6541: 	&appenv(\%envhash);
 6542:     }
 6543:     return %returnhash;
 6544: }
 6545: 
 6546: sub update_released_required {
 6547:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6548:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6549:         $cid = $env{'request.course.id'};
 6550:         $cdom = $env{'course.'.$cid.'.domain'};
 6551:         $cnum = $env{'course.'.$cid.'.num'};
 6552:         $chome = $env{'course.'.$cid.'.home'};
 6553:     }
 6554:     if ($needsrelease) {
 6555:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6556:         my $needsupdate;
 6557:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6558:             $needsupdate = 1;
 6559:         } else {
 6560:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6561:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6562:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6563:                 $needsupdate = 1;
 6564:             }
 6565:         }
 6566:         if ($needsupdate) {
 6567:             my %needshash = (
 6568:                              'internal.releaserequired' => $needsrelease,
 6569:                             );
 6570:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6571:             if ($putresult eq 'ok') {
 6572:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6573:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6574:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6575:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6576:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6577:                 }
 6578:             }
 6579:         }
 6580:     }
 6581:     return;
 6582: }
 6583: 
 6584: # -------------------------------------------------See if a user is privileged
 6585: 
 6586: sub privileged {
 6587:     my ($username,$domain,$possdomains,$possroles)=@_;
 6588:     my $now = time;
 6589:     my $roles;
 6590:     if (ref($possroles) eq 'ARRAY') {
 6591:         $roles = $possroles; 
 6592:     } else {
 6593:         $roles = ['dc','su'];
 6594:     }
 6595:     if (ref($possdomains) eq 'ARRAY') {
 6596:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6597:         foreach my $dom (@{$possdomains}) {
 6598:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6599:                 (ref($privileged{$dom}) eq 'HASH')) {
 6600:                 foreach my $role (@{$roles}) {
 6601:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6602:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6603:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6604:                             return 1 unless (($end && $end < $now) ||
 6605:                                              ($start && $start > $now));
 6606:                         }
 6607:                     }
 6608:                 }
 6609:             }
 6610:         }
 6611:     } else {
 6612:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6613:         my $now = time;
 6614: 
 6615:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6616:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6617:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6618:                 return 1 unless ($tend && $tend < $now) 
 6619:                         or ($tstart && $tstart > $now);
 6620:             }
 6621:         }
 6622:     }
 6623:     return 0;
 6624: }
 6625: 
 6626: sub privileged_by_domain {
 6627:     my ($domains,$roles) = @_;
 6628:     my %privileged = ();
 6629:     my $cachetime = 60*60*24;
 6630:     my $now = time;
 6631:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6632:         return %privileged;
 6633:     }
 6634:     foreach my $dom (@{$domains}) {
 6635:         next if (ref($privileged{$dom}) eq 'HASH');
 6636:         my $needroles;
 6637:         foreach my $role (@{$roles}) {
 6638:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6639:             if (defined($cached)) {
 6640:                 if (ref($result) eq 'HASH') {
 6641:                     $privileged{$dom}{$role} = $result;
 6642:                 }
 6643:             } else {
 6644:                 $needroles = 1;
 6645:             }
 6646:         }
 6647:         if ($needroles) {
 6648:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6649:             $privileged{$dom} = {};
 6650:             foreach my $server (keys(%dompersonnel)) {
 6651:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6652:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6653:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6654:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6655:                         next if ($end && $end < $now);
 6656:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6657:                             $dompersonnel{$server}{$item};
 6658:                     }
 6659:                 }
 6660:             }
 6661:             if (ref($privileged{$dom}) eq 'HASH') {
 6662:                 foreach my $role (@{$roles}) {
 6663:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6664:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6665:                     } else {
 6666:                         my %hash = ();
 6667:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6668:                     }
 6669:                 }
 6670:             }
 6671:         }
 6672:     }
 6673:     return %privileged;
 6674: }
 6675: 
 6676: # -------------------------------------------------------- Get user privileges
 6677: 
 6678: sub rolesinit {
 6679:     my ($domain, $username) = @_;
 6680:     my %userroles = ('user.login.time' => time);
 6681:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6682: 
 6683:     # firstaccess and timerinterval are related to timed maps/resources. 
 6684:     # also, blocking can be triggered by an activating timer
 6685:     # it's saved in the user's %env.
 6686:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6687:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6688:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6689:         %timerintchk, %timerintenv);
 6690: 
 6691:     foreach my $key (keys(%firstaccess)) {
 6692:         my ($cid, $rest) = split(/\0/, $key);
 6693:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6694:     }
 6695: 
 6696:     foreach my $key (keys(%timerinterval)) {
 6697:         my ($cid,$rest) = split(/\0/,$key);
 6698:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6699:     }
 6700: 
 6701:     my %allroles=();
 6702:     my %allgroups=();
 6703: 
 6704:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6705:         my $role = $rolesdump{$area};
 6706:         $area =~ s/\_\w\w$//;
 6707: 
 6708:         my ($trole, $tend, $tstart, $group_privs);
 6709: 
 6710:         if ($role =~ /^cr/) {
 6711:         # Custom role, defined by a user 
 6712:         # e.g., user.role.cr/msu/smith/mynewrole
 6713:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6714:                 $trole = $1;
 6715:                 ($tend, $tstart) = split('_', $2);
 6716:             } else {
 6717:                 $trole = $role;
 6718:             }
 6719:         } elsif ($role =~ m|^gr/|) {
 6720:         # Role of member in a group, defined within a course/community
 6721:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6722:             ($trole, $tend, $tstart) = split(/_/, $role);
 6723:             next if $tstart eq '-1';
 6724:             ($trole, $group_privs) = split(/\//, $trole);
 6725:             $group_privs = &unescape($group_privs);
 6726:         } else {
 6727:         # Just a normal role, defined in roles.tab
 6728:             ($trole, $tend, $tstart) = split(/_/,$role);
 6729:         }
 6730: 
 6731:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6732:                  $username);
 6733:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6734: 
 6735:         # role expired or not available yet?
 6736:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6737:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6738: 
 6739:         next if $area eq '' or $trole eq '';
 6740: 
 6741:         my $spec = "$trole.$area";
 6742:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6743: 
 6744:         if ($trole =~ /^cr\//) {
 6745:         # Custom role, defined by a user
 6746:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6747:         } elsif ($trole eq 'gr') {
 6748:         # Role of a member in a group, defined within a course/community
 6749:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6750:             next;
 6751:         } else {
 6752:         # Normal role, defined in roles.tab
 6753:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6754:         }
 6755: 
 6756:         my $cid = $tdomain.'_'.$trest;
 6757:         unless ($firstaccchk{$cid}) {
 6758:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6759:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6760:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6761:                         $coursetimerstarts{$cid}{$item}; 
 6762:                 }
 6763:             }
 6764:             $firstaccchk{$cid} = 1;
 6765:         }
 6766:         unless ($timerintchk{$cid}) {
 6767:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6768:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6769:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6770:                        $coursetimerintervals{$cid}{$item};
 6771:                 }
 6772:             }
 6773:             $timerintchk{$cid} = 1;
 6774:         }
 6775:     }
 6776: 
 6777:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6778:                                                           \%allroles, \%allgroups);
 6779:     $env{'user.adv'} = $userroles{'user.adv'};
 6780:     $env{'user.rar'} = $userroles{'user.rar'};
 6781: 
 6782:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6783: }
 6784: 
 6785: sub set_arearole {
 6786:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6787:     unless ($nolog) {
 6788: # log the associated role with the area
 6789:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6790:     }
 6791:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6792: }
 6793: 
 6794: sub custom_roleprivs {
 6795:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6796:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6797:     my $homsvr = &homeserver($rauthor,$rdomain);
 6798:     if (&hostname($homsvr) ne '') {
 6799:         my ($rdummy,$roledef)=
 6800:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6801:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6802:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6803:             if (defined($syspriv)) {
 6804:                 if ($trest =~ /^$match_community$/) {
 6805:                     $syspriv =~ s/bre\&S//; 
 6806:                 }
 6807:                 $$allroles{'cm./'}.=':'.$syspriv;
 6808:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6809:             }
 6810:             if ($tdomain ne '') {
 6811:                 if (defined($dompriv)) {
 6812:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6813:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6814:                 }
 6815:                 if (($trest ne '') && (defined($coursepriv))) {
 6816:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6817:                         my $rolename = $1;
 6818:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6819:                     }
 6820:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6821:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6822:                 }
 6823:             }
 6824:         }
 6825:     }
 6826: }
 6827: 
 6828: sub course_adhocrole_privs {
 6829:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6830:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6831:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6832:         my (%currprivs,%storeprivs);
 6833:         foreach my $item (split(/:/,$coursepriv)) {
 6834:             my ($priv,$restrict) = split(/\&/,$item);
 6835:             $currprivs{$priv} = $restrict;
 6836:         }
 6837:         my (%possadd,%possremove,%full);
 6838:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6839:             my ($priv,$restrict)=split(/\&/,$item);
 6840:             $full{$priv} = $restrict;
 6841:         }
 6842:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6843:              next if ($item eq '');
 6844:              my ($rule,$rest) = split(/=/,$item);
 6845:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6846:              foreach my $priv (split(/:/,$rest)) {
 6847:                  if ($priv ne '') {
 6848:                      if ($rule eq 'off') {
 6849:                          $possremove{$priv} = 1;
 6850:                      } else {
 6851:                          $possadd{$priv} = 1;
 6852:                      }
 6853:                  }
 6854:              }
 6855:          }
 6856:          foreach my $priv (sort(keys(%full))) {
 6857:              if (exists($currprivs{$priv})) {
 6858:                  unless (exists($possremove{$priv})) {
 6859:                      $storeprivs{$priv} = $currprivs{$priv};
 6860:                  }
 6861:              } elsif (exists($possadd{$priv})) {
 6862:                  $storeprivs{$priv} = $full{$priv};
 6863:              }
 6864:          }
 6865:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6866:      }
 6867:      return $coursepriv;
 6868: }
 6869: 
 6870: sub group_roleprivs {
 6871:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6872:     my $access = 1;
 6873:     my $now = time;
 6874:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6875:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6876:     if ($access) {
 6877:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6878:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6879:     }
 6880: }
 6881: 
 6882: sub standard_roleprivs {
 6883:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6884:     if (defined($pr{$trole.':s'})) {
 6885:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6886:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6887:     }
 6888:     if ($tdomain ne '') {
 6889:         if (defined($pr{$trole.':d'})) {
 6890:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6891:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6892:         }
 6893:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6894:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6895:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6896:         }
 6897:     }
 6898: }
 6899: 
 6900: sub set_userprivs {
 6901:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6902:     my $author=0;
 6903:     my $adv=0;
 6904:     my $rar=0;
 6905:     my %grouproles = ();
 6906:     if (keys(%{$allgroups}) > 0) {
 6907:         my @groupkeys; 
 6908:         foreach my $role (keys(%{$allroles})) {
 6909:             push(@groupkeys,$role);
 6910:         }
 6911:         if (ref($groups_roles) eq 'HASH') {
 6912:             foreach my $key (keys(%{$groups_roles})) {
 6913:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6914:                     push(@groupkeys,$key);
 6915:                 }
 6916:             }
 6917:         }
 6918:         if (@groupkeys > 0) {
 6919:             foreach my $role (@groupkeys) {
 6920:                 my ($trole,$area,$sec,$extendedarea);
 6921:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6922:                     $trole = $1;
 6923:                     $area = $2;
 6924:                     $sec = $3;
 6925:                     $extendedarea = $area.$sec;
 6926:                     if (exists($$allgroups{$area})) {
 6927:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6928:                             my $spec = $trole.'.'.$extendedarea;
 6929:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6930:                                                 $$allgroups{$area}{$group};
 6931:                         }
 6932:                     }
 6933:                 }
 6934:             }
 6935:         }
 6936:     }
 6937:     foreach my $group (keys(%grouproles)) {
 6938:         $$allroles{$group} = $grouproles{$group};
 6939:     }
 6940:     foreach my $role (keys(%{$allroles})) {
 6941:         my %thesepriv;
 6942:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6943:         foreach my $item (split(/:/,$$allroles{$role})) {
 6944:             if ($item ne '') {
 6945:                 my ($privilege,$restrictions)=split(/&/,$item);
 6946:                 if ($restrictions eq '') {
 6947:                     $thesepriv{$privilege}='F';
 6948:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6949:                     $thesepriv{$privilege}.=$restrictions;
 6950:                 }
 6951:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6952:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6953:             }
 6954:         }
 6955:         my $thesestr='';
 6956:         foreach my $priv (sort(keys(%thesepriv))) {
 6957: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6958: 	}
 6959:         $userroles->{'user.priv.'.$role} = $thesestr;
 6960:     }
 6961:     return ($author,$adv,$rar);
 6962: }
 6963: 
 6964: sub role_status {
 6965:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6966:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6967:         my ($one,$two) = split(m{\./},$rolekey,2);
 6968:         (undef,undef,$$role) = split(/\./,$one,3);
 6969:         unless (!defined($$role) || $$role eq '') {
 6970:             $$where = '/'.$two;
 6971:             $$trolecode=$$role.'.'.$$where;
 6972:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6973:             $$tstatus='is';
 6974:             if ($$tstart && $$tstart>$update) {
 6975:                 $$tstatus='future';
 6976:                 if ($$tstart<$now) {
 6977:                     if ($$tstart && $$tstart>$refresh) {
 6978:                         if (($$where ne '') && ($$role ne '')) {
 6979:                             my (%allroles,%allgroups,$group_privs,
 6980:                                 %groups_roles,@rolecodes);
 6981:                             my %userroles = (
 6982:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6983:                             );
 6984:                             @rolecodes = ('cm'); 
 6985:                             my $spec=$$role.'.'.$$where;
 6986:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6987:                             if ($$role =~ /^cr\//) {
 6988:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6989:                                 push(@rolecodes,'cr');
 6990:                             } elsif ($$role eq 'gr') {
 6991:                                 push(@rolecodes,$$role);
 6992:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6993:                                                     $env{'user.name'});
 6994:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6995:                                 (undef,my $group_privs) = split(/\//,$trole);
 6996:                                 $group_privs = &unescape($group_privs);
 6997:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6998:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6999:                                 &get_groups_roles($tdomain,$trest,
 7000:                                                   \%course_roles,\@rolecodes,
 7001:                                                   \%groups_roles);
 7002:                             } else {
 7003:                                 push(@rolecodes,$$role);
 7004:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7005:                             }
 7006:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7007:                                                                    \%groups_roles);
 7008:                             &appenv(\%userroles,\@rolecodes);
 7009:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7010:                         }
 7011:                     }
 7012:                     $$tstatus = 'is';
 7013:                 }
 7014:             }
 7015:             if ($$tend) {
 7016:                 if ($$tend<$update) {
 7017:                     $$tstatus='expired';
 7018:                 } elsif ($$tend<$now) {
 7019:                     $$tstatus='will_not';
 7020:                 }
 7021:             }
 7022:         }
 7023:     }
 7024: }
 7025: 
 7026: sub get_groups_roles {
 7027:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7028:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7029:                   (ref($rolecodes) eq 'ARRAY') && 
 7030:                   (ref($groups_roles) eq 'HASH')); 
 7031:     if (keys(%{$cdom_courseroles}) > 0) {
 7032:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7033:         if ($cdom ne '' && $cnum ne '') {
 7034:             foreach my $key (keys(%{$cdom_courseroles})) {
 7035:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7036:                     my $crsrole = $1;
 7037:                     my $crssec = $2;
 7038:                     if ($crsrole =~ /^cr/) {
 7039:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7040:                             push(@{$rolecodes},'cr');
 7041:                         }
 7042:                     } else {
 7043:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7044:                             push(@{$rolecodes},$crsrole);
 7045:                         }
 7046:                     }
 7047:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7048:                     if ($crssec ne '') {
 7049:                         $rolekey .= "/$crssec";
 7050:                     }
 7051:                     $rolekey .= './';
 7052:                     $groups_roles->{$rolekey} = $rolecodes;
 7053:                 }
 7054:             }
 7055:         }
 7056:     }
 7057:     return;
 7058: }
 7059: 
 7060: sub delete_env_groupprivs {
 7061:     my ($where,$courseroles,$possroles) = @_;
 7062:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7063:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7064:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7065:         %{$courseroles->{$udom}} =
 7066:             &get_my_roles('','','userroles',['active'],
 7067:                           $possroles,[$udom],1);
 7068:     }
 7069:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7070:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7071:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7072:             my $area = '/'.$cdom.'/'.$cnum;
 7073:             my $privkey = "user.priv.$crsrole.$area";
 7074:             if ($crssec ne '') {
 7075:                 $privkey .= '/'.$crssec;
 7076:             }
 7077:             $privkey .= ".$area/$group";
 7078:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7079:         }
 7080:     }
 7081:     return;
 7082: }
 7083: 
 7084: sub check_adhoc_privs {
 7085:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7086:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7087:     if ($sec) {
 7088:         $cckey .= '/'.$sec;
 7089:     } 
 7090:     my $setprivs;
 7091:     if ($env{$cckey}) {
 7092:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7093:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7094:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7095:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7096:             $setprivs = 1;
 7097:         }
 7098:     } else {
 7099:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7100:         $setprivs = 1;
 7101:     }
 7102:     return $setprivs;
 7103: }
 7104: 
 7105: sub set_adhoc_privileges {
 7106: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7107:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7108:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7109:     if ($sec ne '') {
 7110:         $area .= '/'.$sec;
 7111:     }
 7112:     my $spec = $role.'.'.$area;
 7113:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7114:                                   $env{'user.name'},1);
 7115:     my %rolehash = ();
 7116:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7117:         my $rolename = $1;
 7118:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7119:         my %domdef = &get_domain_defaults($dcdom);
 7120:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7121:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7122:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7123:             }
 7124:         }
 7125:     } else {
 7126:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7127:     }
 7128:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7129:     &appenv(\%userroles,[$role,'cm']);
 7130:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7131:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7132:             ($caller eq 'tiny')) {
 7133:         &appenv( {'request.role'        => $spec,
 7134:                   'request.role.domain' => $dcdom,
 7135:                   'request.course.sec'  => $sec,
 7136:                  }
 7137:                );
 7138:         my $tadv=0;
 7139:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7140:         &appenv({'request.role.adv'    => $tadv});
 7141:     }
 7142: }
 7143: 
 7144: # --------------------------------------------------------------- get interface
 7145: 
 7146: sub get {
 7147:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7148:    my $items='';
 7149:    foreach my $item (@$storearr) {
 7150:        $items.=&escape($item).'&';
 7151:    }
 7152:    $items=~s/\&$//;
 7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7154:    if (!$uname) { $uname=$env{'user.name'}; }
 7155:    my $uhome=&homeserver($uname,$udomain);
 7156: 
 7157:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7158:    my @pairs=split(/\&/,$rep);
 7159:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7160:      return @pairs;
 7161:    }
 7162:    my %returnhash=();
 7163:    my $i=0;
 7164:    foreach my $item (@$storearr) {
 7165:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7166:       $i++;
 7167:    }
 7168:    return %returnhash;
 7169: }
 7170: 
 7171: # --------------------------------------------------------------- del interface
 7172: 
 7173: sub del {
 7174:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7175:    my $items='';
 7176:    foreach my $item (@$storearr) {
 7177:        $items.=&escape($item).'&';
 7178:    }
 7179: 
 7180:    $items=~s/\&$//;
 7181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7182:    if (!$uname) { $uname=$env{'user.name'}; }
 7183:    my $uhome=&homeserver($uname,$udomain);
 7184:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7185: }
 7186: 
 7187: # -------------------------------------------------------------- dump interface
 7188: 
 7189: sub unserialize {
 7190:     my ($rep, $escapedkeys) = @_;
 7191: 
 7192:     return {} if $rep =~ /^error/;
 7193: 
 7194:     my %returnhash=();
 7195: 	foreach my $item (split(/\&/,$rep)) {
 7196: 	    my ($key, $value) = split(/=/, $item, 2);
 7197: 	    $key = unescape($key) unless $escapedkeys;
 7198: 	    next if $key =~ /^error: 2 /;
 7199: 	    $returnhash{$key} = &thaw_unescape($value);
 7200: 	}
 7201:     #return %returnhash;
 7202:     return \%returnhash;
 7203: }        
 7204: 
 7205: # see Lond::dump_with_regexp
 7206: # if $escapedkeys hash keys won't get unescaped.
 7207: sub dump {
 7208:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7209:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7210:     if (!$uname) { $uname=$env{'user.name'}; }
 7211:     my $uhome=&homeserver($uname,$udomain);
 7212: 
 7213:     if ($regexp) {
 7214:         $regexp=&escape($regexp);
 7215:     } else {
 7216:         $regexp='.';
 7217:     }
 7218:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7219:         # user is hosted on this machine
 7220:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7221:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7222:         return %{unserialize($reply, $escapedkeys)};
 7223:     }
 7224:     my $rep;
 7225:     if ($encrypt) {
 7226:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7227:     } else {
 7228:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7229:     }
 7230:     my @pairs=split(/\&/,$rep);
 7231:     my %returnhash=();
 7232:     if (!($rep =~ /^error/ )) {
 7233: 	foreach my $item (@pairs) {
 7234: 	    my ($key,$value)=split(/=/,$item,2);
 7235:         $key = unescape($key) unless $escapedkeys;
 7236:         #$key = &unescape($key);
 7237: 	    next if ($key =~ /^error: 2 /);
 7238: 	    $returnhash{$key}=&thaw_unescape($value);
 7239: 	}
 7240:     }
 7241:     return %returnhash;
 7242: }
 7243: 
 7244: 
 7245: # --------------------------------------------------------- dumpstore interface
 7246: 
 7247: sub dumpstore {
 7248:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7249:    # same as dump but keys must be escaped. They may contain colon separated
 7250:    # lists of values that may themself contain colons (e.g. symbs).
 7251:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7252: }
 7253: 
 7254: # -------------------------------------------------------------- keys interface
 7255: 
 7256: sub getkeys {
 7257:    my ($namespace,$udomain,$uname)=@_;
 7258:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7259:    if (!$uname) { $uname=$env{'user.name'}; }
 7260:    my $uhome=&homeserver($uname,$udomain);
 7261:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7262:    my @keyarray=();
 7263:    foreach my $key (split(/\&/,$rep)) {
 7264:       next if ($key =~ /^error: 2 /);
 7265:       push(@keyarray,&unescape($key));
 7266:    }
 7267:    return @keyarray;
 7268: }
 7269: 
 7270: # --------------------------------------------------------------- currentdump
 7271: sub currentdump {
 7272:    my ($courseid,$sdom,$sname)=@_;
 7273:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7274:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7275:    $sname    = $env{'user.name'}         if (! defined($sname));
 7276:    my $uhome = &homeserver($sname,$sdom);
 7277:    my $rep;
 7278: 
 7279:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7280:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7281:                    $courseid)));
 7282:    } else {
 7283:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7284:    }
 7285: 
 7286:    return if ($rep =~ /^(error:|no_such_host)/);
 7287:    #
 7288:    my %returnhash=();
 7289:    #
 7290:    if ($rep eq 'unknown_cmd') {
 7291:        # an old lond will not know currentdump
 7292:        # Do a dump and make it look like a currentdump
 7293:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7294:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7295:        my %hash = @tmp;
 7296:        @tmp=();
 7297:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7298:    } else {
 7299:        my @pairs=split(/\&/,$rep);
 7300:        foreach my $pair (@pairs) {
 7301:            my ($key,$value)=split(/=/,$pair,2);
 7302:            my ($symb,$param) = split(/:/,$key);
 7303:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7304:                                                         &thaw_unescape($value);
 7305:        }
 7306:    }
 7307:    return %returnhash;
 7308: }
 7309: 
 7310: sub convert_dump_to_currentdump{
 7311:     my %hash = %{shift()};
 7312:     my %returnhash;
 7313:     # Code ripped from lond, essentially.  The only difference
 7314:     # here is the unescaping done by lonnet::dump().  Conceivably
 7315:     # we might run in to problems with parameter names =~ /^v\./
 7316:     while (my ($key,$value) = each(%hash)) {
 7317:         my ($v,$symb,$param) = split(/:/,$key);
 7318: 	$symb  = &unescape($symb);
 7319: 	$param = &unescape($param);
 7320:         next if ($v eq 'version' || $symb eq 'keys');
 7321:         next if (exists($returnhash{$symb}) &&
 7322:                  exists($returnhash{$symb}->{$param}) &&
 7323:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7324:         $returnhash{$symb}->{$param}=$value;
 7325:         $returnhash{$symb}->{'v.'.$param}=$v;
 7326:     }
 7327:     #
 7328:     # Remove all of the keys in the hashes which keep track of
 7329:     # the version of the parameter.
 7330:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7331:         # use a foreach because we are going to delete from the hash.
 7332:         foreach my $key (keys(%$param_hash)) {
 7333:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7334:         }
 7335:     }
 7336:     return \%returnhash;
 7337: }
 7338: 
 7339: # ------------------------------------------------------ critical inc interface
 7340: 
 7341: sub cinc {
 7342:     return &inc(@_,'critical');
 7343: }
 7344: 
 7345: # --------------------------------------------------------------- inc interface
 7346: 
 7347: sub inc {
 7348:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7349:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7350:     if (!$uname) { $uname=$env{'user.name'}; }
 7351:     my $uhome=&homeserver($uname,$udomain);
 7352:     my $items='';
 7353:     if (! ref($store)) {
 7354:         # got a single value, so use that instead
 7355:         $items = &escape($store).'=&';
 7356:     } elsif (ref($store) eq 'SCALAR') {
 7357:         $items = &escape($$store).'=&';        
 7358:     } elsif (ref($store) eq 'ARRAY') {
 7359:         $items = join('=&',map {&escape($_);} @{$store});
 7360:     } elsif (ref($store) eq 'HASH') {
 7361:         while (my($key,$value) = each(%{$store})) {
 7362:             $items.= &escape($key).'='.&escape($value).'&';
 7363:         }
 7364:     }
 7365:     $items=~s/\&$//;
 7366:     if ($critical) {
 7367: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7368:     } else {
 7369: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7370:     }
 7371: }
 7372: 
 7373: # --------------------------------------------------------------- put interface
 7374: 
 7375: sub put {
 7376:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7377:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7378:    if (!$uname) { $uname=$env{'user.name'}; }
 7379:    my $uhome=&homeserver($uname,$udomain);
 7380:    my $items='';
 7381:    foreach my $item (keys(%$storehash)) {
 7382:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7383:    }
 7384:    $items=~s/\&$//;
 7385:    if ($encrypt) {
 7386:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7387:    } else {
 7388:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7389:    }
 7390: }
 7391: 
 7392: # ------------------------------------------------------------ newput interface
 7393: 
 7394: sub newput {
 7395:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7397:    if (!$uname) { $uname=$env{'user.name'}; }
 7398:    my $uhome=&homeserver($uname,$udomain);
 7399:    my $items='';
 7400:    foreach my $key (keys(%$storehash)) {
 7401:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7402:    }
 7403:    $items=~s/\&$//;
 7404:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7405: }
 7406: 
 7407: # ---------------------------------------------------------  putstore interface
 7408: 
 7409: sub putstore {
 7410:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7411:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7412:    if (!$uname) { $uname=$env{'user.name'}; }
 7413:    my $uhome=&homeserver($uname,$udomain);
 7414:    my $items='';
 7415:    foreach my $key (keys(%$storehash)) {
 7416:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7417:    }
 7418:    $items=~s/\&$//;
 7419:    my $esc_symb=&escape($symb);
 7420:    my $esc_v=&escape($version);
 7421:    my $reply =
 7422:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7423: 	      $uhome);
 7424:    if (($tolog) && ($reply eq 'ok')) {
 7425:        my $namevalue='';
 7426:        foreach my $key (keys(%{$storehash})) {
 7427:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7428:        }
 7429:        my $ip = &get_requestor_ip();
 7430:        $namevalue .= 'ip='.&escape($ip).
 7431:                      '&host='.&escape($perlvar{'lonHostID'}).
 7432:                      '&version='.$esc_v.
 7433:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7434:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7435:    }
 7436:    if ($reply eq 'unknown_cmd') {
 7437:        # gfall back to way things use to be done
 7438:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7439: 			    $uname);
 7440:    }
 7441:    return $reply;
 7442: }
 7443: 
 7444: sub old_putstore {
 7445:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7446:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7447:     if (!$uname) { $uname=$env{'user.name'}; }
 7448:     my $uhome=&homeserver($uname,$udomain);
 7449:     my %newstorehash;
 7450:     foreach my $item (keys(%$storehash)) {
 7451: 	my $key = $version.':'.&escape($symb).':'.$item;
 7452: 	$newstorehash{$key} = $storehash->{$item};
 7453:     }
 7454:     my $items='';
 7455:     my %allitems = ();
 7456:     foreach my $item (keys(%newstorehash)) {
 7457: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7458: 	    my $key = $1.':keys:'.$2;
 7459: 	    $allitems{$key} .= $3.':';
 7460: 	}
 7461: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7462:     }
 7463:     foreach my $item (keys(%allitems)) {
 7464: 	$allitems{$item} =~ s/\:$//;
 7465: 	$items.= $item.'='.$allitems{$item}.'&';
 7466:     }
 7467:     $items=~s/\&$//;
 7468:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7469: }
 7470: 
 7471: # ------------------------------------------------------ critical put interface
 7472: 
 7473: sub cput {
 7474:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7475:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7476:    if (!$uname) { $uname=$env{'user.name'}; }
 7477:    my $uhome=&homeserver($uname,$udomain);
 7478:    my $items='';
 7479:    foreach my $item (keys(%$storehash)) {
 7480:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7481:    }
 7482:    $items=~s/\&$//;
 7483:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7484: }
 7485: 
 7486: # -------------------------------------------------------------- eget interface
 7487: 
 7488: sub eget {
 7489:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7490:    my $items='';
 7491:    foreach my $item (@$storearr) {
 7492:        $items.=&escape($item).'&';
 7493:    }
 7494:    $items=~s/\&$//;
 7495:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7496:    if (!$uname) { $uname=$env{'user.name'}; }
 7497:    my $uhome=&homeserver($uname,$udomain);
 7498:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7499:    my @pairs=split(/\&/,$rep);
 7500:    my %returnhash=();
 7501:    my $i=0;
 7502:    foreach my $item (@$storearr) {
 7503:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7504:       $i++;
 7505:    }
 7506:    return %returnhash;
 7507: }
 7508: 
 7509: # ------------------------------------------------------------ tmpput interface
 7510: sub tmpput {
 7511:     my ($storehash,$server,$context)=@_;
 7512:     my $items='';
 7513:     foreach my $item (keys(%$storehash)) {
 7514: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7515:     }
 7516:     $items=~s/\&$//;
 7517:     if (defined($context)) {
 7518:         $items .= ':'.&escape($context);
 7519:     }
 7520:     return &reply("tmpput:$items",$server);
 7521: }
 7522: 
 7523: # ------------------------------------------------------------ tmpget interface
 7524: sub tmpget {
 7525:     my ($token,$server)=@_;
 7526:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7527:     my $rep=&reply("tmpget:$token",$server);
 7528:     my %returnhash;
 7529:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7530:         return %returnhash;
 7531:     }
 7532:     foreach my $item (split(/\&/,$rep)) {
 7533: 	my ($key,$value)=split(/=/,$item);
 7534: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7535:     }
 7536:     return %returnhash;
 7537: }
 7538: 
 7539: # ------------------------------------------------------------ tmpdel interface
 7540: sub tmpdel {
 7541:     my ($token,$server)=@_;
 7542:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7543:     return &reply("tmpdel:$token",$server);
 7544: }
 7545: 
 7546: # ------------------------------------------------------------ get_timebased_id 
 7547: 
 7548: sub get_timebased_id {
 7549:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7550:         $maxtries) = @_;
 7551:     my ($newid,$error,$dellock);
 7552:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7553:         return ('','ok','invalid call to get suffix');
 7554:     }
 7555: 
 7556: # set defaults for any optional args for which values were not supplied
 7557:     if ($who eq '') {
 7558:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7559:     }
 7560:     if (!$locktries) {
 7561:         $locktries = 3;
 7562:     }
 7563:     if (!$maxtries) {
 7564:         $maxtries = 10;
 7565:     }
 7566:     
 7567:     if (($cdom eq '') || ($cnum eq '')) {
 7568:         if ($env{'request.course.id'}) {
 7569:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7570:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7571:         }
 7572:         if (($cdom eq '') || ($cnum eq '')) {
 7573:             return ('','ok','call to get suffix not in course context');
 7574:         }
 7575:     }
 7576: 
 7577: # construct locking item
 7578:     my $lockhash = {
 7579:                       $prefix."\0".'locked_'.$keyid => $who,
 7580:                    };
 7581:     my $tries = 0;
 7582: 
 7583: # attempt to get lock on nohist_$namespace file
 7584:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7585:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7586:         $tries ++;
 7587:         sleep 1;
 7588:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7589:     }
 7590: 
 7591: # attempt to get unique identifier, based on current timestamp
 7592:     if ($gotlock eq 'ok') {
 7593:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7594:         my $id = time;
 7595:         $newid = $id;
 7596:         if ($idtype eq 'addcode') {
 7597:             $newid .= &sixnum_code();
 7598:         }
 7599:         my $idtries = 0;
 7600:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7601:             if ($idtype eq 'concat') {
 7602:                 $newid = $id.$idtries;
 7603:             } elsif ($idtype eq 'addcode') {
 7604:                 $newid = $newid.&sixnum_code();
 7605:             } else {
 7606:                 $newid ++;
 7607:             }
 7608:             $idtries ++;
 7609:         }
 7610:         if (!exists($inuse{$prefix."\0".$newid})) {
 7611:             my %new_item =  (
 7612:                               $prefix."\0".$newid => $who,
 7613:                             );
 7614:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7615:                                                  $cdom,$cnum);
 7616:             if ($putresult ne 'ok') {
 7617:                 undef($newid);
 7618:                 $error = 'error saving new item: '.$putresult;
 7619:             }
 7620:         } else {
 7621:              undef($newid);
 7622:              $error = ('error: no unique suffix available for the new item ');
 7623:         }
 7624: #  remove lock
 7625:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7626:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7627:     } else {
 7628:         $error = "error: could not obtain lockfile\n";
 7629:         $dellock = 'ok';
 7630:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7631:             $dellock = 'nolock';
 7632:         }
 7633:     }
 7634:     return ($newid,$dellock,$error);
 7635: }
 7636: 
 7637: sub sixnum_code {
 7638:     my $code;
 7639:     for (0..6) {
 7640:         $code .= int( rand(9) );
 7641:     }
 7642:     return $code;
 7643: }
 7644: 
 7645: # -------------------------------------------------- portfolio access checking
 7646: 
 7647: sub portfolio_access {
 7648:     my ($requrl,$clientip) = @_;
 7649:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7650:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7651:     if ($result) {
 7652:         my %setters;
 7653:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7654:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7655:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7656:             if (($startblock && $endblock) || ($by_ip)) {
 7657:                 return 'B';
 7658:             }
 7659:         } else {
 7660:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7661:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7662:             if (($startblock && $endblock) || ($by_ip)) {
 7663:                 return 'B';
 7664:             }
 7665:         }
 7666:     }
 7667:     if ($result eq 'ok') {
 7668:        return 'F';
 7669:     } elsif ($result =~ /^[^:]+:guest_/) {
 7670:        return 'A';
 7671:     }
 7672:     return '';
 7673: }
 7674: 
 7675: sub get_portfolio_access {
 7676:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7677: 
 7678:     if (!ref($access_hash)) {
 7679: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7680: 	my %access_controls = &get_access_controls($current_perms,$group,
 7681: 						   $file_name);
 7682: 	$access_hash = $access_controls{$file_name};
 7683:     }
 7684: 
 7685:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7686:     my $now = time;
 7687:     if (ref($access_hash) eq 'HASH') {
 7688:         foreach my $key (keys(%{$access_hash})) {
 7689:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7690:             if ($start > $now) {
 7691:                 next;
 7692:             }
 7693:             if ($end && $end<$now) {
 7694:                 next;
 7695:             }
 7696:             if ($scope eq 'public') {
 7697:                 $public = $key;
 7698:                 last;
 7699:             } elsif ($scope eq 'guest') {
 7700:                 $guest = $key;
 7701:             } elsif ($scope eq 'domains') {
 7702:                 push(@domains,$key);
 7703:             } elsif ($scope eq 'users') {
 7704:                 push(@users,$key);
 7705:             } elsif ($scope eq 'course') {
 7706:                 push(@courses,$key);
 7707:             } elsif ($scope eq 'group') {
 7708:                 push(@groups,$key);
 7709:             } elsif ($scope eq 'ip') {
 7710:                 push(@ips,$key);
 7711:             }
 7712:         }
 7713:         if ($public) {
 7714:             return 'ok';
 7715:         } elsif (@ips > 0) {
 7716:             my $allowed;
 7717:             foreach my $ipkey (@ips) {
 7718:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7719:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7720:                         $allowed = 1;
 7721:                         last; 
 7722:                     }
 7723:                 }
 7724:             }
 7725:             if ($allowed) {
 7726:                 return 'ok';
 7727:             }
 7728:         }
 7729:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7730:             if ($guest) {
 7731:                 return $guest;
 7732:             }
 7733:         } else {
 7734:             if (@domains > 0) {
 7735:                 foreach my $domkey (@domains) {
 7736:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7737:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7738:                             return 'ok';
 7739:                         }
 7740:                     }
 7741:                 }
 7742:             }
 7743:             if (@users > 0) {
 7744:                 foreach my $userkey (@users) {
 7745:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7746:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7747:                             if (ref($item) eq 'HASH') {
 7748:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7749:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7750:                                     return 'ok';
 7751:                                 }
 7752:                             }
 7753:                         }
 7754:                     } 
 7755:                 }
 7756:             }
 7757:             my %roleshash;
 7758:             my @courses_and_groups = @courses;
 7759:             push(@courses_and_groups,@groups); 
 7760:             if (@courses_and_groups > 0) {
 7761:                 my (%allgroups,%allroles); 
 7762:                 my ($start,$end,$role,$sec,$group);
 7763:                 foreach my $envkey (%env) {
 7764:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7765:                         my $cid = $2.'_'.$3; 
 7766:                         if ($1 eq 'gr') {
 7767:                             $group = $4;
 7768:                             $allgroups{$cid}{$group} = $env{$envkey};
 7769:                         } else {
 7770:                             if ($4 eq '') {
 7771:                                 $sec = 'none';
 7772:                             } else {
 7773:                                 $sec = $4;
 7774:                             }
 7775:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7776:                         }
 7777:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7778:                         my $cid = $2.'_'.$3;
 7779:                         if ($4 eq '') {
 7780:                             $sec = 'none';
 7781:                         } else {
 7782:                             $sec = $4;
 7783:                         }
 7784:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7785:                     }
 7786:                 }
 7787:                 if (keys(%allroles) == 0) {
 7788:                     return;
 7789:                 }
 7790:                 foreach my $key (@courses_and_groups) {
 7791:                     my %content = %{$$access_hash{$key}};
 7792:                     my $cnum = $content{'number'};
 7793:                     my $cdom = $content{'domain'};
 7794:                     my $cid = $cdom.'_'.$cnum;
 7795:                     if (!exists($allroles{$cid})) {
 7796:                         next;
 7797:                     }    
 7798:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7799:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7800:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7801:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7802:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7803:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7804:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7805:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7806:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7807:                                         if (grep/^all$/,@sections) {
 7808:                                             return 'ok';
 7809:                                         } else {
 7810:                                             if (grep/^$sec$/,@sections) {
 7811:                                                 return 'ok';
 7812:                                             }
 7813:                                         }
 7814:                                     }
 7815:                                 }
 7816:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7817:                                     if (grep/^none$/,@groups) {
 7818:                                         return 'ok';
 7819:                                     }
 7820:                                 } else {
 7821:                                     if (grep/^all$/,@groups) {
 7822:                                         return 'ok';
 7823:                                     } 
 7824:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7825:                                         if (grep/^$group$/,@groups) {
 7826:                                             return 'ok';
 7827:                                         }
 7828:                                     }
 7829:                                 } 
 7830:                             }
 7831:                         }
 7832:                     }
 7833:                 }
 7834:             }
 7835:             if ($guest) {
 7836:                 return $guest;
 7837:             }
 7838:         }
 7839:     }
 7840:     return;
 7841: }
 7842: 
 7843: sub course_group_datechecker {
 7844:     my ($dates,$now,$status) = @_;
 7845:     my ($start,$end) = split(/\./,$dates);
 7846:     if (!$start && !$end) {
 7847:         return 'ok';
 7848:     }
 7849:     if (grep/^active$/,@{$status}) {
 7850:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7851:             return 'ok';
 7852:         }
 7853:     }
 7854:     if (grep/^previous$/,@{$status}) {
 7855:         if ($end > $now ) {
 7856:             return 'ok';
 7857:         }
 7858:     }
 7859:     if (grep/^future$/,@{$status}) {
 7860:         if ($start > $now) {
 7861:             return 'ok';
 7862:         }
 7863:     }
 7864:     return; 
 7865: }
 7866: 
 7867: sub parse_portfolio_url {
 7868:     my ($url) = @_;
 7869: 
 7870:     my ($type,$udom,$unum,$group,$file_name);
 7871:     
 7872:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7873: 	$type = 1;
 7874:         $udom = $1;
 7875:         $unum = $2;
 7876:         $file_name = $3;
 7877:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7878: 	$type = 2;
 7879:         $udom = $1;
 7880:         $unum = $2;
 7881:         $group = $3;
 7882:         $file_name = $3.'/'.$4;
 7883:     }
 7884:     if (wantarray) {
 7885: 	return ($type,$udom,$unum,$file_name,$group);
 7886:     }
 7887:     return $type;
 7888: }
 7889: 
 7890: sub is_portfolio_url {
 7891:     my ($url) = @_;
 7892:     return scalar(&parse_portfolio_url($url));
 7893: }
 7894: 
 7895: sub is_portfolio_file {
 7896:     my ($file) = @_;
 7897:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7898:         return 1;
 7899:     }
 7900:     return;
 7901: }
 7902: 
 7903: sub usertools_access {
 7904:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7905:     my ($access,%tools);
 7906:     if ($context eq '') {
 7907:         $context = 'tools';
 7908:     }
 7909:     if ($context eq 'requestcourses') {
 7910:         %tools = (
 7911:                       official   => 1,
 7912:                       unofficial => 1,
 7913:                       community  => 1,
 7914:                       textbook   => 1,
 7915:                       placement  => 1,
 7916:                       lti        => 1,
 7917:                  );
 7918:     } elsif ($context eq 'requestauthor') {
 7919:         %tools = (
 7920:                       requestauthor => 1,
 7921:                  );
 7922:     } else {
 7923:         %tools = (
 7924:                       aboutme   => 1,
 7925:                       blog      => 1,
 7926:                       webdav    => 1,
 7927:                       portfolio => 1,
 7928:                  );
 7929:     }
 7930:     return if (!defined($tools{$tool}));
 7931: 
 7932:     if (($udom eq '') || ($uname eq '')) {
 7933:         $udom = $env{'user.domain'};
 7934:         $uname = $env{'user.name'};
 7935:     }
 7936: 
 7937:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7938:         if ($action ne 'reload') {
 7939:             if ($context eq 'requestcourses') {
 7940:                 return $env{'environment.canrequest.'.$tool};
 7941:             } elsif ($context eq 'requestauthor') {
 7942:                 return $env{'environment.canrequest.author'};
 7943:             } else {
 7944:                 return $env{'environment.availabletools.'.$tool};
 7945:             }
 7946:         }
 7947:     }
 7948: 
 7949:     my ($toolstatus,$inststatus,$envkey);
 7950:     if ($context eq 'requestauthor') {
 7951:         $envkey = $context; 
 7952:     } else {
 7953:         $envkey = $context.'.'.$tool;
 7954:     }
 7955: 
 7956:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7957:          ($action ne 'reload')) {
 7958:         $toolstatus = $env{'environment.'.$envkey};
 7959:         $inststatus = $env{'environment.inststatus'};
 7960:     } else {
 7961:         if (ref($userenvref) eq 'HASH') {
 7962:             $toolstatus = $userenvref->{$envkey};
 7963:             $inststatus = $userenvref->{'inststatus'};
 7964:         } else {
 7965:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7966:             $toolstatus = $userenv{$envkey};
 7967:             $inststatus = $userenv{'inststatus'};
 7968:         }
 7969:     }
 7970: 
 7971:     if ($toolstatus ne '') {
 7972:         if ($toolstatus) {
 7973:             $access = 1;
 7974:         } else {
 7975:             $access = 0;
 7976:         }
 7977:         return $access;
 7978:     }
 7979: 
 7980:     my ($is_adv,%domdef);
 7981:     if (ref($is_advref) eq 'HASH') {
 7982:         $is_adv = $is_advref->{'is_adv'};
 7983:     } else {
 7984:         $is_adv = &is_advanced_user($udom,$uname);
 7985:     }
 7986:     if (ref($domdefref) eq 'HASH') {
 7987:         %domdef = %{$domdefref};
 7988:     } else {
 7989:         %domdef = &get_domain_defaults($udom);
 7990:     }
 7991:     if (ref($domdef{$tool}) eq 'HASH') {
 7992:         if ($is_adv) {
 7993:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7994:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7995:                     $access = 1;
 7996:                 } else {
 7997:                     $access = 0;
 7998:                 }
 7999:                 return $access;
 8000:             }
 8001:         }
 8002:         if ($inststatus ne '') {
 8003:             my ($hasaccess,$hasnoaccess);
 8004:             foreach my $affiliation (split(/:/,$inststatus)) {
 8005:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8006:                     if ($domdef{$tool}{$affiliation}) {
 8007:                         $hasaccess = 1;
 8008:                     } else {
 8009:                         $hasnoaccess = 1;
 8010:                     }
 8011:                 }
 8012:             }
 8013:             if ($hasaccess || $hasnoaccess) {
 8014:                 if ($hasaccess) {
 8015:                     $access = 1;
 8016:                 } elsif ($hasnoaccess) {
 8017:                     $access = 0; 
 8018:                 }
 8019:                 return $access;
 8020:             }
 8021:         } else {
 8022:             if ($domdef{$tool}{'default'} ne '') {
 8023:                 if ($domdef{$tool}{'default'}) {
 8024:                     $access = 1;
 8025:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8026:                     $access = 0;
 8027:                 }
 8028:                 return $access;
 8029:             }
 8030:         }
 8031:     } else {
 8032:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8033:             $access = 1;
 8034:         } else {
 8035:             $access = 0;
 8036:         }
 8037:         return $access;
 8038:     }
 8039: }
 8040: 
 8041: sub is_course_owner {
 8042:     my ($cdom,$cnum,$udom,$uname) = @_;
 8043:     if (($udom eq '') || ($uname eq '')) {
 8044:         $udom = $env{'user.domain'};
 8045:         $uname = $env{'user.name'};
 8046:     }
 8047:     unless (($udom eq '') || ($uname eq '')) {
 8048:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8049:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8050:                 return 1;
 8051:             } else {
 8052:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 8053:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8054:                     return 1;
 8055:                 }
 8056:             }
 8057:         }
 8058:     }
 8059:     return;
 8060: }
 8061: 
 8062: sub is_advanced_user {
 8063:     my ($udom,$uname) = @_;
 8064:     if ($udom ne '' && $uname ne '') {
 8065:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8066:             if (wantarray) {
 8067:                 return ($env{'user.adv'},$env{'user.author'});
 8068:             } else {
 8069:                 return $env{'user.adv'};
 8070:             }
 8071:         }
 8072:     }
 8073:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8074:     my %allroles;
 8075:     my ($is_adv,$is_author);
 8076:     foreach my $role (keys(%roleshash)) {
 8077:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8078:         my $area = '/'.$tdomain.'/'.$trest;
 8079:         if ($sec ne '') {
 8080:             $area .= '/'.$sec;
 8081:         }
 8082:         if (($area ne '') && ($trole ne '')) {
 8083:             my $spec=$trole.'.'.$area;
 8084:             if ($trole =~ /^cr\//) {
 8085:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8086:             } elsif ($trole ne 'gr') {
 8087:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8088:             }
 8089:             if ($trole eq 'au') {
 8090:                 $is_author = 1;
 8091:             }
 8092:         }
 8093:     }
 8094:     foreach my $role (keys(%allroles)) {
 8095:         last if ($is_adv);
 8096:         foreach my $item (split(/:/,$allroles{$role})) {
 8097:             if ($item ne '') {
 8098:                 my ($privilege,$restrictions)=split(/&/,$item);
 8099:                 if ($privilege eq 'adv') {
 8100:                     $is_adv = 1;
 8101:                     last;
 8102:                 }
 8103:             }
 8104:         }
 8105:     }
 8106:     if (wantarray) {
 8107:         return ($is_adv,$is_author);
 8108:     }
 8109:     return $is_adv;
 8110: }
 8111: 
 8112: sub check_can_request {
 8113:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8114:     my $canreq = 0;
 8115:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8116:         $uname = $env{'user.name'};
 8117:         $udom = $env{'user.domain'};
 8118:     }
 8119:     my ($types,$typename) = &Apache::loncommon::course_types();
 8120:     my @options = ('approval','validate','autolimit');
 8121:     my $optregex = join('|',@options);
 8122:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8123:         foreach my $type (@{$types}) {
 8124:             if (&usertools_access($uname,$udom,$type,undef,
 8125:                                   'requestcourses')) {
 8126:                 $canreq ++;
 8127:                 if (ref($request_domains) eq 'HASH') {
 8128:                     push(@{$request_domains->{$type}},$udom);
 8129:                 }
 8130:                 if ($dom eq $udom) {
 8131:                     $can_request->{$type} = 1;
 8132:                 }
 8133:             }
 8134:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8135:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8136:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8137:                 if (@curr > 0) {
 8138:                     foreach my $item (@curr) {
 8139:                         if (ref($request_domains) eq 'HASH') {
 8140:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8141:                             if ($otherdom ne '') {
 8142:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 8143:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8144:                                         push(@{$request_domains->{$type}},$otherdom);
 8145:                                     }
 8146:                                 } else {
 8147:                                     push(@{$request_domains->{$type}},$otherdom);
 8148:                                 }
 8149:                             }
 8150:                         }
 8151:                     }
 8152:                     unless ($dom eq $env{'user.domain'}) {
 8153:                         $canreq ++;
 8154:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8155:                             $can_request->{$type} = 1;
 8156:                         }
 8157:                     }
 8158:                 }
 8159:             }
 8160:         }
 8161:     }
 8162:     return $canreq;
 8163: }
 8164: 
 8165: # ---------------------------------------------- Custom access rule evaluation
 8166: 
 8167: sub customaccess {
 8168:     my ($priv,$uri)=@_;
 8169:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8170:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8171:     $udom = &LONCAPA::clean_domain($udom);
 8172:     $ucrs = &LONCAPA::clean_username($ucrs);
 8173:     my $access=0;
 8174:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8175: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8176: 	if ($type eq 'user') {
 8177: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8178: 		my ($tdom,$tuname)=split(m{/},$scope);
 8179: 		if ($tdom) {
 8180: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8181: 		}
 8182: 		if ($tuname) {
 8183: 		    if ($tuname ne $env{'user.name'}) { next; }
 8184: 		}
 8185: 		$access=($effect eq 'allow');
 8186: 		last;
 8187: 	    }
 8188: 	} else {
 8189: 	    if ($role) {
 8190: 		if ($role ne $urole) { next; }
 8191: 	    }
 8192: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8193: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8194: 		if ($tdom) {
 8195: 		    if ($tdom ne $udom) { next; }
 8196: 		}
 8197: 		if ($tcrs) {
 8198: 		    if ($tcrs ne $ucrs) { next; }
 8199: 		}
 8200: 		if ($tsec) {
 8201: 		    if ($tsec ne $usec) { next; }
 8202: 		}
 8203: 		$access=($effect eq 'allow');
 8204: 		last;
 8205: 	    }
 8206: 	    if ($realm eq '' && $role eq '') {
 8207: 		$access=($effect eq 'allow');
 8208: 	    }
 8209: 	}
 8210:     }
 8211:     return $access;
 8212: }
 8213: 
 8214: # ------------------------------------------------- Check for a user privilege
 8215: 
 8216: sub allowed {
 8217:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8218:     my $ver_orguri=$uri;
 8219:     $uri=&deversion($uri);
 8220:     my $orguri=$uri;
 8221:     $uri=&declutter($uri);
 8222: 
 8223:     if ($priv eq 'evb') {
 8224: # Evade communication block restrictions for specified role in a course or domain
 8225:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8226:             return $1;
 8227:         } else {
 8228:             return;
 8229:         }
 8230:     }
 8231: 
 8232:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8233: # Free bre access to adm and meta resources
 8234:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8235: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8236: 	&& ($priv eq 'bre')) {
 8237: 	return 'F';
 8238:     }
 8239: 
 8240: # Free bre access to user's own portfolio contents
 8241:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8242:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8243: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8244:         my %setters;
 8245:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8246:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8247:         if (($startblock && $endblock) || ($by_ip)) {
 8248:             return 'B';
 8249:         } else {
 8250:             return 'F';
 8251:         }
 8252:     }
 8253: 
 8254: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8255:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8256:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8257:         if (exists($env{'request.course.id'})) {
 8258:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8259:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8260:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8261:                 my $courseprivid=$env{'request.course.id'};
 8262:                 $courseprivid=~s/\_/\//;
 8263:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8264:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8265:                     return $1; 
 8266:                 } else {
 8267:                     if ($env{'request.course.sec'}) {
 8268:                         $courseprivid.='/'.$env{'request.course.sec'};
 8269:                     }
 8270:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8271:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8272:                         return $2;
 8273:                     }
 8274:                 }
 8275:             }
 8276:         }
 8277:     }
 8278: 
 8279: # Free bre to public access
 8280: 
 8281:     if ($priv eq 'bre') {
 8282:         my $copyright;
 8283:         unless ($uri =~ /ext\.tool/) {
 8284:             $copyright=&metadata($uri,'copyright');
 8285:         }
 8286: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8287:            return 'F'; 
 8288:         }
 8289:         if ($copyright eq 'priv') {
 8290:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8291: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8292: 		return '';
 8293:             }
 8294:         }
 8295:         if ($copyright eq 'domain') {
 8296:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8297: 	    unless (($env{'user.domain'} eq $1) ||
 8298:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8299: 		return '';
 8300:             }
 8301:         }
 8302:         if ($env{'request.role'}=~ /li\.\//) {
 8303:             # Library role, so allow browsing of resources in this domain.
 8304:             return 'F';
 8305:         }
 8306:         if ($copyright eq 'custom') {
 8307: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8308:         }
 8309:     }
 8310:     # Domain coordinator is trying to create a course
 8311:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8312:         # uri is the requested domain in this case.
 8313:         # comparison to 'request.role.domain' shows if the user has selected
 8314:         # a role of dc for the domain in question.
 8315:         return 'F' if ($uri eq $env{'request.role.domain'});
 8316:     }
 8317: 
 8318:     my $thisallowed='';
 8319:     my $statecond=0;
 8320:     my $courseprivid='';
 8321: 
 8322:     my $ownaccess;
 8323:     # Community Coordinator or Assistant Co-author browsing resource space.
 8324:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8325:         if ($uri eq '') {
 8326:             $ownaccess = 1;
 8327:         } else {
 8328:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8329:                 my $udom = $env{'user.domain'};
 8330:                 my $uname = $env{'user.name'};
 8331:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8332:                     $ownaccess = 1;
 8333:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8334:                     unless ($uri =~ m{\.\./}) {
 8335:                         $ownaccess = 1;
 8336:                     }
 8337:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8338:                     my $now = time;
 8339:                     if ($uri =~ m{^([^/]+)/?$}) {
 8340:                         my $adom = $1;
 8341:                         foreach my $key (keys(%env)) {
 8342:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8343:                                 my ($start,$end) = split(/\./,$env{$key});
 8344:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8345:                                     $ownaccess = 1;
 8346:                                     last;
 8347:                                 }
 8348:                             }
 8349:                         }
 8350:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8351:                         my $adom = $1;
 8352:                         my $aname = $2;
 8353:                         foreach my $role ('ca','aa') { 
 8354:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8355:                                 my ($start,$end) =
 8356:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8357:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8358:                                     $ownaccess = 1;
 8359:                                     last;
 8360:                                 }
 8361:                             }
 8362:                         }
 8363:                     }
 8364:                 }
 8365:             }
 8366:         }
 8367:     }
 8368: 
 8369: # Course
 8370: 
 8371:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8372:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8373:             $thisallowed.=$1;
 8374:         }
 8375:     }
 8376: 
 8377: # Domain
 8378: 
 8379:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8380:        =~/\Q$priv\E\&([^\:]*)/) {
 8381:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8382:             $thisallowed.=$1;
 8383:         }
 8384:     }
 8385: 
 8386: # User who is not author or co-author might still be able to edit
 8387: # resource of an author in the domain (e.g., if Domain Coordinator).
 8388:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8389:         (&allowed('mdc',$env{'request.course.id'}))) {
 8390:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8391:             $thisallowed.=$1;
 8392:         }
 8393:     }
 8394: 
 8395: # Course: uri itself is a course
 8396:     my $courseuri=$uri;
 8397:     $courseuri=~s/\_(\d)/\/$1/;
 8398:     $courseuri=~s/^([^\/])/\/$1/;
 8399: 
 8400:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8401:        =~/\Q$priv\E\&([^\:]*)/) {
 8402:         if ($priv eq 'mip') {
 8403:             my $rem = $1;
 8404:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8405:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8406:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8407:                 if ($cdom ne '') {
 8408:                     my %passwdconf = &get_passwdconf($cdom);
 8409:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8410:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8411:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8412:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8413:                                 unless (@inststatuses) {
 8414:                                     @inststatuses = ('default');
 8415:                                 }
 8416:                                 foreach my $status (@inststatuses) {
 8417:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8418:                                         $thisallowed.=$rem;
 8419:                                     }
 8420:                                 }
 8421:                             }
 8422:                         }
 8423:                     }
 8424:                 }
 8425:             }
 8426:         } else {
 8427:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8428:                 $thisallowed.=$1;
 8429:             }
 8430:         }
 8431:     }
 8432: 
 8433: # URI is an uploaded document for this course, default permissions don't matter
 8434: # not allowing 'edit' access (editupload) to uploaded course docs
 8435:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8436: 	$thisallowed='';
 8437:         my ($match)=&is_on_map($uri);
 8438:         if ($match) {
 8439:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8440:                   =~/\Q$priv\E\&([^\:]*)/) {
 8441:                 my $value = $1;
 8442:                 my $deeplinkblock;
 8443:                 unless ($nodeeplinkcheck) {
 8444:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8445:                 }
 8446:                 if ($deeplinkblock) {
 8447:                     $thisallowed='D';
 8448:                 } elsif ($noblockcheck) {
 8449:                     $thisallowed.=$value;
 8450:                 } else {
 8451:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8452:                     if (@blockers > 0) {
 8453:                         $thisallowed = 'B';
 8454:                     } else {
 8455:                         $thisallowed.=$value;
 8456:                     }
 8457:                 }
 8458:             }
 8459:         } else {
 8460:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8461:             if ($refuri) {
 8462:                 if ($refuri =~ m|^/adm/|) {
 8463:                     $thisallowed='F';
 8464:                 } else {
 8465:                     $refuri=&declutter($refuri);
 8466:                     my ($match) = &is_on_map($refuri);
 8467:                     if ($match) {
 8468:                         my $deeplinkblock;
 8469:                         unless ($nodeeplinkcheck) {
 8470:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8471:                         }
 8472:                         if ($deeplinkblock) {
 8473:                             $thisallowed='D';
 8474:                         } elsif ($noblockcheck) {
 8475:                             $thisallowed='F';
 8476:                         } else {
 8477:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8478:                             if (@blockers > 0) {
 8479:                                 $thisallowed = 'B';
 8480:                             } else {
 8481:                                 $thisallowed='F';
 8482:                             }
 8483:                         }
 8484:                     }
 8485:                 }
 8486:             }
 8487:         }
 8488:     }
 8489: 
 8490:     if ($priv eq 'bre'
 8491: 	&& $thisallowed ne 'F' 
 8492: 	&& $thisallowed ne '2'
 8493: 	&& &is_portfolio_url($uri)) {
 8494: 	$thisallowed = &portfolio_access($uri,$clientip);
 8495:     }
 8496: 
 8497: # Full access at system, domain or course-wide level? Exit.
 8498:     if ($thisallowed=~/F/) {
 8499: 	return 'F';
 8500:     }
 8501: 
 8502: # If this is generating or modifying users, exit with special codes
 8503: 
 8504:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8505: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8506: 	    my ($audom,$auname)=split('/',$uri);
 8507: # no author name given, so this just checks on the general right to make a co-author in this domain
 8508: 	    unless ($auname) { return $thisallowed; }
 8509: # an author name is given, so we are about to actually make a co-author for a certain account
 8510: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8511: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8512: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8513: 	}
 8514: 	return $thisallowed;
 8515:     }
 8516: #
 8517: # Gathered so far: system, domain and course wide privileges
 8518: #
 8519: # Course: See if uri or referer is an individual resource that is part of 
 8520: # the course
 8521: 
 8522:     if ($env{'request.course.id'}) {
 8523: 
 8524: # If this is modifying password (internal auth) domains must match for user and user's role.
 8525: 
 8526:         if ($priv eq 'mip') {
 8527:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8528:                 return $thisallowed;
 8529:             } else {
 8530:                 return '';
 8531:             }
 8532:         }
 8533: 
 8534:        $courseprivid=$env{'request.course.id'};
 8535:        if ($env{'request.course.sec'}) {
 8536:           $courseprivid.='/'.$env{'request.course.sec'};
 8537:        }
 8538:        $courseprivid=~s/\_/\//;
 8539:        my $checkreferer=1;
 8540:        my ($match,$cond)=&is_on_map($uri);
 8541:        if ($match) {
 8542:            $statecond=$cond;
 8543:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8544:                =~/\Q$priv\E\&([^\:]*)/) {
 8545:                my $value = $1;
 8546:                if ($priv eq 'bre') {
 8547:                    my $deeplinkblock;
 8548:                    unless ($nodeeplinkcheck) {
 8549:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8550:                    }
 8551:                    if ($deeplinkblock) {
 8552:                        $thisallowed = 'D';
 8553:                    } elsif ($noblockcheck) {
 8554:                        $thisallowed.=$value;
 8555:                    } else {
 8556:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8557:                        if (@blockers > 0) {
 8558:                            $thisallowed = 'B';
 8559:                        } else {
 8560:                            $thisallowed.=$value;
 8561:                        }
 8562:                    }
 8563:                } else {
 8564:                    $thisallowed.=$value;
 8565:                }
 8566:                $checkreferer=0;
 8567:            }
 8568:        }
 8569: 
 8570:        if ($checkreferer) {
 8571: 	  my $refuri=$env{'httpref.'.$orguri};
 8572:             unless ($refuri) {
 8573:                 foreach my $key (keys(%env)) {
 8574: 		    if ($key=~/^httpref\..*\*/) {
 8575: 			my $pattern=$key;
 8576:                         $pattern=~s/^httpref\.\/res\///;
 8577:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8578:                         $pattern=~s/\//\\\//g;
 8579:                         if ($orguri=~/$pattern/) {
 8580: 			    $refuri=$env{$key};
 8581:                         }
 8582:                     }
 8583:                 }
 8584:             }
 8585: 
 8586:          if ($refuri) { 
 8587: 	  $refuri=&declutter($refuri);
 8588:           my ($match,$cond)=&is_on_map($refuri);
 8589:             if ($match) {
 8590:               my $refstatecond=$cond;
 8591:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8592:                   =~/\Q$priv\E\&([^\:]*)/) {
 8593:                   my $value = $1;
 8594:                   if ($priv eq 'bre') {
 8595:                       my $deeplinkblock;
 8596:                       unless ($nodeeplinkcheck) {
 8597:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8598:                       }
 8599:                       if ($deeplinkblock) {
 8600:                           $thisallowed = 'D';
 8601:                       } elsif ($noblockcheck) {
 8602:                           $thisallowed.=$value;
 8603:                       } else {
 8604:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8605:                           if (@blockers > 0) {
 8606:                               $thisallowed = 'B';
 8607:                           } else {
 8608:                               $thisallowed.=$value;
 8609:                           }
 8610:                       }
 8611:                   } else {
 8612:                       $thisallowed.=$value;
 8613:                   }
 8614:                   $uri=$refuri;
 8615:                   $statecond=$refstatecond;
 8616:               }
 8617:           }
 8618:         }
 8619:        }
 8620:    }
 8621: 
 8622: #
 8623: # Gathered now: all privileges that could apply, and condition number
 8624: # 
 8625: #
 8626: # Full or no access?
 8627: #
 8628: 
 8629:     if ($thisallowed=~/F/) {
 8630: 	return 'F';
 8631:     }
 8632: 
 8633:     unless ($thisallowed) {
 8634:         return '';
 8635:     }
 8636: 
 8637: # Restrictions exist, deal with them
 8638: #
 8639: #   C:according to course preferences
 8640: #   R:according to resource settings
 8641: #   L:unless locked
 8642: #   X:according to user session state
 8643: #
 8644: 
 8645: # Possibly locked functionality, check all courses
 8646: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8647: # Locks might take effect only after 10 minutes cache expiration for other
 8648: # courses, and 2 minutes for current course, in which user has st or ta role
 8649: # which is neither expired nor a future role (unless current course).
 8650: 
 8651:     my ($needlockcheck,$now,$crsonly);
 8652:     if ($thisallowed=~/L/) {
 8653:         $now = time;
 8654:         if ($priv eq 'bre') {
 8655:             if ($uri ne '') {
 8656:                 if ($orguri =~ m{^/+res/}) {
 8657:                     if ($uri =~ m{^lib/templates/}) {
 8658:                         if ($env{'request.course.id'}) {
 8659:                             $crsonly = 1;
 8660:                             $needlockcheck = 1;
 8661:                         }
 8662:                     } else {
 8663:                         $needlockcheck = 1;
 8664:                     }
 8665:                 } elsif ($env{'request.course.id'}) {
 8666:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8667:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8668:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8669:                         $crsonly = 1;
 8670:                     }
 8671:                     $needlockcheck = 1;
 8672:                 }
 8673:             }
 8674:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8675:             $needlockcheck = 1;
 8676:         }
 8677:     }
 8678:     if ($needlockcheck) {
 8679:         foreach my $envkey (keys(%env)) {
 8680:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8681:                my $courseid=$2;
 8682:                my $roleid=$1.'.'.$2;
 8683:                $courseid=~s/^\///;
 8684:                unless ($env{'request.role'} eq $roleid) {
 8685:                    my ($start,$end) = split(/\./,$env{$envkey});
 8686:                    next unless (($now >= $start) && (!$end || $end > $now));
 8687:                }
 8688:                my $expiretime=600;
 8689:                if ($env{'request.role'} eq $roleid) {
 8690: 		  $expiretime=120;
 8691:                }
 8692: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8693:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8694:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8695: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8696:                }
 8697:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8698:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8699: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8700:                        &log($env{'user.domain'},$env{'user.name'},
 8701:                             $env{'user.home'},
 8702:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8703:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8704:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8705: 		       return '';
 8706:                    }
 8707:                }
 8708:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8709:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8710: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8711:                        &log($env{'user.domain'},$env{'user.name'},
 8712:                             $env{'user.home'},
 8713:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8714:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8715:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8716: 		       return '';
 8717:                    }
 8718:                }
 8719: 	   }
 8720:        }
 8721:     }
 8722: 
 8723: #
 8724: # Rest of the restrictions depend on selected course
 8725: #
 8726: 
 8727:     unless ($env{'request.course.id'}) {
 8728: 	if ($thisallowed eq 'A') {
 8729: 	    return 'A';
 8730:         } elsif ($thisallowed eq 'B') {
 8731:             return 'B';
 8732: 	} else {
 8733: 	    return '1';
 8734: 	}
 8735:     }
 8736: 
 8737: #
 8738: # Now user is definitely in a course
 8739: #
 8740: 
 8741: 
 8742: # Course preferences
 8743: 
 8744:    if ($thisallowed=~/C/) {
 8745:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8746:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8747:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8748: 	   =~/\Q$rolecode\E/) {
 8749: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8750: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8751: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8752: 			$env{'request.course.id'});
 8753: 	   }
 8754:            return '';
 8755:        }
 8756: 
 8757:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8758: 	   =~/\Q$unamedom\E/) {
 8759: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8760: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8761: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8762: 			$env{'request.course.id'});
 8763: 	   }
 8764:            return '';
 8765:        }
 8766:    }
 8767: 
 8768: # Resource preferences
 8769: 
 8770:    if ($thisallowed=~/R/) {
 8771:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8772:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8773: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8774: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8775: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8776: 	   }
 8777: 	   return '';
 8778:        }
 8779:    }
 8780: 
 8781: # Restricted for deeplinked session?
 8782: 
 8783:     if ($env{'request.deeplink.login'}) {
 8784:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8785:             if (!$symb) { $symb=&symbread($uri,1); }
 8786:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8787:                 return '';
 8788:             }
 8789:         }
 8790:     }
 8791: 
 8792: # Restricted by state or randomout?
 8793: 
 8794:    if ($thisallowed=~/X/) {
 8795:       if ($env{'acc.randomout'}) {
 8796: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8797:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8798:             return ''; 
 8799:          }
 8800:       }
 8801:       if (&condval($statecond)) {
 8802: 	 return '2';
 8803:       } else {
 8804:          return '';
 8805:       }
 8806:    }
 8807: 
 8808:     if ($thisallowed eq 'A') {
 8809: 	return 'A';
 8810:     } elsif ($thisallowed eq 'B') {
 8811:         return 'B';
 8812:     } elsif ($thisallowed eq 'D') {
 8813:         return 'D';
 8814:     }
 8815:    return 'F';
 8816: }
 8817: 
 8818: # ------------------------------------------- Check construction space access
 8819: 
 8820: sub constructaccess {
 8821:     my ($url,$setpriv)=@_;
 8822: 
 8823: # We do not allow editing of previous versions of files
 8824:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8825: 
 8826: # Get username and domain from URL
 8827:     my ($ownername,$ownerdomain,$ownerhome);
 8828: 
 8829:     ($ownerdomain,$ownername) =
 8830:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8831: 
 8832: # The URL does not really point to any authorspace, forget it
 8833:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8834: 
 8835: # Now we need to see if the user has access to the authorspace of
 8836: # $ownername at $ownerdomain
 8837: 
 8838:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8839: # Real author for this?
 8840:        $ownerhome = $env{'user.home'};
 8841:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8842:           return ($ownername,$ownerdomain,$ownerhome);
 8843:        }
 8844:     } else {
 8845: # Co-author for this?
 8846:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8847:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8848:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8849:             return ($ownername,$ownerdomain,$ownerhome);
 8850:         }
 8851:         if ($env{'request.course.id'}) {
 8852:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8853:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8854:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8855:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8856:                     return ($ownername,$ownerdomain,$ownerhome);
 8857:                 }
 8858:             }
 8859:         }
 8860:     }
 8861: 
 8862: # We don't have any access right now. If we are not possibly going to do anything about this,
 8863: # we might as well leave
 8864:    unless ($setpriv) { return ''; }
 8865: 
 8866: # Backdoor access?
 8867:     my $allowed=&allowed('eco',$ownerdomain);
 8868: # Nope
 8869:     unless ($allowed) { return ''; }
 8870: # Looks like we may have access, but could be locked by the owner of the construction space
 8871:     if ($allowed eq 'U') {
 8872:         my %blocked=&get('environment',['domcoord.author'],
 8873:                          $ownerdomain,$ownername);
 8874: # Is blocked by owner
 8875:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8876:     }
 8877:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8878: # Grant temporary access
 8879:         my $then=$env{'user.login.time'};
 8880:         my $update=$env{'user.update.time'};
 8881:         if (!$update) { $update = $then; }
 8882:         my $refresh=$env{'user.refresh.time'};
 8883:         if (!$refresh) { $refresh = $update; }
 8884:         my $now = time;
 8885:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8886:                            $now,'ca','constructaccess');
 8887:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8888:         return($ownername,$ownerdomain,$ownerhome);
 8889:     }
 8890: # No business here
 8891:     return '';
 8892: }
 8893: 
 8894: # ----------------------------------------------------------- Content Blocking
 8895: 
 8896: {
 8897: # Caches for faster Course Contents display where content blocking
 8898: # is in operation (i.e., interval param set) for timed quiz.
 8899: #
 8900: # User for whom data are being temporarily cached.
 8901: my $cacheduser='';
 8902: # Course for which data are being temporarily cached.
 8903: my $cachedcid='';
 8904: # Cached blockers for this user (a hash of blocking items). 
 8905: my %cachedblockers=();
 8906: # When the data were last cached.
 8907: my $cachedlast='';
 8908: 
 8909: sub load_all_blockers {
 8910:     my ($uname,$udom)=@_;
 8911:     if (($uname ne '') && ($udom ne '')) { 
 8912:         if (($cacheduser eq $uname.':'.$udom) &&
 8913:             ($cachedcid eq $env{'request.course.id'}) &&
 8914:             (abs($cachedlast-time)<5)) {
 8915:             return;
 8916:         }
 8917:     }
 8918:     $cachedlast=time;
 8919:     $cacheduser=$uname.':'.$udom;
 8920:     $cachedcid=$env{'request.course.id'};
 8921:     %cachedblockers = &get_commblock_resources();
 8922:     return;
 8923: }
 8924: 
 8925: sub get_comm_blocks {
 8926:     my ($cdom,$cnum) = @_;
 8927:     if ($cdom eq '' || $cnum eq '') {
 8928:         return unless ($env{'request.course.id'});
 8929:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8930:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8931:     }
 8932:     my %commblocks;
 8933:     my $hashid=$cdom.'_'.$cnum;
 8934:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8935:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8936:         %commblocks = %{$blocksref};
 8937:     } else {
 8938:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8939:         my $cachetime = 600;
 8940:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8941:     }
 8942:     return %commblocks;
 8943: }
 8944: 
 8945: sub get_commblock_resources {
 8946:     my ($blocks) = @_;
 8947:     my %blockers = ();
 8948:     return %blockers unless ($env{'request.course.id'});
 8949:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8950:     if ($env{'request.course.sec'}) {
 8951:         $courseurl .= '/'.$env{'request.course.sec'};
 8952:     }
 8953:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8954:     my %commblocks;
 8955:     if (ref($blocks) eq 'HASH') {
 8956:         %commblocks = %{$blocks};
 8957:     } else {
 8958:         %commblocks = &get_comm_blocks();
 8959:     }
 8960:     return %blockers unless (keys(%commblocks) > 0); 
 8961:     my $navmap = Apache::lonnavmaps::navmap->new();
 8962:     return %blockers unless (ref($navmap));
 8963:     my $now = time;
 8964:     foreach my $block (keys(%commblocks)) {
 8965:         if ($block =~ /^(\d+)____(\d+)$/) {
 8966:             my ($start,$end) = ($1,$2);
 8967:             if ($start <= $now && $end >= $now) {
 8968:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8969:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8970:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8971:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8972:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8973:                             }
 8974:                         }
 8975:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8976:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8977:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8978:                             }
 8979:                         }
 8980:                     }
 8981:                 }
 8982:             }
 8983:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8984:             my $item = $1;
 8985:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8986:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8987:                     my (@interval,$mapname);
 8988:                     my $type = 'map';
 8989:                     if ($item eq 'course') {
 8990:                         $type = 'course';
 8991:                         @interval=&EXT("resource.0.interval");
 8992:                     } else {
 8993:                         if ($item =~ /___\d+___/) {
 8994:                             $type = 'resource';
 8995:                             @interval=&EXT("resource.0.interval",$item);
 8996:                         } else {
 8997:                             $mapname = &deversion($item);
 8998:                             if (ref($navmap)) {
 8999:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9000:                                 @interval = ($timelimit,'map');
 9001:                             }
 9002:                         }
 9003:                     }
 9004:                     if ($interval[0] =~ /^(\d+)/) {
 9005:                         my $timelimit = $1; 
 9006:                         my $first_access;
 9007:                         if ($type eq 'resource') {
 9008:                             $first_access=&get_first_access($interval[1],$item);
 9009:                         } elsif ($type eq 'map') {
 9010:                             $first_access=&get_first_access($interval[1],undef,$item);
 9011:                         } else {
 9012:                             $first_access=&get_first_access($interval[1]);
 9013:                         }
 9014:                         if ($first_access) {
 9015:                             my $timesup = $first_access+$timelimit;
 9016:                             if ($timesup > $now) {
 9017:                                 my $activeblock;
 9018:                                 if ($type eq 'resource') {
 9019:                                     if (ref($navmap)) {
 9020:                                         my $res = $navmap->getBySymb($item);
 9021:                                         if ($res->answerable()) {
 9022:                                             $activeblock = 1;
 9023:                                         }
 9024:                                     }
 9025:                                 } elsif ($type eq 'map') {
 9026:                                     my $mapsymb = &symbread($mapname,1);
 9027:                                     if (($mapsymb) && (ref($navmap))) {
 9028:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9029:                                         if (ref($mapres)) {
 9030:                                             my $first = $mapres->map_start();
 9031:                                             my $finish = $mapres->map_finish();
 9032:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9033:                                             if (ref($it)) {
 9034:                                                 my $res;
 9035:                                                 while ($res = $it->next(undef,1)) {
 9036:                                                     next unless (ref($res));
 9037:                                                     my $symb = $res->symb();
 9038:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9039:                                                     @interval=&EXT("resource.0.interval",$symb);
 9040:                                                     if ($interval[1] eq 'map') {
 9041:                                                         if ($res->answerable()) {
 9042:                                                             $activeblock = 1;
 9043:                                                             last;
 9044:                                                         }
 9045:                                                     }
 9046:                                                 }
 9047:                                             }
 9048:                                         }
 9049:                                     }
 9050:                                 }
 9051:                                 if ($activeblock) {
 9052:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9053:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9054:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9055:                                          }
 9056:                                     }
 9057:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9058:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9059:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9060:                                         }
 9061:                                     }
 9062:                                 }
 9063:                             }
 9064:                         }
 9065:                     }
 9066:                 }
 9067:             }
 9068:         }
 9069:     }
 9070:     return %blockers;
 9071: }
 9072: 
 9073: sub has_comm_blocking {
 9074:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9075:     my @blockers;
 9076:     return unless ($env{'request.course.id'});
 9077:     return unless ($priv eq 'bre');
 9078:     return if ($env{'request.state'} eq 'construct');
 9079:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9080:     if ($env{'request.course.sec'}) {
 9081:         $courseurl .= '/'.$env{'request.course.sec'};
 9082:     }
 9083:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9084:     my %blockinfo;
 9085:     if (ref($blocks) eq 'HASH') {
 9086:         %blockinfo = &get_commblock_resources($blocks);
 9087:     } else {
 9088:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9089:         %blockinfo = %cachedblockers;
 9090:     }
 9091:     return unless (keys(%blockinfo) > 0);
 9092:     my (%possibles,@symbs);
 9093:     if (!$symb) {
 9094:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9095:     }
 9096:     if ($symb) {
 9097:         @symbs = ($symb);
 9098:     } elsif (keys(%possibles)) { 
 9099:         @symbs = keys(%possibles);
 9100:     }
 9101:     my $noblock;
 9102:     foreach my $symb (@symbs) {
 9103:         last if ($noblock);
 9104:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9105:         foreach my $block (keys(%blockinfo)) {
 9106:             if ($block =~ /^firstaccess____(.+)$/) {
 9107:                 my $item = $1;
 9108:                 unless ($blocked) {
 9109:                     if (($item eq $map) || ($item eq $symb)) {
 9110:                         $noblock = 1;
 9111:                         last;
 9112:                     }
 9113:                 }
 9114:             }
 9115:             if (ref($blockinfo{$block}) eq 'HASH') {
 9116:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9117:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9118:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9119:                             push(@blockers,$block);
 9120:                         }
 9121:                     }
 9122:                 }
 9123:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9124:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9125:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9126:                             push(@blockers,$block);
 9127:                         }
 9128:                     }
 9129:                 }
 9130:             }
 9131:         }
 9132:     }
 9133:     unless ($noblock) { 
 9134:         return @blockers;
 9135:     }
 9136:     return;
 9137: }
 9138: }
 9139: 
 9140: sub deeplink_check {
 9141:     my ($priv,$symb,$uri) = @_;
 9142:     return unless ($env{'request.course.id'});
 9143:     return unless ($priv eq 'bre');
 9144:     return if ($env{'request.state'} eq 'construct');
 9145:     return if ($env{'request.role.adv'});
 9146:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9147:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9148:     my (%possibles,@symbs);
 9149:     if (!$symb) {
 9150:         $symb = &symbread($uri,1,1,1,\%possibles);
 9151:     }
 9152:     if ($symb) {
 9153:         @symbs = ($symb);
 9154:     } elsif (keys(%possibles)) {
 9155:         @symbs = keys(%possibles);
 9156:     }
 9157: 
 9158:     my ($deeplink_symb,$allow);
 9159:     if ($env{'request.deeplink.login'}) {
 9160:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9161:     }
 9162:     foreach my $symb (@symbs) {
 9163:         last if ($allow);
 9164:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9165:         if ($deeplink eq '') {
 9166:             $allow = 1;
 9167:         } else {
 9168:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9169:             if ($state ne 'only') {
 9170:                 $allow = 1;
 9171:             } else {
 9172:                 my $check_deeplink_entry;
 9173:                 if ($protect ne 'none') {
 9174:                     my ($acctype,$item) = split(/:/,$protect);
 9175:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9176:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9177:                             $check_deeplink_entry = 1
 9178:                         }
 9179:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9180:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9181:                             $check_deeplink_entry = 1;
 9182:                         }
 9183:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9184:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9185:                             $check_deeplink_entry = 1;
 9186:                         }
 9187:                     }
 9188:                 }
 9189:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9190:                     if ($scope eq 'res') {
 9191:                         if ($symb eq $deeplink_symb) {
 9192:                             $allow = 1;
 9193:                         }
 9194:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9195:                         my ($map_from_symb,$map_from_login);
 9196:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9197:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9198:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9199:                         } else {
 9200:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9201:                         }
 9202:                         if (($map_from_symb) && ($map_from_login)) {
 9203:                             if ($map_from_symb eq $map_from_login) {
 9204:                                 $allow = 1;
 9205:                             } elsif ($scope eq 'rec') {
 9206:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9207:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9208:                                     $allow = 1;
 9209:                                 }
 9210:                             }
 9211:                         }
 9212:                     }
 9213:                 }
 9214:             }
 9215:         }
 9216:     }
 9217:     return if ($allow);
 9218:     return 1;
 9219: }
 9220: 
 9221: # -------------------------------- Deversion and split uri into path an filename   
 9222: 
 9223: #
 9224: #   Removes the version from a URI and
 9225: #   splits it in to its filename and path to the filename.
 9226: #   Seems like File::Basename could have done this more clearly.
 9227: #   Parameters:
 9228: #      $uri   - input URI
 9229: #   Returns:
 9230: #     Two element list consisting of 
 9231: #     $pathname  - the URI up to and excluding the trailing /
 9232: #     $filename  - The part of the URI following the last /
 9233: #  NOTE:
 9234: #    Another realization of this is simply:
 9235: #    use File::Basename;
 9236: #    ...
 9237: #    $uri = shift;
 9238: #    $filename = basename($uri);
 9239: #    $path     = dirname($uri);
 9240: #    return ($filename, $path);
 9241: #
 9242: #     The implementation below is probably faster however.
 9243: #
 9244: sub split_uri_for_cond {
 9245:     my $uri=&deversion(&declutter(shift));
 9246:     my @uriparts=split(/\//,$uri);
 9247:     my $filename=pop(@uriparts);
 9248:     my $pathname=join('/',@uriparts);
 9249:     return ($pathname,$filename);
 9250: }
 9251: # --------------------------------------------------- Is a resource on the map?
 9252: 
 9253: sub is_on_map {
 9254:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9255:     #Trying to find the conditional for the file
 9256:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9257: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9258:     if ($match) {
 9259: 	return (1,$1);
 9260:     } else {
 9261: 	return (0,0);
 9262:     }
 9263: }
 9264: 
 9265: # --------------------------------------------------------- Get symb from alias
 9266: 
 9267: sub get_symb_from_alias {
 9268:     my $symb=shift;
 9269:     my ($map,$resid,$url)=&decode_symb($symb);
 9270: # Already is a symb
 9271:     if ($url) { return $symb; }
 9272: # Must be an alias
 9273:     my $aliassymb='';
 9274:     my %bighash;
 9275:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9276:                             &GDBM_READER(),0640)) {
 9277:         my $rid=$bighash{'mapalias_'.$symb};
 9278: 	if ($rid) {
 9279: 	    my ($mapid,$resid)=split(/\./,$rid);
 9280: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9281: 				    $resid,$bighash{'src_'.$rid});
 9282: 	}
 9283:         untie %bighash;
 9284:     }
 9285:     return $aliassymb;
 9286: }
 9287: 
 9288: # ----------------------------------------------------------------- Define Role
 9289: 
 9290: sub definerole {
 9291:   if (allowed('mcr','/')) {
 9292:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9293:     foreach my $role (split(':',$sysrole)) {
 9294: 	my ($crole,$cqual)=split(/\&/,$role);
 9295:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9296:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9297: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9298:                return "refused:s:$crole&$cqual"; 
 9299:             }
 9300:         }
 9301:     }
 9302:     foreach my $role (split(':',$domrole)) {
 9303: 	my ($crole,$cqual)=split(/\&/,$role);
 9304:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9305:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9306: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9307:                return "refused:d:$crole&$cqual"; 
 9308:             }
 9309:         }
 9310:     }
 9311:     foreach my $role (split(':',$courole)) {
 9312: 	my ($crole,$cqual)=split(/\&/,$role);
 9313:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9314:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9315: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9316:                return "refused:c:$crole&$cqual"; 
 9317:             }
 9318:         }
 9319:     }
 9320:     my $uhome;
 9321:     if (($uname ne '') && ($udom ne '')) {
 9322:         $uhome = &homeserver($uname,$udom);
 9323:         return $uhome if ($uhome eq 'no_host');
 9324:     } else {
 9325:         $uname = $env{'user.name'};
 9326:         $udom = $env{'user.domain'};
 9327:         $uhome = $env{'user.home'};
 9328:     }
 9329:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9330:                 "$udom:$uname:rolesdef_$rolename=".
 9331:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9332:     return reply($command,$uhome);
 9333:   } else {
 9334:     return 'refused';
 9335:   }
 9336: }
 9337: 
 9338: # ---------------- Make a metadata query against the network of library servers
 9339: 
 9340: sub metadata_query {
 9341:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9342:     my %rhash;
 9343:     my %libserv = &all_library();
 9344:     my @server_list = (defined($server_array) ? @$server_array
 9345:                                               : keys(%libserv) );
 9346:     for my $server (@server_list) {
 9347:         my $domains = ''; 
 9348:         if (ref($domains_hash) eq 'HASH') {
 9349:             $domains = $domains_hash->{$server}; 
 9350:         }
 9351: 	unless ($custom or $customshow) {
 9352: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9353: 	    $rhash{$server}=$reply;
 9354: 	}
 9355: 	else {
 9356: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9357: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9358: 			     $server);
 9359: 	    $rhash{$server}=$reply;
 9360: 	}
 9361:     }
 9362:     return \%rhash;
 9363: }
 9364: 
 9365: # ----------------------------------------- Send log queries and wait for reply
 9366: 
 9367: sub log_query {
 9368:     my ($uname,$udom,$query,%filters)=@_;
 9369:     my $uhome=&homeserver($uname,$udom);
 9370:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9371:     my $uhost=&hostname($uhome);
 9372:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9373:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9374:                        $uhome);
 9375:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9376:     return get_query_reply($queryid);
 9377: }
 9378: 
 9379: # -------------------------- Update MySQL table for portfolio file
 9380: 
 9381: sub update_portfolio_table {
 9382:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9383:     if ($group ne '') {
 9384:         $file_name =~s /^\Q$group\E//;
 9385:     }
 9386:     my $homeserver = &homeserver($uname,$udom);
 9387:     my $queryid=
 9388:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9389:                ':'.&escape($file_name).':'.$action,$homeserver);
 9390:     my $reply = &get_query_reply($queryid);
 9391:     return $reply;
 9392: }
 9393: 
 9394: # -------------------------- Update MySQL allusers table
 9395: 
 9396: sub update_allusers_table {
 9397:     my ($uname,$udom,$names) = @_;
 9398:     my $homeserver = &homeserver($uname,$udom);
 9399:     my $queryid=
 9400:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9401:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9402:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9403:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9404:                'generation='.&escape($names->{'generation'}).'%%'.
 9405:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9406:                'id='.&escape($names->{'id'}),$homeserver);
 9407:     return;
 9408: }
 9409: 
 9410: # ------- Request retrieval of institutional classlists for course(s)
 9411: 
 9412: sub fetch_enrollment_query {
 9413:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9414:     my ($homeserver,$sleep,$loopmax);
 9415:     my $maxtries = 1;
 9416:     if ($context eq 'automated') {
 9417:         $homeserver = $perlvar{'lonHostID'};
 9418:         $sleep = 2;
 9419:         $loopmax = 100;
 9420:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9421:     } else {
 9422:         $homeserver = &homeserver($cnum,$dom);
 9423:     }
 9424:     my $host=&hostname($homeserver);
 9425:     my $cmd = '';
 9426:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9427:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9428:     }
 9429:     $cmd =~ s/%%$//;
 9430:     $cmd = &escape($cmd);
 9431:     my $query = 'fetchenrollment';
 9432:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9433:     unless ($queryid=~/^\Q$host\E\_/) { 
 9434:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9435:         return 'error: '.$queryid;
 9436:     }
 9437:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9438:     my $tries = 1;
 9439:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9440:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9441:         $tries ++;
 9442:     }
 9443:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9444:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9445:     } else {
 9446:         my @responses = split(/:/,$reply);
 9447:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9448:             foreach my $line (@responses) {
 9449:                 my ($key,$value) = split(/=/,$line,2);
 9450:                 $$replyref{$key} = $value;
 9451:             }
 9452:         } else {
 9453:             my $pathname = LONCAPA::tempdir();
 9454:             foreach my $line (@responses) {
 9455:                 my ($key,$value) = split(/=/,$line);
 9456:                 $$replyref{$key} = $value;
 9457:                 if ($value > 0) {
 9458:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9459:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9460:                         my $destname = $pathname.'/'.$filename;
 9461:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9462:                         if ($xml_classlist =~ /^error/) {
 9463:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9464:                         } else {
 9465:                             if ( open(FILE,">",$destname) ) {
 9466:                                 print FILE &unescape($xml_classlist);
 9467:                                 close(FILE);
 9468:                             } else {
 9469:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9470:                             }
 9471:                         }
 9472:                     }
 9473:                 }
 9474:             }
 9475:         }
 9476:         return 'ok';
 9477:     }
 9478:     return 'error';
 9479: }
 9480: 
 9481: sub get_query_reply {
 9482:     my ($queryid,$sleep,$loopmax) = @_;
 9483:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9484:         $sleep = 0.2;
 9485:     }
 9486:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9487:         $loopmax = 100;
 9488:     }
 9489:     my $replyfile=LONCAPA::tempdir().$queryid;
 9490:     my $reply='';
 9491:     for (1..$loopmax) {
 9492: 	sleep($sleep);
 9493:         if (-e $replyfile.'.end') {
 9494: 	    if (open(my $fh,"<",$replyfile)) {
 9495: 		$reply = join('',<$fh>);
 9496: 		close($fh);
 9497: 	   } else { return 'error: reply_file_error'; }
 9498:            return &unescape($reply);
 9499: 	}
 9500:     }
 9501:     return 'timeout:'.$queryid;
 9502: }
 9503: 
 9504: sub courselog_query {
 9505: #
 9506: # possible filters:
 9507: # url: url or symb
 9508: # username
 9509: # domain
 9510: # action: view, submit, grade
 9511: # start: timestamp
 9512: # end: timestamp
 9513: #
 9514:     my (%filters)=@_;
 9515:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9516:     if ($filters{'url'}) {
 9517: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9518:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9519:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9520:     }
 9521:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9522:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9523:     return &log_query($cname,$cdom,'courselog',%filters);
 9524: }
 9525: 
 9526: sub userlog_query {
 9527: #
 9528: # possible filters:
 9529: # action: log check role
 9530: # start: timestamp
 9531: # end: timestamp
 9532: #
 9533:     my ($uname,$udom,%filters)=@_;
 9534:     return &log_query($uname,$udom,'userlog',%filters);
 9535: }
 9536: 
 9537: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9538: 
 9539: sub auto_run {
 9540:     my ($cnum,$cdom) = @_;
 9541:     my $response = 0;
 9542:     my $settings;
 9543:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9544:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9545:         $settings = $domconfig{'autoenroll'};
 9546:         if ($settings->{'run'} eq '1') {
 9547:             $response = 1;
 9548:         }
 9549:     } else {
 9550:         my $homeserver;
 9551:         if (&is_course($cdom,$cnum)) {
 9552:             $homeserver = &homeserver($cnum,$cdom);
 9553:         } else {
 9554:             $homeserver = &domain($cdom,'primary');
 9555:         }
 9556:         if ($homeserver ne 'no_host') {
 9557:             $response = &reply('autorun:'.$cdom,$homeserver);
 9558:         }
 9559:     }
 9560:     return $response;
 9561: }
 9562: 
 9563: sub auto_get_sections {
 9564:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9565:     my $homeserver;
 9566:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9567:         $homeserver = &homeserver($cnum,$cdom);
 9568:     }
 9569:     if (!defined($homeserver)) { 
 9570:         if ($cdom =~ /^$match_domain$/) {
 9571:             $homeserver = &domain($cdom,'primary');
 9572:         }
 9573:     }
 9574:     my @secs;
 9575:     if (defined($homeserver)) {
 9576:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9577:         unless ($response eq 'refused') {
 9578:             @secs = split(/:/,$response);
 9579:         }
 9580:     }
 9581:     return @secs;
 9582: }
 9583: 
 9584: sub auto_new_course {
 9585:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9586:     my $homeserver = &homeserver($cnum,$cdom);
 9587:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9588:     return $response;
 9589: }
 9590: 
 9591: sub auto_validate_courseID {
 9592:     my ($cnum,$cdom,$inst_course_id) = @_;
 9593:     my $homeserver = &homeserver($cnum,$cdom);
 9594:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9595:     return $response;
 9596: }
 9597: 
 9598: sub auto_validate_instcode {
 9599:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9600:     my ($homeserver,$response);
 9601:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9602:         $homeserver = &homeserver($cnum,$cdom);
 9603:     }
 9604:     if (!defined($homeserver)) {
 9605:         if ($cdom =~ /^$match_domain$/) {
 9606:             $homeserver = &domain($cdom,'primary');
 9607:         }
 9608:     }
 9609:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9610:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9611:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9612:     return ($outcome,$description,$defaultcredits);
 9613: }
 9614: 
 9615: sub auto_validate_inst_crosslist {
 9616:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9617:     my ($homeserver,$response);
 9618:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9619:         $homeserver = &homeserver($cnum,$cdom);
 9620:     }
 9621:     if (!defined($homeserver)) {
 9622:         if ($cdom =~ /^$match_domain$/) {
 9623:             $homeserver = &domain($cdom,'primary');
 9624:         }
 9625:     }
 9626:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9627:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9628:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9629:                          &escape($coowner),$homeserver);
 9630:     }
 9631:     return $response;
 9632: }
 9633: 
 9634: sub auto_create_password {
 9635:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9636:     my ($homeserver,$response);
 9637:     my $create_passwd = 0;
 9638:     my $authchk = '';
 9639:     if ($udom =~ /^$match_domain$/) {
 9640:         $homeserver = &domain($udom,'primary');
 9641:     }
 9642:     if ($homeserver eq '') {
 9643:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9644:             $homeserver = &homeserver($cnum,$cdom);
 9645:         }
 9646:     }
 9647:     if ($homeserver eq '') {
 9648:         $authchk = 'nodomain';
 9649:     } else {
 9650:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9651:         if ($response eq 'refused') {
 9652:             $authchk = 'refused';
 9653:         } else {
 9654:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9655:         }
 9656:     }
 9657:     return ($authparam,$create_passwd,$authchk);
 9658: }
 9659: 
 9660: sub auto_photo_permission {
 9661:     my ($cnum,$cdom,$students) = @_;
 9662:     my $homeserver = &homeserver($cnum,$cdom);
 9663:     my ($outcome,$perm_reqd,$conditions) = 
 9664: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9665:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9666: 	return (undef,undef);
 9667:     }
 9668:     return ($outcome,$perm_reqd,$conditions);
 9669: }
 9670: 
 9671: sub auto_checkphotos {
 9672:     my ($uname,$udom,$pid) = @_;
 9673:     my $homeserver = &homeserver($uname,$udom);
 9674:     my ($result,$resulttype);
 9675:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9676: 				   &escape($uname).':'.&escape($pid),
 9677: 				   $homeserver));
 9678:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9679: 	return (undef,undef);
 9680:     }
 9681:     if ($outcome) {
 9682:         ($result,$resulttype) = split(/:/,$outcome);
 9683:     } 
 9684:     return ($result,$resulttype);
 9685: }
 9686: 
 9687: sub auto_photochoice {
 9688:     my ($cnum,$cdom) = @_;
 9689:     my $homeserver = &homeserver($cnum,$cdom);
 9690:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9691: 						       &escape($cdom),
 9692: 						       $homeserver)));
 9693:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9694: 	return (undef,undef);
 9695:     }
 9696:     return ($update,$comment);
 9697: }
 9698: 
 9699: sub auto_photoupdate {
 9700:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9701:     my $homeserver = &homeserver($cnum,$dom);
 9702:     my $host=&hostname($homeserver);
 9703:     my $cmd = '';
 9704:     my $maxtries = 1;
 9705:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9706:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9707:     }
 9708:     $cmd =~ s/%%$//;
 9709:     $cmd = &escape($cmd);
 9710:     my $query = 'institutionalphotos';
 9711:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9712:     unless ($queryid=~/^\Q$host\E\_/) {
 9713:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9714:         return 'error: '.$queryid;
 9715:     }
 9716:     my $reply = &get_query_reply($queryid);
 9717:     my $tries = 1;
 9718:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9719:         $reply = &get_query_reply($queryid);
 9720:         $tries ++;
 9721:     }
 9722:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9723:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9724:     } else {
 9725:         my @responses = split(/:/,$reply);
 9726:         my $outcome = shift(@responses); 
 9727:         foreach my $item (@responses) {
 9728:             my ($key,$value) = split(/=/,$item);
 9729:             $$photo{$key} = $value;
 9730:         }
 9731:         return $outcome;
 9732:     }
 9733:     return 'error';
 9734: }
 9735: 
 9736: sub auto_instcode_format {
 9737:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9738: 	$cat_order) = @_;
 9739:     my $courses = '';
 9740:     my @homeservers;
 9741:     if ($caller eq 'global') {
 9742: 	my %servers = &get_servers($codedom,'library');
 9743: 	foreach my $tryserver (keys(%servers)) {
 9744: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9745: 		push(@homeservers,$tryserver);
 9746: 	    }
 9747:         }
 9748:     } elsif ($caller eq 'requests') {
 9749:         if ($codedom =~ /^$match_domain$/) {
 9750:             my $chome = &domain($codedom,'primary');
 9751:             unless ($chome eq 'no_host') {
 9752:                 push(@homeservers,$chome);
 9753:             }
 9754:         }
 9755:     } else {
 9756:         push(@homeservers,&homeserver($caller,$codedom));
 9757:     }
 9758:     foreach my $code (keys(%{$instcodes})) {
 9759:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9760:     }
 9761:     chop($courses);
 9762:     my $ok_response = 0;
 9763:     my $response;
 9764:     while (@homeservers > 0 && $ok_response == 0) {
 9765:         my $server = shift(@homeservers); 
 9766:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9767:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9768:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9769: 		split(/:/,$response);
 9770:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9771:             push(@{$codetitles},&str2array($codetitles_str));
 9772:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9773:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9774:             $ok_response = 1;
 9775:         }
 9776:     }
 9777:     if ($ok_response) {
 9778:         return 'ok';
 9779:     } else {
 9780:         return $response;
 9781:     }
 9782: }
 9783: 
 9784: sub auto_instcode_defaults {
 9785:     my ($domain,$returnhash,$code_order) = @_;
 9786:     my @homeservers;
 9787: 
 9788:     my %servers = &get_servers($domain,'library');
 9789:     foreach my $tryserver (keys(%servers)) {
 9790: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9791: 	    push(@homeservers,$tryserver);
 9792: 	}
 9793:     }
 9794: 
 9795:     my $response;
 9796:     foreach my $server (@homeservers) {
 9797:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9798:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9799: 	
 9800: 	foreach my $pair (split(/\&/,$response)) {
 9801: 	    my ($name,$value)=split(/\=/,$pair);
 9802: 	    if ($name eq 'code_order') {
 9803: 		@{$code_order} = split(/\&/,&unescape($value));
 9804: 	    } else {
 9805: 		$returnhash->{&unescape($name)}=&unescape($value);
 9806: 	    }
 9807: 	}
 9808: 	return 'ok';
 9809:     }
 9810: 
 9811:     return $response;
 9812: }
 9813: 
 9814: sub auto_possible_instcodes {
 9815:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9816:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9817:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9818:         return;
 9819:     }
 9820:     my (@homeservers,$uhome);
 9821:     if (defined(&domain($domain,'primary'))) {
 9822:         $uhome=&domain($domain,'primary');
 9823:         push(@homeservers,&domain($domain,'primary'));
 9824:     } else {
 9825:         my %servers = &get_servers($domain,'library');
 9826:         foreach my $tryserver (keys(%servers)) {
 9827:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9828:                 push(@homeservers,$tryserver);
 9829:             }
 9830:         }
 9831:     }
 9832:     my $response;
 9833:     foreach my $server (@homeservers) {
 9834:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9835:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9836:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9837:             split(':',$response);
 9838:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9839:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9840:         foreach my $item (split('&',$cat_title)) {   
 9841:             my ($name,$value)=split('=',$item);
 9842:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9843:         }
 9844:         foreach my $item (split('&',$cat_order)) {
 9845:             my ($name,$value)=split('=',$item);
 9846:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9847:         }
 9848:         return 'ok';
 9849:     }
 9850:     return $response;
 9851: }
 9852: 
 9853: sub auto_courserequest_checks {
 9854:     my ($dom) = @_;
 9855:     my ($homeserver,%validations);
 9856:     if ($dom =~ /^$match_domain$/) {
 9857:         $homeserver = &domain($dom,'primary');
 9858:     }
 9859:     unless ($homeserver eq 'no_host') {
 9860:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9861:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9862:             my @items = split(/&/,$response);
 9863:             foreach my $item (@items) {
 9864:                 my ($key,$value) = split('=',$item);
 9865:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9866:             }
 9867:         }
 9868:     }
 9869:     return %validations; 
 9870: }
 9871: 
 9872: sub auto_courserequest_validation {
 9873:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9874:     my ($homeserver,$response);
 9875:     if ($dom =~ /^$match_domain$/) {
 9876:         $homeserver = &domain($dom,'primary');
 9877:     }
 9878:     unless ($homeserver eq 'no_host') {
 9879:         my $customdata;
 9880:         if (ref($custominfo) eq 'HASH') {
 9881:             $customdata = &freeze_escape($custominfo);
 9882:         }
 9883:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9884:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9885:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9886:                                     $customdata,$homeserver));
 9887:     }
 9888:     return $response;
 9889: }
 9890: 
 9891: sub auto_validate_class_sec {
 9892:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9893:     my $homeserver = &homeserver($cnum,$cdom);
 9894:     my $ownerlist;
 9895:     if (ref($owners) eq 'ARRAY') {
 9896:         $ownerlist = join(',',@{$owners});
 9897:     } else {
 9898:         $ownerlist = $owners;
 9899:     }
 9900:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9901:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9902:     return $response;
 9903: }
 9904: 
 9905: sub auto_instsec_reformat {
 9906:     my ($cdom,$action,$instsecref) = @_;
 9907:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
 9908:     my @homeservers;
 9909:     if (defined(&domain($cdom,'primary'))) {
 9910:         push(@homeservers,&domain($cdom,'primary'));
 9911:     } else {
 9912:         my %servers = &get_servers($cdom,'library');
 9913:         foreach my $tryserver (keys(%servers)) {
 9914:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9915:                 push(@homeservers,$tryserver);
 9916:             }
 9917:         }
 9918:     }
 9919:     my $response;
 9920:     my %reformatted = %{$instsecref};
 9921:     foreach my $server (@homeservers) {
 9922:         if (ref($instsecref) eq 'HASH') {
 9923:             my $info = &freeze_escape($instsecref);
 9924:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
 9925:                                 $action.':'.$info,$server);
 9926:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
 9927:             my @items = split(/&/,$response);
 9928:             foreach my $item (@items) {
 9929:                 my ($key,$value) = split(/=/,$item);
 9930:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
 9931:             }
 9932:         }
 9933:     }
 9934:     return %reformatted;
 9935: }
 9936: 
 9937: sub auto_validate_instclasses {
 9938:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9939:     my ($homeserver,%validations);
 9940:     $homeserver = &homeserver($cnum,$cdom);
 9941:     unless ($homeserver eq 'no_host') {
 9942:         my $ownerlist;
 9943:         if (ref($owners) eq 'ARRAY') {
 9944:             $ownerlist = join(',',@{$owners});
 9945:         } else {
 9946:             $ownerlist = $owners;
 9947:         }
 9948:         if (ref($classesref) eq 'HASH') {
 9949:             my $classes = &freeze_escape($classesref);
 9950:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9951:                                 ':'.$cdom.':'.$classes,$homeserver);
 9952:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9953:                 my @items = split(/&/,$response);
 9954:                 foreach my $item (@items) {
 9955:                     my ($key,$value) = split('=',$item);
 9956:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9957:                 }
 9958:             }
 9959:         }
 9960:     }
 9961:     return %validations;
 9962: }
 9963: 
 9964: sub auto_crsreq_update {
 9965:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9966:         $code,$accessstart,$accessend,$inbound) = @_;
 9967:     my ($homeserver,%crsreqresponse);
 9968:     if ($cdom =~ /^$match_domain$/) {
 9969:         $homeserver = &domain($cdom,'primary');
 9970:     }
 9971:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9972:         my $info;
 9973:         if (ref($inbound) eq 'HASH') {
 9974:             $info = &freeze_escape($inbound);
 9975:         }
 9976:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9977:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9978:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9979:                             &escape($title).':'.&escape($code).':'.
 9980:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9981:                             $homeserver);
 9982:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9983:             my @items = split(/&/,$response);
 9984:             foreach my $item (@items) {
 9985:                 my ($key,$value) = split('=',$item);
 9986:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9987:             }
 9988:         }
 9989:     }
 9990:     return \%crsreqresponse;
 9991: }
 9992: 
 9993: sub auto_export_grades {
 9994:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9995:     my ($homeserver,%exportresponse);
 9996:     if ($cdom =~ /^$match_domain$/) {
 9997:         $homeserver = &domain($cdom,'primary');
 9998:     }
 9999:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10000:         my $info;
10001:         if (ref($inforef) eq 'HASH') {
10002:             $info = &freeze_escape($inforef);
10003:         }
10004:         if (ref($gradesref) eq 'HASH') {
10005:             my $grades = &freeze_escape($gradesref);
10006:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10007:                                 $info.':'.$grades,$homeserver);
10008:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10009:                 my @items = split(/&/,$response);
10010:                 foreach my $item (@items) {
10011:                     my ($key,$value) = split('=',$item);
10012:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10013:                 }
10014:             }
10015:         }
10016:     }
10017:     return \%exportresponse;
10018: }
10019: 
10020: sub check_instcode_cloning {
10021:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10022:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10023:         return;
10024:     }
10025:     my $canclone;
10026:     if (@{$code_order} > 0) {
10027:         my $instcoderegexp ='^';
10028:         my @clonecodes = split(/\&/,$cloner);
10029:         foreach my $item (@{$code_order}) {
10030:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10031:                 foreach my $pair (@clonecodes) {
10032:                     my ($key,$val) = split(/\=/,$pair,2);
10033:                     $val = &unescape($val);
10034:                     if ($key eq $item) {
10035:                         $instcoderegexp .= '('.$val.')';
10036:                         last;
10037:                     }
10038:                 }
10039:             } else {
10040:                 $instcoderegexp .= $codedefaults->{$item};
10041:             }
10042:         }
10043:         $instcoderegexp .= '$';
10044:         my (@from,@to);
10045:         eval {
10046:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10047:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10048:         };
10049:         if ((@from > 0) && (@to > 0)) {
10050:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10051:             if (!@diffs) {
10052:                 $canclone = 1;
10053:             }
10054:         }
10055:     }
10056:     return $canclone;
10057: }
10058: 
10059: sub default_instcode_cloning {
10060:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10061:     my (%codedefaults,@code_order,$canclone);
10062:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10063:         %codedefaults = %{$codedefaultsref};
10064:         @code_order = @{$codeorderref};
10065:     } elsif ($clonedom) {
10066:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10067:     }
10068:     if (($domdefclone) && (@code_order)) {
10069:         my @clonecodes = split(/\+/,$domdefclone);
10070:         my $instcoderegexp ='^';
10071:         foreach my $item (@code_order) {
10072:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10073:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10074:             } else {
10075:                 $instcoderegexp .= $codedefaults{$item};
10076:             }
10077:         }
10078:         $instcoderegexp .= '$';
10079:         my (@from,@to);
10080:         eval {
10081:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10082:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10083:         };
10084:         if ((@from > 0) && (@to > 0)) {
10085:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10086:             if (!@diffs) {
10087:                 $canclone = 1;
10088:             }
10089:         }
10090:     }
10091:     return $canclone;
10092: }
10093: 
10094: # ------------------------------------------------------- Course Group routines
10095: 
10096: sub get_coursegroups {
10097:     my ($cdom,$cnum,$group,$namespace) = @_;
10098:     return(&dump($namespace,$cdom,$cnum,$group));
10099: }
10100: 
10101: sub modify_coursegroup {
10102:     my ($cdom,$cnum,$groupsettings) = @_;
10103:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10104: }
10105: 
10106: sub toggle_coursegroup_status {
10107:     my ($cdom,$cnum,$group,$action) = @_;
10108:     my ($from_namespace,$to_namespace);
10109:     if ($action eq 'delete') {
10110:         $from_namespace = 'coursegroups';
10111:         $to_namespace = 'deleted_groups';
10112:     } else {
10113:         $from_namespace = 'deleted_groups';
10114:         $to_namespace = 'coursegroups';
10115:     }
10116:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10117:     if (my $tmp = &error(%curr_group)) {
10118:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10119:         return ('read error',$tmp);
10120:     } else {
10121:         my %savedsettings = %curr_group; 
10122:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10123:         my $deloutcome;
10124:         if ($result eq 'ok') {
10125:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10126:         } else {
10127:             return ('write error',$result);
10128:         }
10129:         if ($deloutcome eq 'ok') {
10130:             return 'ok';
10131:         } else {
10132:             return ('delete error',$deloutcome);
10133:         }
10134:     }
10135: }
10136: 
10137: sub modify_group_roles {
10138:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10139:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10140:     my $role = 'gr/'.&escape($userprivs);
10141:     my ($uname,$udom) = split(/:/,$user);
10142:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10143:     if ($result eq 'ok') {
10144:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10145:     }
10146:     return $result;
10147: }
10148: 
10149: sub modify_coursegroup_membership {
10150:     my ($cdom,$cnum,$membership) = @_;
10151:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10152:     return $result;
10153: }
10154: 
10155: sub get_active_groups {
10156:     my ($udom,$uname,$cdom,$cnum) = @_;
10157:     my $now = time;
10158:     my %groups = ();
10159:     foreach my $key (keys(%env)) {
10160:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10161:             my ($start,$end) = split(/\./,$env{$key});
10162:             if (($end!=0) && ($end<$now)) { next; }
10163:             if (($start!=0) && ($start>$now)) { next; }
10164:             if ($1 eq $cdom && $2 eq $cnum) {
10165:                 $groups{$3} = $env{$key} ;
10166:             }
10167:         }
10168:     }
10169:     return %groups;
10170: }
10171: 
10172: sub get_group_membership {
10173:     my ($cdom,$cnum,$group) = @_;
10174:     return(&dump('groupmembership',$cdom,$cnum,$group));
10175: }
10176: 
10177: sub get_users_groups {
10178:     my ($udom,$uname,$courseid) = @_;
10179:     my @usersgroups;
10180:     my $cachetime=1800;
10181: 
10182:     my $hashid="$udom:$uname:$courseid";
10183:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10184:     if (defined($cached)) {
10185:         @usersgroups = split(/:/,$grouplist);
10186:     } else {  
10187:         $grouplist = '';
10188:         my $courseurl = &courseid_to_courseurl($courseid);
10189:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10190:         my $access_end = $env{'course.'.$courseid.
10191:                               '.default_enrollment_end_date'};
10192:         my $now = time;
10193:         foreach my $key (keys(%roleshash)) {
10194:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10195:                 my $group = $1;
10196:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10197:                     my $start = $2;
10198:                     my $end = $1;
10199:                     if ($start == -1) { next; } # deleted from group
10200:                     if (($start!=0) && ($start>$now)) { next; }
10201:                     if (($end!=0) && ($end<$now)) {
10202:                         if ($access_end && $access_end < $now) {
10203:                             if ($access_end - $end < 86400) {
10204:                                 push(@usersgroups,$group);
10205:                             }
10206:                         }
10207:                         next;
10208:                     }
10209:                     push(@usersgroups,$group);
10210:                 }
10211:             }
10212:         }
10213:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10214:         $grouplist = join(':',@usersgroups);
10215:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10216:     }
10217:     return @usersgroups;
10218: }
10219: 
10220: sub devalidate_getgroups_cache {
10221:     my ($udom,$uname,$cdom,$cnum)=@_;
10222:     my $courseid = $cdom.'_'.$cnum;
10223: 
10224:     my $hashid="$udom:$uname:$courseid";
10225:     &devalidate_cache_new('getgroups',$hashid);
10226: }
10227: 
10228: # ------------------------------------------------------------------ Plain Text
10229: 
10230: sub plaintext {
10231:     my ($short,$type,$cid,$forcedefault) = @_;
10232:     if ($short =~ m{^cr/}) {
10233: 	return (split('/',$short))[-1];
10234:     }
10235:     if (!defined($cid)) {
10236:         $cid = $env{'request.course.id'};
10237:     }
10238:     my %rolenames = (
10239:                       Course    => 'std',
10240:                       Community => 'alt1',
10241:                       Placement => 'std',
10242:                     );
10243:     if ($cid ne '') {
10244:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10245:             unless ($forcedefault) {
10246:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10247:                 &Apache::lonlocal::mt_escape(\$roletext);
10248:                 return &Apache::lonlocal::mt($roletext);
10249:             }
10250:         }
10251:     }
10252:     if ((defined($type)) && (defined($rolenames{$type})) &&
10253:         (defined($rolenames{$type})) && 
10254:         (defined($prp{$short}{$rolenames{$type}}))) {
10255:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10256:     } elsif ($cid ne '') {
10257:         my $crstype = $env{'course.'.$cid.'.type'};
10258:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10259:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10260:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10261:         }
10262:     }
10263:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10264: }
10265: 
10266: # ----------------------------------------------------------------- Assign Role
10267: 
10268: sub assignrole {
10269:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10270:         $context)=@_;
10271:     my $mrole;
10272:     if ($role =~ /^cr\//) {
10273:         my $cwosec=$url;
10274:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10275: 	unless (&allowed('ccr',$cwosec)) {
10276:            my $refused = 1;
10277:            if ($context eq 'requestcourses') {
10278:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10279:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10280:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10281:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10282:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10283:                            if ($crsenv{'internal.courseowner'} eq
10284:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10285:                                $refused = '';
10286:                            }
10287:                        }
10288:                    }
10289:                }
10290:            }
10291:            if ($refused) {
10292:                &logthis('Refused custom assignrole: '.
10293:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10294:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10295:                return 'refused';
10296:            }
10297:         }
10298:         $mrole='cr';
10299:     } elsif ($role =~ /^gr\//) {
10300:         my $cwogrp=$url;
10301:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10302:         unless (&allowed('mdg',$cwogrp)) {
10303:             &logthis('Refused group assignrole: '.
10304:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10305:                     $env{'user.name'}.' at '.$env{'user.domain'});
10306:             return 'refused';
10307:         }
10308:         $mrole='gr';
10309:     } else {
10310:         my $cwosec=$url;
10311:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10312:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10313:             my $refused;
10314:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10315:                 if (!(&allowed('c'.$role,$url))) {
10316:                     $refused = 1;
10317:                 }
10318:             } else {
10319:                 $refused = 1;
10320:             }
10321:             if ($refused) {
10322:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10323:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10324:                     my %crsenv;
10325:                     if ($role eq 'cc' || $role eq 'co') {
10326:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10327:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10328:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10329:                                 if ($crsenv{'internal.courseowner'} eq 
10330:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10331:                                     $refused = '';
10332:                                 }
10333:                             }
10334:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10335:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10336:                                 if ($crsenv{'internal.courseowner'} eq 
10337:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10338:                                     $refused = '';
10339:                                 }
10340:                             }
10341:                         }
10342:                     }
10343:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10344:                     if ($role eq 'st') {
10345:                         $refused = '';
10346:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10347:                         $refused = '';
10348:                     }
10349:                 } elsif ($context eq 'requestcourses') {
10350:                     my @possroles = ('st','ta','ep','in','cc','co');
10351:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10352:                         my $wrongcc;
10353:                         if ($cnum =~ /^$match_community$/) {
10354:                             $wrongcc = 1 if ($role eq 'cc');
10355:                         } else {
10356:                             $wrongcc = 1 if ($role eq 'co');
10357:                         }
10358:                         unless ($wrongcc) {
10359:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10360:                             if ($crsenv{'internal.courseowner'} eq 
10361:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10362:                                 $refused = '';
10363:                             }
10364:                         }
10365:                     }
10366:                 } elsif ($context eq 'requestauthor') {
10367:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10368:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10369:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10370:                             $refused = '';
10371:                         } else {
10372:                             my %domdefaults = &get_domain_defaults($udom);
10373:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10374:                                 my $checkbystatus;
10375:                                 if ($env{'user.adv'}) { 
10376:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10377:                                     if ($disposition eq 'automatic') {
10378:                                         $refused = '';
10379:                                     } elsif ($disposition eq '') {
10380:                                         $checkbystatus = 1;
10381:                                     } 
10382:                                 } else {
10383:                                     $checkbystatus = 1;
10384:                                 }
10385:                                 if ($checkbystatus) {
10386:                                     if ($env{'environment.inststatus'}) {
10387:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10388:                                         foreach my $type (@inststatuses) {
10389:                                             if (($type ne '') &&
10390:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10391:                                                 $refused = '';
10392:                                             }
10393:                                         }
10394:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10395:                                         $refused = '';
10396:                                     }
10397:                                 }
10398:                             }
10399:                         }
10400:                     }
10401:                 }
10402:                 if ($refused) {
10403:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10404:                              ' '.$role.' '.$end.' '.$start.' by '.
10405: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10406:                     return 'refused';
10407:                 }
10408:             }
10409:         } elsif ($role eq 'au') {
10410:             if ($url ne '/'.$udom.'/') {
10411:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10412:                          ' to assign author role for '.$uname.':'.$udom.
10413:                          ' in domain: '.$url.' refused (wrong domain).');
10414:                 return 'refused';
10415:             }
10416:         }
10417:         $mrole=$role;
10418:     }
10419:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10420:                 "$udom:$uname:$url".'_'."$mrole=$role";
10421:     if ($end) { $command.='_'.$end; }
10422:     if ($start) {
10423: 	if ($end) { 
10424:            $command.='_'.$start; 
10425:         } else {
10426:            $command.='_0_'.$start;
10427:         }
10428:     }
10429:     my $origstart = $start;
10430:     my $origend = $end;
10431:     my $delflag;
10432: # actually delete
10433:     if ($deleteflag) {
10434: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10435: # modify command to delete the role
10436:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10437:                 "$udom:$uname:$url".'_'."$mrole";
10438: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10439: # set start and finish to negative values for userrolelog
10440:            $start=-1;
10441:            $end=-1;
10442:            $delflag = 1;
10443:         }
10444:     }
10445: # send command
10446:     my $answer=&reply($command,&homeserver($uname,$udom));
10447: # log new user role if status is ok
10448:     if ($answer eq 'ok') {
10449: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10450:         if (($role eq 'cc') || ($role eq 'in') ||
10451:             ($role eq 'ep') || ($role eq 'ad') ||
10452:             ($role eq 'ta') || ($role eq 'st') ||
10453:             ($role=~/^cr/) || ($role eq 'gr') ||
10454:             ($role eq 'co')) {
10455: # for course roles, perform group memberships changes triggered by role change.
10456:             unless ($role =~ /^gr/) {
10457:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10458:                                                  $origstart,$selfenroll,$context);
10459:             }
10460:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10461:                            $selfenroll,$context);
10462:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10463:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10464:                  ($role eq 'da')) {
10465:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10466:                            $context);
10467:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10468:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10469:                              $context); 
10470:         }
10471:         if ($role eq 'cc') {
10472:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10473:         }
10474:     }
10475:     return $answer;
10476: }
10477: 
10478: sub autoupdate_coowners {
10479:     my ($url,$end,$start,$uname,$udom) = @_;
10480:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10481:     if (($cdom ne '') && ($cnum ne '')) {
10482:         my $now = time;
10483:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10484:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10485:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10486:             my $instcode = $coursehash{'internal.coursecode'};
10487:             my $xlists = $coursehash{'internal.crosslistings'};
10488:             if ($instcode ne '') {
10489:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10490:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10491:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10492:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10493:                         unless ($result eq 'valid') {
10494:                             if ($xlists ne '') {
10495:                                 foreach my $xlist (split(',',$xlists)) {
10496:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10497:                                     $result =
10498:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10499:                                                                       $inst_crosslist,$uname.':'.$udom);
10500:                                     last if ($result eq 'valid');
10501:                                 }
10502:                             }
10503:                         }
10504:                         if ($result eq 'valid') {
10505:                             if ($coursehash{'internal.co-owners'}) {
10506:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10507:                                     push(@newcoowners,$coowner);
10508:                                 }
10509:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10510:                                     push(@newcoowners,$uname.':'.$udom);
10511:                                 }
10512:                                 @newcoowners = sort(@newcoowners);
10513:                             } else {
10514:                                 push(@newcoowners,$uname.':'.$udom);
10515:                             }
10516:                         } elsif ($coursehash{'internal.co-owners'}) {
10517:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10518:                                 unless ($coowner eq $uname.':'.$udom) {
10519:                                     push(@newcoowners,$coowner);
10520:                                 }
10521:                             }
10522:                             unless (@newcoowners > 0) {
10523:                                 $delcoowners = 1;
10524:                                 $coowners = '';
10525:                             }
10526:                         }
10527:                         if (@newcoowners || $delcoowners) {
10528:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10529:                                             $delcoowners,@newcoowners);
10530:                         }
10531:                     }
10532:                 }
10533:             }
10534:         }
10535:     }
10536: }
10537: 
10538: sub store_coowners {
10539:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10540:     my $cid = $cdom.'_'.$cnum;
10541:     my ($coowners,$delresult,$putresult);
10542:     if (@newcoowners) {
10543:         $coowners = join(',',@newcoowners);
10544:         my %coownershash = (
10545:                             'internal.co-owners' => $coowners,
10546:                            );
10547:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10548:         if ($putresult eq 'ok') {
10549:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10550:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10551:             }
10552:         }
10553:     }
10554:     if ($delcoowners) {
10555:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10556:         if ($delresult eq 'ok') {
10557:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10558:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10559:             }
10560:         }
10561:     }
10562:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10563:         my %crsinfo =
10564:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10565:         if (ref($crsinfo{$cid}) eq 'HASH') {
10566:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10567:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10568:         }
10569:     }
10570: }
10571: 
10572: # -------------------------------------------------- Modify user authentication
10573: # Overrides without validation
10574: 
10575: sub modifyuserauth {
10576:     my ($udom,$uname,$umode,$upass)=@_;
10577:     my $uhome=&homeserver($uname,$udom);
10578:     my $allowed;
10579:     if (&allowed('mau',$udom)) {
10580:         $allowed = 1;
10581:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10582:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10583:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10584:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10585:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10586:         if (($cdom ne '') && ($cnum ne '')) {
10587:             my $is_owner = &is_course_owner($cdom,$cnum);
10588:             if ($is_owner) {
10589:                 $allowed = 1;
10590:             }
10591:         }
10592:     }
10593:     unless ($allowed) { return 'refused'; }
10594:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10595:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10596:              ' in domain '.$env{'request.role.domain'});  
10597:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10598: 		     &escape($upass),$uhome);
10599:     my $ip = &get_requestor_ip();
10600:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10601:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10602:          '(Remote '.$ip.'): '.$reply);
10603:     &log($udom,,$uname,$uhome,
10604:         'Authentication changed by '.$env{'user.domain'}.', '.
10605:                                      $env{'user.name'}.', '.$umode.
10606:          '(Remote '.$ip.'): '.$reply);
10607:     unless ($reply eq 'ok') {
10608:         &logthis('Authentication mode error: '.$reply);
10609: 	return 'error: '.$reply;
10610:     }   
10611:     return 'ok';
10612: }
10613: 
10614: # --------------------------------------------------------------- Modify a user
10615: 
10616: sub modifyuser {
10617:     my ($udom,    $uname, $uid,
10618:         $umode,   $upass, $first,
10619:         $middle,  $last,  $gene,
10620:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10621:     $udom= &LONCAPA::clean_domain($udom);
10622:     $uname=&LONCAPA::clean_username($uname);
10623:     my $showcandelete = 'none';
10624:     if (ref($candelete) eq 'ARRAY') {
10625:         if (@{$candelete} > 0) {
10626:             $showcandelete = join(', ',@{$candelete});
10627:         }
10628:     }
10629:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10630:              $umode.', '.$first.', '.$middle.', '.
10631: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10632:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10633:                                      ' desiredhome not specified'). 
10634:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10635:              ' in domain '.$env{'request.role.domain'});
10636:     my $uhome=&homeserver($uname,$udom,'true');
10637:     my $newuser;
10638:     if ($uhome eq 'no_host') {
10639:         $newuser = 1;
10640:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10641:                 ($umode eq 'lti')) {
10642:             return 'error: more information needed to create new user';
10643:         }
10644:     }
10645: # ----------------------------------------------------------------- Create User
10646:     if (($uhome eq 'no_host') && 
10647: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10648:         my $unhome='';
10649:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10650:             $unhome = $desiredhome;
10651: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10652: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10653:         } else { # load balancing routine for determining $unhome
10654:             my $loadm=10000000;
10655: 	    my %servers = &get_servers($udom,'library');
10656: 	    foreach my $tryserver (keys(%servers)) {
10657: 		my $answer=reply('load',$tryserver);
10658: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10659: 		    $loadm=$answer;
10660: 		    $unhome=$tryserver;
10661: 		}
10662: 	    }
10663:         }
10664:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10665: 	    return 'error: unable to find a home server for '.$uname.
10666:                    ' in domain '.$udom;
10667:         }
10668:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10669:                          &escape($upass),$unhome);
10670: 	unless ($reply eq 'ok') {
10671:             return 'error: '.$reply;
10672:         }   
10673:         $uhome=&homeserver($uname,$udom,'true');
10674:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10675: 	    return 'error: unable verify users home machine.';
10676:         }
10677:     }   # End of creation of new user
10678: # ---------------------------------------------------------------------- Add ID
10679:     if ($uid) {
10680:        $uid=~tr/A-Z/a-z/;
10681:        my %uidhash=&idrget($udom,$uname);
10682:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10683:          && (!$forceid)) {
10684: 	  unless ($uid eq $uidhash{$uname}) {
10685: 	      return 'error: user id "'.$uid.'" does not match '.
10686:                   'current user id "'.$uidhash{$uname}.'".';
10687:           }
10688:        } else {
10689: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10690:        }
10691:     }
10692: # -------------------------------------------------------------- Add names, etc
10693:     my @tmp=&get('environment',
10694: 		   ['firstname','middlename','lastname','generation','id',
10695:                     'permanentemail','inststatus'],
10696: 		   $udom,$uname);
10697:     my (%names,%oldnames);
10698:     if ($tmp[0] =~ m/^error:.*/) { 
10699:         %names=(); 
10700:     } else {
10701:         %names = @tmp;
10702:         %oldnames = %names;
10703:     }
10704: #
10705: # If name, email and/or uid are blank (e.g., because an uploaded file
10706: # of users did not contain them), do not overwrite existing values
10707: # unless field is in $candelete array ref.  
10708: #
10709: 
10710:     my @fields = ('firstname','middlename','lastname','generation',
10711:                   'permanentemail','id');
10712:     my %newvalues;
10713:     if (ref($candelete) eq 'ARRAY') {
10714:         foreach my $field (@fields) {
10715:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10716:                 if ($field eq 'firstname') {
10717:                     $names{$field} = $first;
10718:                 } elsif ($field eq 'middlename') {
10719:                     $names{$field} = $middle;
10720:                 } elsif ($field eq 'lastname') {
10721:                     $names{$field} = $last;
10722:                 } elsif ($field eq 'generation') { 
10723:                     $names{$field} = $gene;
10724:                 } elsif ($field eq 'permanentemail') {
10725:                     $names{$field} = $email;
10726:                 } elsif ($field eq 'id') {
10727:                     $names{$field}  = $uid;
10728:                 }
10729:             }
10730:         }
10731:     }
10732:     if ($first)  { $names{'firstname'}  = $first; }
10733:     if (defined($middle)) { $names{'middlename'} = $middle; }
10734:     if ($last)   { $names{'lastname'}   = $last; }
10735:     if (defined($gene))   { $names{'generation'} = $gene; }
10736:     if ($email) {
10737:        $email=~s/[^\w\@\.\-\,]//gs;
10738:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10739:     }
10740:     if ($uid) { $names{'id'}  = $uid; }
10741:     if (defined($inststatus)) {
10742:         $names{'inststatus'} = '';
10743:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10744:         if (ref($usertypes) eq 'HASH') {
10745:             my @okstatuses; 
10746:             foreach my $item (split(/:/,$inststatus)) {
10747:                 if (defined($usertypes->{$item})) {
10748:                     push(@okstatuses,$item);  
10749:                 }
10750:             }
10751:             if (@okstatuses) {
10752:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10753:             }
10754:         }
10755:     }
10756:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10757:                  $umode.', '.$first.', '.$middle.', '.
10758:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10759:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10760:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10761:     } else {
10762:         $logmsg .= ' during self creation';
10763:     }
10764:     my $changed;
10765:     if ($newuser) {
10766:         $changed = 1;
10767:     } else {
10768:         foreach my $field (@fields) {
10769:             if ($names{$field} ne $oldnames{$field}) {
10770:                 $changed = 1;
10771:                 last;
10772:             }
10773:         }
10774:     }
10775:     unless ($changed) {
10776:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10777:         &logthis($logmsg);
10778:         return 'ok';
10779:     }
10780:     my $reply = &put('environment', \%names, $udom,$uname);
10781:     if ($reply ne 'ok') { 
10782:         return 'error: '.$reply;
10783:     }
10784:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10785:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10786:     }
10787:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10788:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10789:     $logmsg = 'Success modifying user '.$logmsg;
10790:     &logthis($logmsg);
10791:     return 'ok';
10792: }
10793: 
10794: # -------------------------------------------------------------- Modify student
10795: 
10796: sub modifystudent {
10797:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10798:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10799:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10800:     if (!$cid) {
10801: 	unless ($cid=$env{'request.course.id'}) {
10802: 	    return 'not_in_class';
10803: 	}
10804:     }
10805: # --------------------------------------------------------------- Make the user
10806:     my $reply=&modifyuser
10807: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10808:          $desiredhome,$email,$inststatus);
10809:     unless ($reply eq 'ok') { return $reply; }
10810:     # This will cause &modify_student_enrollment to get the uid from the
10811:     # student's environment
10812:     $uid = undef if (!$forceid);
10813:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10814:                                         $gene,$usec,$end,$start,$type,$locktype,
10815:                                         $cid,$selfenroll,$context,$credits,$instsec);
10816:     return $reply;
10817: }
10818: 
10819: sub modify_student_enrollment {
10820:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10821:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10822:     my ($cdom,$cnum,$chome);
10823:     if (!$cid) {
10824: 	unless ($cid=$env{'request.course.id'}) {
10825: 	    return 'not_in_class';
10826: 	}
10827: 	$cdom=$env{'course.'.$cid.'.domain'};
10828: 	$cnum=$env{'course.'.$cid.'.num'};
10829:     } else {
10830: 	($cdom,$cnum)=split(/_/,$cid);
10831:     }
10832:     $chome=$env{'course.'.$cid.'.home'};
10833:     if (!$chome) {
10834: 	$chome=&homeserver($cnum,$cdom);
10835:     }
10836:     if (!$chome) { return 'unknown_course'; }
10837:     # Make sure the user exists
10838:     my $uhome=&homeserver($uname,$udom);
10839:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10840: 	return 'error: no such user';
10841:     }
10842:     # Get student data if we were not given enough information
10843:     if (!defined($first)  || $first  eq '' || 
10844:         !defined($last)   || $last   eq '' || 
10845:         !defined($uid)    || $uid    eq '' || 
10846:         !defined($middle) || $middle eq '' || 
10847:         !defined($gene)   || $gene   eq '') {
10848:         # They did not supply us with enough data to enroll the student, so
10849:         # we need to pick up more information.
10850:         my %tmp = &get('environment',
10851:                        ['firstname','middlename','lastname', 'generation','id']
10852:                        ,$udom,$uname);
10853: 
10854:         #foreach my $key (keys(%tmp)) {
10855:         #    &logthis("key $key = ".$tmp{$key});
10856:         #}
10857:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10858:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10859:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10860:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10861:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10862:     }
10863:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10864:     my $user = "$uname:$udom";
10865:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10866:     my $reply=cput('classlist',
10867: 		   {$user => 
10868: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10869: 		   $cdom,$cnum);
10870:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10871:         &devalidate_getsection_cache($udom,$uname,$cid);
10872:     } else { 
10873: 	return 'error: '.$reply;
10874:     }
10875:     # Add student role to user
10876:     my $uurl='/'.$cid;
10877:     $uurl=~s/\_/\//g;
10878:     if ($usec) {
10879: 	$uurl.='/'.$usec;
10880:     }
10881:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10882:                              $selfenroll,$context);
10883:     if ($result ne 'ok') {
10884:         if ($old_entry{$user} ne '') {
10885:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10886:         } else {
10887:             $reply = &del('classlist',[$user],$cdom,$cnum);
10888:         }
10889:     }
10890:     return $result; 
10891: }
10892: 
10893: sub format_name {
10894:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10895:     my $name;
10896:     if ($first ne 'lastname') {
10897: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10898:     } else {
10899: 	if ($lastname=~/\S/) {
10900: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10901: 	    $name=~s/\s+,/,/;
10902: 	} else {
10903: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10904: 	}
10905:     }
10906:     $name=~s/^\s+//;
10907:     $name=~s/\s+$//;
10908:     $name=~s/\s+/ /g;
10909:     return $name;
10910: }
10911: 
10912: # ------------------------------------------------- Write to course preferences
10913: 
10914: sub writecoursepref {
10915:     my ($courseid,%prefs)=@_;
10916:     $courseid=~s/^\///;
10917:     $courseid=~s/\_/\//g;
10918:     my ($cdomain,$cnum)=split(/\//,$courseid);
10919:     my $chome=homeserver($cnum,$cdomain);
10920:     if (($chome eq '') || ($chome eq 'no_host')) { 
10921: 	return 'error: no such course';
10922:     }
10923:     my $cstring='';
10924:     foreach my $pref (keys(%prefs)) {
10925: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10926:     }
10927:     $cstring=~s/\&$//;
10928:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10929: }
10930: 
10931: # ---------------------------------------------------------- Make/modify course
10932: 
10933: sub createcourse {
10934:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10935:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10936:     $url=&declutter($url);
10937:     my $cid='';
10938:     if ($context eq 'requestcourses') {
10939:         my $can_create = 0;
10940:         my ($ownername,$ownerdom) = split(':',$course_owner);
10941:         if ($udom eq $ownerdom) {
10942:             my $reload;
10943:             if (($callercontext eq 'auto') &&
10944:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10945:                 $reload = 'reload';
10946:             }
10947:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10948:                                   $context)) {
10949:                 $can_create = 1;
10950:             }
10951:         } else {
10952:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10953:                                            $category);
10954:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10955:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10956:                 if (@curr > 0) {
10957:                     my @options = qw(approval validate autolimit);
10958:                     my $optregex = join('|',@options);
10959:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10960:                         $can_create = 1;
10961:                     }
10962:                 }
10963:             }
10964:         }
10965:         if ($can_create) {
10966:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10967:                 unless (&allowed('ccc',$udom)) {
10968:                     return 'refused'; 
10969:                 }
10970:             }
10971:         } else {
10972:             return 'refused';
10973:         }
10974:     } elsif (!&allowed('ccc',$udom)) {
10975:         return 'refused';
10976:     }
10977: # --------------------------------------------------------------- Get Unique ID
10978:     my $uname;
10979:     if ($cnum =~ /^$match_courseid$/) {
10980:         my $chome=&homeserver($cnum,$udom,'true');
10981:         if (($chome eq '') || ($chome eq 'no_host')) {
10982:             $uname = $cnum;
10983:         } else {
10984:             $uname = &generate_coursenum($udom,$crstype);
10985:         }
10986:     } else {
10987:         $uname = &generate_coursenum($udom,$crstype);
10988:     }
10989:     return $uname if ($uname =~ /^error/);
10990: # -------------------------------------------------- Check supplied server name
10991:     if (!defined($course_server)) {
10992:         if (defined(&domain($udom,'primary'))) {
10993:             $course_server = &domain($udom,'primary');
10994:         } else {
10995:             $course_server = $env{'user.home'}; 
10996:         }
10997:     }
10998:     my %host_servers =
10999:         &Apache::lonnet::get_servers($udom,'library');
11000:     unless ($host_servers{$course_server}) {
11001:         return 'error: invalid home server for course: '.$course_server;
11002:     }
11003: # ------------------------------------------------------------- Make the course
11004:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11005:                       $course_server);
11006:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11007:     my $uhome=&homeserver($uname,$udom,'true');
11008:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11009: 	return 'error: no such course';
11010:     }
11011: # ----------------------------------------------------------------- Course made
11012: # log existence
11013:     my $now = time;
11014:     my $newcourse = {
11015:                     $udom.'_'.$uname => {
11016:                                      description => $description,
11017:                                      inst_code   => $inst_code,
11018:                                      owner       => $course_owner,
11019:                                      type        => $crstype,
11020:                                      creator     => $env{'user.name'}.':'.
11021:                                                     $env{'user.domain'},
11022:                                      created     => $now,
11023:                                      context     => $context,
11024:                                                 },
11025:                     };
11026:     &courseidput($udom,$newcourse,$uhome,'notime');
11027: # set toplevel url
11028:     my $topurl=$url;
11029:     unless ($nonstandard) {
11030: # ------------------------------------------ For standard courses, make top url
11031:         my $mapurl=&clutter($url);
11032:         if ($mapurl eq '/res/') { $mapurl=''; }
11033:         $env{'form.initmap'}=(<<ENDINITMAP);
11034: <map>
11035: <resource id="1" type="start"></resource>
11036: <resource id="2" src="$mapurl"></resource>
11037: <resource id="3" type="finish"></resource>
11038: <link index="1" from="1" to="2"></link>
11039: <link index="2" from="2" to="3"></link>
11040: </map>
11041: ENDINITMAP
11042:         $topurl=&declutter(
11043:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11044:                           );
11045:     }
11046: # ----------------------------------------------------------- Write preferences
11047:     &writecoursepref($udom.'_'.$uname,
11048:                      ('description'              => $description,
11049:                       'url'                      => $topurl,
11050:                       'internal.creator'         => $env{'user.name'}.':'.
11051:                                                     $env{'user.domain'},
11052:                       'internal.created'         => $now,
11053:                       'internal.creationcontext' => $context)
11054:                     );
11055:     return '/'.$udom.'/'.$uname;
11056: }
11057: 
11058: # ------------------------------------------------------------------- Create ID
11059: sub generate_coursenum {
11060:     my ($udom,$crstype) = @_;
11061:     my $domdesc = &domain($udom);
11062:     return 'error: invalid domain' if ($domdesc eq '');
11063:     my $first;
11064:     if ($crstype eq 'Community') {
11065:         $first = '0';
11066:     } else {
11067:         $first = int(1+rand(9)); 
11068:     } 
11069:     my $uname=$first.
11070:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11071:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11072:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11073: # ----------------------------------------------- Make sure that does not exist
11074:     my $uhome=&homeserver($uname,$udom,'true');
11075:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11076:         if ($crstype eq 'Community') {
11077:             $first = '0';
11078:         } else {
11079:             $first = int(1+rand(9));
11080:         }
11081:         $uname=$first.
11082:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11083:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11084:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11085:         $uhome=&homeserver($uname,$udom,'true');
11086:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11087:             return 'error: unable to generate unique course-ID';
11088:         }
11089:     }
11090:     return $uname;
11091: }
11092: 
11093: sub is_course {
11094:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11095:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11096: 
11097:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11098:     my $uhome=&homeserver($cnum,$cdom);
11099:     my $iscourse;
11100:     if (grep { $_ eq $uhome } current_machine_ids()) {
11101:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11102:     } else {
11103:         my $hashid = $cdom.':'.$cnum;
11104:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11105:         unless (defined($cached)) {
11106:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11107:                                         $cnum,undef,undef,'.');
11108:             $iscourse = 0;
11109:             if (exists($courses{$cdom.'_'.$cnum})) {
11110:                 $iscourse = 1;
11111:             }
11112:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11113:         }
11114:     }
11115:     return unless ($iscourse);
11116:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11117: }
11118: 
11119: sub store_userdata {
11120:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11121:     my $result;
11122:     if ($datakey ne '') {
11123:         if (ref($storehash) eq 'HASH') {
11124:             if ($udom eq '' || $uname eq '') {
11125:                 $udom = $env{'user.domain'};
11126:                 $uname = $env{'user.name'};
11127:             }
11128:             my $uhome=&homeserver($uname,$udom);
11129:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11130:                 $result = 'error: no_host';
11131:             } else {
11132:                 $storehash->{'ip'} = &get_requestor_ip();
11133:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11134: 
11135:                 my $namevalue='';
11136:                 foreach my $key (keys(%{$storehash})) {
11137:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11138:                 }
11139:                 $namevalue=~s/\&$//;
11140:                 unless ($namespace eq 'courserequests') {
11141:                     $datakey = &escape($datakey);
11142:                 }
11143:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11144:                                   $namevalue,$uhome);
11145:             }
11146:         } else {
11147:             $result = 'error: data to store was not a hash reference'; 
11148:         }
11149:     } else {
11150:         $result= 'error: invalid requestkey'; 
11151:     }
11152:     return $result;
11153: }
11154: 
11155: # ---------------------------------------------------------- Assign Custom Role
11156: 
11157: sub assigncustomrole {
11158:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11159:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11160:                        $end,$start,$deleteflag,$selfenroll,$context);
11161: }
11162: 
11163: # ----------------------------------------------------------------- Revoke Role
11164: 
11165: sub revokerole {
11166:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11167:     my $now=time;
11168:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11169: }
11170: 
11171: # ---------------------------------------------------------- Revoke Custom Role
11172: 
11173: sub revokecustomrole {
11174:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11175:     my $now=time;
11176:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11177:            $deleteflag,$selfenroll,$context);
11178: }
11179: 
11180: # ------------------------------------------------------------ Disk usage
11181: sub diskusage {
11182:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11183:     $directorypath =~ s/\/$//;
11184:     my $listing=&reply('du2:'.&escape($directorypath).':'
11185:                        .&escape($getpropath).':'.&escape($uname).':'
11186:                        .&escape($udom),homeserver($uname,$udom));
11187:     if ($listing eq 'unknown_cmd') {
11188:         if ($getpropath) {
11189:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11190:         }
11191:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11192:     }
11193:     return $listing;
11194: }
11195: 
11196: sub is_locked {
11197:     my ($file_name, $domain, $user, $which) = @_;
11198:     my @check;
11199:     my $is_locked;
11200:     push (@check,$file_name);
11201:     my %locked = &get('file_permissions',\@check,
11202: 		      $env{'user.domain'},$env{'user.name'});
11203:     my ($tmp)=keys(%locked);
11204:     if ($tmp=~/^error:/) { undef(%locked); }
11205:     
11206:     if (ref($locked{$file_name}) eq 'ARRAY') {
11207:         $is_locked = 'false';
11208:         foreach my $entry (@{$locked{$file_name}}) {
11209:            if (ref($entry) eq 'ARRAY') {
11210:                $is_locked = 'true';
11211:                if (ref($which) eq 'ARRAY') {
11212:                    push(@{$which},$entry);
11213:                } else {
11214:                    last;
11215:                }
11216:            }
11217:        }
11218:     } else {
11219:         $is_locked = 'false';
11220:     }
11221:     return $is_locked;
11222: }
11223: 
11224: sub declutter_portfile {
11225:     my ($file) = @_;
11226:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11227:     return $file;
11228: }
11229: 
11230: # ------------------------------------------------------------- Mark as Read Only
11231: 
11232: sub mark_as_readonly {
11233:     my ($domain,$user,$files,$what) = @_;
11234:     my %current_permissions = &dump('file_permissions',$domain,$user);
11235:     my ($tmp)=keys(%current_permissions);
11236:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11237:     foreach my $file (@{$files}) {
11238: 	$file = &declutter_portfile($file);
11239:         push(@{$current_permissions{$file}},$what);
11240:     }
11241:     &put('file_permissions',\%current_permissions,$domain,$user);
11242:     return;
11243: }
11244: 
11245: # ------------------------------------------------------------Save Selected Files
11246: 
11247: sub save_selected_files {
11248:     my ($user, $path, @files) = @_;
11249:     my $filename = $user."savedfiles";
11250:     my @other_files = &files_not_in_path($user, $path);
11251:     open (OUT,'>',LONCAPA::tempdir().$filename);
11252:     foreach my $file (@files) {
11253:         print (OUT $env{'form.currentpath'}.$file."\n");
11254:     }
11255:     foreach my $file (@other_files) {
11256:         print (OUT $file."\n");
11257:     }
11258:     close (OUT);
11259:     return 'ok';
11260: }
11261: 
11262: sub clear_selected_files {
11263:     my ($user) = @_;
11264:     my $filename = $user."savedfiles";
11265:     open (OUT,'>',LONCAPA::tempdir().$filename);
11266:     print (OUT undef);
11267:     close (OUT);
11268:     return ("ok");    
11269: }
11270: 
11271: sub files_in_path {
11272:     my ($user, $path) = @_;
11273:     my $filename = $user."savedfiles";
11274:     my %return_files;
11275:     open (IN,'<',LONCAPA::tempdir().$filename);
11276:     while (my $line_in = <IN>) {
11277:         chomp ($line_in);
11278:         my @paths_and_file = split (m!/!, $line_in);
11279:         my $file_part = pop (@paths_and_file);
11280:         my $path_part = join ('/', @paths_and_file);
11281:         $path_part.='/';
11282:         my $path_and_file = $path_part.$file_part;
11283:         if ($path_part eq $path) {
11284:             $return_files{$file_part}= 'selected';
11285:         }
11286:     }
11287:     close (IN);
11288:     return (\%return_files);
11289: }
11290: 
11291: # called in portfolio select mode, to show files selected NOT in current directory
11292: sub files_not_in_path {
11293:     my ($user, $path) = @_;
11294:     my $filename = $user."savedfiles";
11295:     my @return_files;
11296:     my $path_part;
11297:     open(IN, '<',LONCAPA::tempdir().$filename);
11298:     while (my $line = <IN>) {
11299:         #ok, I know it's clunky, but I want it to work
11300:         my @paths_and_file = split(m|/|, $line);
11301:         my $file_part = pop(@paths_and_file);
11302:         chomp($file_part);
11303:         my $path_part = join('/', @paths_and_file);
11304:         $path_part .= '/';
11305:         my $path_and_file = $path_part.$file_part;
11306:         if ($path_part ne $path) {
11307:             push(@return_files, ($path_and_file));
11308:         }
11309:     }
11310:     close(OUT);
11311:     return (@return_files);
11312: }
11313: 
11314: #------------------------------Submitted/Handedback Portfolio Files Versioning
11315:  
11316: sub portfiles_versioning {
11317:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11318:     my $portfolio_root = '/userfiles/portfolio';
11319:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11320:     foreach my $file (@{$portfiles}) {
11321:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11322:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11323:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11324:         my $getpropath = 1;
11325:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11326:                                              $stu_name,$getpropath);
11327:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11328:         my $new_answer = 
11329:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11330:         if ($new_answer ne 'problem getting file') {
11331:             push(@{$versioned_portfiles}, $directory.$new_answer);
11332:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11333:                               [$symb,$env{'request.course.id'},'graded']);
11334:         }
11335:     }
11336: }
11337: 
11338: sub get_next_version {
11339:     my ($answer_name, $answer_ext, $dir_list) = @_;
11340:     my $version;
11341:     if (ref($dir_list) eq 'ARRAY') {
11342:         foreach my $row (@{$dir_list}) {
11343:             my ($file) = split(/\&/,$row,2);
11344:             my ($file_name,$file_version,$file_ext) =
11345:                 &file_name_version_ext($file);
11346:             if (($file_name eq $answer_name) &&
11347:                 ($file_ext eq $answer_ext)) {
11348:                      # gets here if filename and extension match,
11349:                      # regardless of version
11350:                 if ($file_version ne '') {
11351:                     # a versioned file is found  so save it for later
11352:                     if ($file_version > $version) {
11353:                         $version = $file_version;
11354:                     }
11355:                 }
11356:             }
11357:         }
11358:     }
11359:     $version ++;
11360:     return($version);
11361: }
11362: 
11363: sub version_selected_portfile {
11364:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11365:     my ($answer_name,$answer_ver,$answer_ext) =
11366:         &file_name_version_ext($file_name);
11367:     my $new_answer;
11368:     $env{'form.copy'} =
11369:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11370:     if($env{'form.copy'} eq '-1') {
11371:         $new_answer = 'problem getting file';
11372:     } else {
11373:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11374:         my $copy_result = 
11375:             &finishuserfileupload($stu_name,$domain,'copy',
11376:                                   '/portfolio'.$directory.$new_answer);
11377:     }
11378:     undef($env{'form.copy'});
11379:     return ($new_answer);
11380: }
11381: 
11382: sub file_name_version_ext {
11383:     my ($file)=@_;
11384:     my @file_parts = split(/\./, $file);
11385:     my ($name,$version,$ext);
11386:     if (@file_parts > 1) {
11387:         $ext=pop(@file_parts);
11388:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11389:             $version=pop(@file_parts);
11390:         }
11391:         $name=join('.',@file_parts);
11392:     } else {
11393:         $name=join('.',@file_parts);
11394:     }
11395:     return($name,$version,$ext);
11396: }
11397: 
11398: #----------------------------------------------Get portfolio file permissions
11399: 
11400: sub get_portfile_permissions {
11401:     my ($domain,$user) = @_;
11402:     my %current_permissions = &dump('file_permissions',$domain,$user);
11403:     my ($tmp)=keys(%current_permissions);
11404:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11405:     return \%current_permissions;
11406: }
11407: 
11408: #---------------------------------------------Get portfolio file access controls
11409: 
11410: sub get_access_controls {
11411:     my ($current_permissions,$group,$file) = @_;
11412:     my %access;
11413:     my $real_file = $file;
11414:     $file =~ s/\.meta$//;
11415:     if (defined($file)) {
11416:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11417:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11418:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11419:             }
11420:         }
11421:     } else {
11422:         foreach my $key (keys(%{$current_permissions})) {
11423:             if ($key =~ /\0accesscontrol$/) {
11424:                 if (defined($group)) {
11425:                     if ($key !~ m-^\Q$group\E/-) {
11426:                         next;
11427:                     }
11428:                 }
11429:                 my ($fullpath) = split(/\0/,$key);
11430:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11431:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11432:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11433:                     }
11434:                 }
11435:             }
11436:         }
11437:     }
11438:     return %access;
11439: }
11440: 
11441: sub modify_access_controls {
11442:     my ($file_name,$changes,$domain,$user)=@_;
11443:     my ($outcome,$deloutcome);
11444:     my %store_permissions;
11445:     my %new_values;
11446:     my %new_control;
11447:     my %translation;
11448:     my @deletions = ();
11449:     my $now = time;
11450:     if (exists($$changes{'activate'})) {
11451:         if (ref($$changes{'activate'}) eq 'HASH') {
11452:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11453:             my $numnew = scalar(@newitems);
11454:             for (my $i=0; $i<$numnew; $i++) {
11455:                 my $newkey = $newitems[$i];
11456:                 my $newid = &Apache::loncommon::get_cgi_id();
11457:                 if ($newkey =~ /^\d+:/) { 
11458:                     $newkey =~ s/^(\d+)/$newid/;
11459:                     $translation{$1} = $newid;
11460:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11461:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11462:                     $translation{$1} = $newid;
11463:                 }
11464:                 $new_values{$file_name."\0".$newkey} = 
11465:                                           $$changes{'activate'}{$newitems[$i]};
11466:                 $new_control{$newkey} = $now;
11467:             }
11468:         }
11469:     }
11470:     my %todelete;
11471:     my %changed_items;
11472:     foreach my $action ('delete','update') {
11473:         if (exists($$changes{$action})) {
11474:             if (ref($$changes{$action}) eq 'HASH') {
11475:                 foreach my $key (keys(%{$$changes{$action}})) {
11476:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11477:                     if ($action eq 'delete') { 
11478:                         $todelete{$itemnum} = 1;
11479:                     } else {
11480:                         $changed_items{$itemnum} = $key;
11481:                     }
11482:                 }
11483:             }
11484:         }
11485:     }
11486:     # get lock on access controls for file.
11487:     my $lockhash = {
11488:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11489:                                                        ':'.$env{'user.domain'},
11490:                    }; 
11491:     my $tries = 0;
11492:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11493:    
11494:     while (($gotlock ne 'ok') && $tries < 10) {
11495:         $tries ++;
11496:         sleep(0.1);
11497:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11498:     }
11499:     if ($gotlock eq 'ok') {
11500:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11501:         my ($tmp)=keys(%curr_permissions);
11502:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11503:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11504:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11505:             if (ref($curr_controls) eq 'HASH') {
11506:                 foreach my $control_item (keys(%{$curr_controls})) {
11507:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11508:                     if (defined($todelete{$itemnum})) {
11509:                         push(@deletions,$file_name."\0".$control_item);
11510:                     } else {
11511:                         if (defined($changed_items{$itemnum})) {
11512:                             $new_control{$changed_items{$itemnum}} = $now;
11513:                             push(@deletions,$file_name."\0".$control_item);
11514:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11515:                         } else {
11516:                             $new_control{$control_item} = $$curr_controls{$control_item};
11517:                         }
11518:                     }
11519:                 }
11520:             }
11521:         }
11522:         my ($group);
11523:         if (&is_course($domain,$user)) {
11524:             ($group,my $file) = split(/\//,$file_name,2);
11525:         }
11526:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11527:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11528:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11529:         #  remove lock
11530:         my @del_lock = ($file_name."\0".'locked_access_records');
11531:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11532:         my $sqlresult =
11533:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11534:                                     $group);
11535:     } else {
11536:         $outcome = "error: could not obtain lockfile\n";  
11537:     }
11538:     return ($outcome,$deloutcome,\%new_values,\%translation);
11539: }
11540: 
11541: sub make_public_indefinitely {
11542:     my (@requrl) = @_;
11543:     return &automated_portfile_access('public',\@requrl);
11544: }
11545: 
11546: sub automated_portfile_access {
11547:     my ($accesstype,$addsref,$delsref,$info) = @_;
11548:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11549:         return 'invalid';
11550:     }
11551:     my %urls;
11552:     if (ref($addsref) eq 'ARRAY') {
11553:         foreach my $requrl (@{$addsref}) {
11554:             if (&is_portfolio_url($requrl)) {
11555:                 unless (exists($urls{$requrl})) {
11556:                     $urls{$requrl} = 'add';
11557:                 }
11558:             }
11559:         }
11560:     }
11561:     if (ref($delsref) eq 'ARRAY') {
11562:         foreach my $requrl (@{$delsref}) { 
11563:             if (&is_portfolio_url($requrl)) {
11564:                 unless (exists($urls{$requrl})) {
11565:                     $urls{$requrl} = 'delete'; 
11566:                 }
11567:             }
11568:         }
11569:     }
11570:     unless (keys(%urls)) {
11571:         return 'invalid';
11572:     }
11573:     my $ip;
11574:     if ($accesstype eq 'ip') {
11575:         if (ref($info) eq 'HASH') {
11576:             if ($info->{'ip'} ne '') {
11577:                 $ip = $info->{'ip'};
11578:             }
11579:         }
11580:         if ($ip eq '') {
11581:             return 'invalid';
11582:         }
11583:     }
11584:     my $errors;
11585:     my $now = time;
11586:     my %current_perms;
11587:     foreach my $requrl (sort(keys(%urls))) {
11588:         my $action;
11589:         if ($urls{$requrl} eq 'add') {
11590:             $action = 'activate';
11591:         } else {
11592:             $action = 'none';
11593:         }
11594:         my $aclnum = 0;
11595:         my (undef,$udom,$unum,$file_name,$group) =
11596:             &parse_portfolio_url($requrl);
11597:         unless (exists($current_perms{$unum.':'.$udom})) {
11598:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11599:         }
11600:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11601:                                                    $group,$file_name);
11602:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11603:             my ($num,$scope,$end,$start) = 
11604:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11605:             if ($scope eq $accesstype) {
11606:                 if (($start <= $now) && ($end == 0)) {
11607:                     if ($accesstype eq 'ip') {
11608:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11609:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11610:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11611:                                     if ($urls{$requrl} eq 'add') {
11612:                                         $action = 'none';
11613:                                         last;
11614:                                     } else {
11615:                                         $action = 'delete';
11616:                                         $aclnum = $num;
11617:                                         last;
11618:                                     }
11619:                                 }
11620:                             }
11621:                         }
11622:                     } elsif ($accesstype eq 'public') {
11623:                         if ($urls{$requrl} eq 'add') {
11624:                             $action = 'none';
11625:                             last;
11626:                         } else {
11627:                             $action = 'delete';
11628:                             $aclnum = $num;
11629:                             last;
11630:                         }
11631:                     }
11632:                 } elsif ($accesstype eq 'public') {
11633:                     $action = 'update';
11634:                     $aclnum = $num;
11635:                     last;
11636:                 }
11637:             }
11638:         }
11639:         if ($action eq 'none') {
11640:             next;
11641:         } else {
11642:             my %changes;
11643:             my $newend = 0;
11644:             my $newstart = $now;
11645:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11646:             $changes{$action}{$newkey} = {
11647:                 type => $accesstype,
11648:                 time => {
11649:                     start => $newstart,
11650:                     end   => $newend,
11651:                 },
11652:             };
11653:             if ($accesstype eq 'ip') {
11654:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11655:             }
11656:             my ($outcome,$deloutcome,$new_values,$translation) =
11657:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11658:             unless ($outcome eq 'ok') {
11659:                 $errors .= $outcome.' ';
11660:             }
11661:         }
11662:     }
11663:     if ($errors) {
11664:         $errors =~ s/\s$//;
11665:         return $errors;
11666:     } else {
11667:         return 'ok';
11668:     }
11669: }
11670: 
11671: #------------------------------------------------------Get Marked as Read Only
11672: 
11673: sub get_marked_as_readonly {
11674:     my ($domain,$user,$what,$group) = @_;
11675:     my $current_permissions = &get_portfile_permissions($domain,$user);
11676:     my @readonly_files;
11677:     my $cmp1=$what;
11678:     if (ref($what)) { $cmp1=join('',@{$what}) };
11679:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11680:         if (defined($group)) {
11681:             if ($file_name !~ m-^\Q$group\E/-) {
11682:                 next;
11683:             }
11684:         }
11685:         if (ref($value) eq "ARRAY"){
11686:             foreach my $stored_what (@{$value}) {
11687:                 my $cmp2=$stored_what;
11688:                 if (ref($stored_what) eq 'ARRAY') {
11689:                     $cmp2=join('',@{$stored_what});
11690:                 }
11691:                 if ($cmp1 eq $cmp2) {
11692:                     push(@readonly_files, $file_name);
11693:                     last;
11694:                 } elsif (!defined($what)) {
11695:                     push(@readonly_files, $file_name);
11696:                     last;
11697:                 }
11698:             }
11699:         }
11700:     }
11701:     return @readonly_files;
11702: }
11703: #-----------------------------------------------------------Get Marked as Read Only Hash
11704: 
11705: sub get_marked_as_readonly_hash {
11706:     my ($current_permissions,$group,$what) = @_;
11707:     my %readonly_files;
11708:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11709:         if (defined($group)) {
11710:             if ($file_name !~ m-^\Q$group\E/-) {
11711:                 next;
11712:             }
11713:         }
11714:         if (ref($value) eq "ARRAY"){
11715:             foreach my $stored_what (@{$value}) {
11716:                 if (ref($stored_what) eq 'ARRAY') {
11717:                     foreach my $lock_descriptor(@{$stored_what}) {
11718:                         if ($lock_descriptor eq 'graded') {
11719:                             $readonly_files{$file_name} = 'graded';
11720:                         } elsif ($lock_descriptor eq 'handback') {
11721:                             $readonly_files{$file_name} = 'handback';
11722:                         } else {
11723:                             if (!exists($readonly_files{$file_name})) {
11724:                                 $readonly_files{$file_name} = 'locked';
11725:                             }
11726:                         }
11727:                     }
11728:                 } 
11729:             }
11730:         } 
11731:     }
11732:     return %readonly_files;
11733: }
11734: # ------------------------------------------------------------ Unmark as Read Only
11735: 
11736: sub unmark_as_readonly {
11737:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11738:     # for portfolio submissions, $what contains [$symb,$crsid] 
11739:     my ($domain,$user,$what,$file_name,$group) = @_;
11740:     $file_name = &declutter_portfile($file_name);
11741:     my $symb_crs = $what;
11742:     if (ref($what)) { $symb_crs=join('',@$what); }
11743:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11744:     my ($tmp)=keys(%current_permissions);
11745:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11746:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11747:     foreach my $file (@readonly_files) {
11748: 	my $clean_file = &declutter_portfile($file);
11749: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11750: 	my $current_locks = $current_permissions{$file};
11751:         my @new_locks;
11752:         my @del_keys;
11753:         if (ref($current_locks) eq "ARRAY"){
11754:             foreach my $locker (@{$current_locks}) {
11755:                 my $compare=$locker;
11756:                 if (ref($locker) eq 'ARRAY') {
11757:                     $compare=join('',@{$locker});
11758:                     if ($compare ne $symb_crs) {
11759:                         push(@new_locks, $locker);
11760:                     }
11761:                 }
11762:             }
11763:             if (scalar(@new_locks) > 0) {
11764:                 $current_permissions{$file} = \@new_locks;
11765:             } else {
11766:                 push(@del_keys, $file);
11767:                 &del('file_permissions',\@del_keys, $domain, $user);
11768:                 delete($current_permissions{$file});
11769:             }
11770:         }
11771:     }
11772:     &put('file_permissions',\%current_permissions,$domain,$user);
11773:     return;
11774: }
11775: 
11776: # ------------------------------------------------------------ Directory lister
11777: 
11778: sub dirlist {
11779:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11780:     $uri=~s/^\///;
11781:     $uri=~s/\/$//;
11782:     my ($udom, $uname);
11783:     if ($getuserdir) {
11784:         $udom = $userdomain;
11785:         $uname = $username;
11786:     } else {
11787:         (undef,$udom,$uname)=split(/\//,$uri);
11788:         if(defined($userdomain)) {
11789:             $udom = $userdomain;
11790:         }
11791:         if(defined($username)) {
11792:             $uname = $username;
11793:         }
11794:     }
11795:     my ($dirRoot,$listing,@listing_results);
11796: 
11797:     $dirRoot = $perlvar{'lonDocRoot'};
11798:     if (defined($getpropath)) {
11799:         $dirRoot = &propath($udom,$uname);
11800:         $dirRoot =~ s/\/$//;
11801:     } elsif (defined($getuserdir)) {
11802:         my $subdir=$uname.'__';
11803:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11804:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11805:                    ."/$udom/$subdir/$uname";
11806:     } elsif (defined($alternateRoot)) {
11807:         $dirRoot = $alternateRoot;
11808:     }
11809: 
11810:     if($udom) {
11811:         if($uname) {
11812:             my $uhome = &homeserver($uname,$udom);
11813:             if ($uhome eq 'no_host') {
11814:                 return ([],'no_host');
11815:             }
11816:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11817:                               .$getuserdir.':'.&escape($dirRoot)
11818:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11819:             if ($listing eq 'unknown_cmd') {
11820:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11821:             } else {
11822:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11823:             }
11824:             if ($listing eq 'unknown_cmd') {
11825:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11826:                 @listing_results = split(/:/,$listing);
11827:             } else {
11828:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11829:             }
11830:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11831:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11832:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11833:                 return ([],$listing);
11834:             } else {
11835:                 return (\@listing_results);
11836:             }
11837:         } elsif(!$alternateRoot) {
11838:             my (%allusers,%listerror);
11839: 	    my %servers = &get_servers($udom,'library');
11840:  	    foreach my $tryserver (keys(%servers)) {
11841:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11842:                                   &escape($udom),$tryserver);
11843:                 if ($listing eq 'unknown_cmd') {
11844: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11845: 				      $udom, $tryserver);
11846:                 } else {
11847:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11848:                 }
11849: 		if ($listing eq 'unknown_cmd') {
11850: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11851: 				      $udom, $tryserver);
11852: 		    @listing_results = split(/:/,$listing);
11853: 		} else {
11854: 		    @listing_results =
11855: 			map { &unescape($_); } split(/:/,$listing);
11856: 		}
11857:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11858:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11859:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11860:                     $listerror{$tryserver} = $listing;
11861:                 } else {
11862: 		    foreach my $line (@listing_results) {
11863: 			my ($entry) = split(/&/,$line,2);
11864: 			$allusers{$entry} = 1;
11865: 		    }
11866: 		}
11867:             }
11868:             my @alluserslist=();
11869:             foreach my $user (sort(keys(%allusers))) {
11870:                 push(@alluserslist,$user.'&user');
11871:             }
11872: 
11873:             if (!%listerror) {
11874:                 # no errors
11875:                 return (\@alluserslist);
11876:             } elsif (scalar(keys(%servers)) == 1) {
11877:                 # one library server, one error 
11878:                 my ($key) = keys(%listerror);
11879:                 return (\@alluserslist, $listerror{$key});
11880:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11881:                 # con_lost indicates that we might miss data from at least one
11882:                 # library server
11883:                 return (\@alluserslist, 'con_lost');
11884:             } else {
11885:                 # multiple library servers and no con_lost -> data should be
11886:                 # complete. 
11887:                 return (\@alluserslist);
11888:             }
11889: 
11890:         } else {
11891:             return ([],'missing username');
11892:         }
11893:     } elsif(!defined($getpropath)) {
11894:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11895:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11896:         return (\@all_domains);
11897:     } else {
11898:         return ([],'missing domain');
11899:     }
11900: }
11901: 
11902: # --------------------------------------------- GetFileTimestamp
11903: # This function utilizes dirlist and returns the date stamp for
11904: # when it was last modified.  It will also return an error of -1
11905: # if an error occurs
11906: 
11907: sub GetFileTimestamp {
11908:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11909:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11910:     $studentName   = &LONCAPA::clean_username($studentName);
11911:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11912:                                     undef,$getuserdir);
11913:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11914:         return -1;
11915:     }
11916:     if (ref($fileref) eq 'ARRAY') {
11917:         my @stats = split('&',$fileref->[0]);
11918:         # @stats contains first the filename, then the stat output
11919:         return $stats[10]; # so this is 10 instead of 9.
11920:     } else {
11921:         return -1;
11922:     }
11923: }
11924: 
11925: sub stat_file {
11926:     my ($uri) = @_;
11927:     $uri = &clutter_with_no_wrapper($uri);
11928: 
11929:     my ($udom,$uname,$file);
11930:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11931: 	($udom,$uname,$file) =
11932: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11933: 	$file = 'userfiles/'.$file;
11934:     }
11935:     if ($uri =~ m-^/res/-) {
11936: 	($udom,$uname) = 
11937: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11938: 	$file = $uri;
11939:     }
11940: 
11941:     if (!$udom || !$uname || !$file) {
11942: 	# unable to handle the uri
11943: 	return ();
11944:     }
11945:     my $getpropath;
11946:     if ($file =~ /^userfiles\//) {
11947:         $getpropath = 1;
11948:     }
11949:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11950:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11951:         return ();
11952:     } else {
11953:         if (ref($listref) eq 'ARRAY') {
11954:             my @stats = split('&',$listref->[0]);
11955: 	    shift(@stats); #filename is first
11956: 	    return @stats;
11957:         }
11958:     }
11959:     return ();
11960: }
11961: 
11962: # --------------------------------------------------------- recursedirs
11963: # Recursive function to traverse either a specific user's Authoring Space
11964: # or corresponding Published Resource Space, and populate the hash ref:
11965: # $dirhashref with URLs of all directories, and if $filehashref hash
11966: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11967: # or .rights files in resource space, and .meta, .save, .log, and .bak
11968: # files in Authoring Space.
11969: #
11970: # Inputs:
11971: #
11972: # $is_home - true if current server is home server for user's space
11973: # $context - either: priv, or res respectively for Authoring or Resource Space.
11974: # $docroot - Document root (i.e., /home/httpd/html
11975: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11976: # $relpath - Current path (relative to top level).
11977: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11978: # $filehashref - reference to hash to populate with URLs of files (Optional)
11979: #
11980: # Returns: nothing
11981: #
11982: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11983: #
11984: # Currently used by interface/londocs.pm to create linked select boxes for
11985: # directory and filename to import a Course "Author" resource into a course, and
11986: # also to create linked select boxes for Authoring Space and Directory to choose
11987: # save location for creation of a new "standard" problem from the Course Editor.
11988: #
11989: 
11990: sub recursedirs {
11991:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11992:     return unless (ref($dirhashref) eq 'HASH');
11993:     my $currpath = $docroot.$toppath;
11994:     if ($relpath) {
11995:         $currpath .= "/$relpath";
11996:     }
11997:     my $savefile;
11998:     if (ref($filehashref)) {
11999:         $savefile = 1;
12000:     }
12001:     if ($is_home) {
12002:         if (opendir(my $dirh,$currpath)) {
12003:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12004:                 next if ($item eq '');
12005:                 if (-d "$currpath/$item") {
12006:                     my $newpath;
12007:                     if ($relpath) {
12008:                         $newpath = "$relpath/$item";
12009:                     } else {
12010:                         $newpath = $item;
12011:                     }
12012:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12013:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12014:                 } elsif ($savefile) {
12015:                     if ($context eq 'priv') {
12016:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12017:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12018:                         }
12019:                     } else {
12020:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
12021:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12022:                         }
12023:                     }
12024:                 }
12025:             }
12026:             closedir($dirh);
12027:         }
12028:     } else {
12029:         my ($dirlistref,$listerror) =
12030:             &dirlist($toppath.$relpath);
12031:         my @dir_lines;
12032:         my $dirptr=16384;
12033:         if (ref($dirlistref) eq 'ARRAY') {
12034:             foreach my $dir_line (sort
12035:                               {
12036:                                   my ($afile)=split('&',$a,2);
12037:                                   my ($bfile)=split('&',$b,2);
12038:                                   return (lc($afile) cmp lc($bfile));
12039:                               } (@{$dirlistref})) {
12040:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12041:                     split(/\&/,$dir_line,16);
12042:                 $item =~ s/\s+$//;
12043:                 next if (($item =~ /^\.\.?$/) || ($obs));
12044:                 if ($dirptr&$testdir) {
12045:                     my $newpath;
12046:                     if ($relpath) {
12047:                         $newpath = "$relpath/$item";
12048:                     } else {
12049:                         $relpath = '/';
12050:                         $newpath = $item;
12051:                     }
12052:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12053:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12054:                 } elsif ($savefile) {
12055:                     if ($context eq 'priv') {
12056:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12057:                             $filehashref->{$relpath}{$item} = 1;
12058:                         }
12059:                     } else {
12060:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
12061:                             $filehashref->{$relpath}{$item} = 1;
12062:                         }
12063:                     }
12064:                 }
12065:             }
12066:         }
12067:     }
12068:     return;
12069: }
12070: 
12071: # -------------------------------------------------------- Value of a Condition
12072: 
12073: # gets the value of a specific preevaluated condition
12074: #    stored in the string  $env{user.state.<cid>}
12075: # or looks up a condition reference in the bighash and if if hasn't
12076: # already been evaluated recurses into docondval to get the value of
12077: # the condition, then memoizing it to 
12078: #   $env{user.state.<cid>.<condition>}
12079: sub directcondval {
12080:     my $number=shift;
12081:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12082: 	&Apache::lonuserstate::evalstate();
12083:     }
12084:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12085: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12086:     } elsif ($number =~ /^_/) {
12087: 	my $sub_condition;
12088: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12089: 		&GDBM_READER(),0640)) {
12090: 	    $sub_condition=$bighash{'conditions'.$number};
12091: 	    untie(%bighash);
12092: 	}
12093: 	my $value = &docondval($sub_condition);
12094: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12095: 	return $value;
12096:     }
12097:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12098:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12099:     } else {
12100:        return 2;
12101:     }
12102: }
12103: 
12104: # get the collection of conditions for this resource
12105: sub condval {
12106:     my $condidx=shift;
12107:     my $allpathcond='';
12108:     foreach my $cond (split(/\|/,$condidx)) {
12109: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12110: 	    $allpathcond.=
12111: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12112: 	}
12113:     }
12114:     $allpathcond=~s/\|$//;
12115:     return &docondval($allpathcond);
12116: }
12117: 
12118: #evaluates an expression of conditions
12119: sub docondval {
12120:     my ($allpathcond) = @_;
12121:     my $result=0;
12122:     if ($env{'request.course.id'}
12123: 	&& defined($allpathcond)) {
12124: 	my $operand='|';
12125: 	my @stack;
12126: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12127: 	    if ($chunk eq '(') {
12128: 		push @stack,($operand,$result);
12129: 	    } elsif ($chunk eq ')') {
12130: 		my $before=pop @stack;
12131: 		if (pop @stack eq '&') {
12132: 		    $result=$result>$before?$before:$result;
12133: 		} else {
12134: 		    $result=$result>$before?$result:$before;
12135: 		}
12136: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12137: 		$operand=$chunk;
12138: 	    } else {
12139: 		my $new=directcondval($chunk);
12140: 		if ($operand eq '&') {
12141: 		    $result=$result>$new?$new:$result;
12142: 		} else {
12143: 		    $result=$result>$new?$result:$new;
12144: 		}
12145: 	    }
12146: 	}
12147:     }
12148:     return $result;
12149: }
12150: 
12151: # ---------------------------------------------------- Devalidate courseresdata
12152: 
12153: sub devalidatecourseresdata {
12154:     my ($coursenum,$coursedomain)=@_;
12155:     my $hashid=$coursenum.':'.$coursedomain;
12156:     &devalidate_cache_new('courseres',$hashid);
12157: }
12158: 
12159: 
12160: # --------------------------------------------------- Course Resourcedata Query
12161: #
12162: #  Parameters:
12163: #      $coursenum    - Number of the course.
12164: #      $coursedomain - Domain at which the course was created.
12165: #  Returns:
12166: #     A hash of the course parameters along (I think) with timestamps
12167: #     and version info.
12168: 
12169: sub get_courseresdata {
12170:     my ($coursenum,$coursedomain)=@_;
12171:     my $coursehom=&homeserver($coursenum,$coursedomain);
12172:     my $hashid=$coursenum.':'.$coursedomain;
12173:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12174:     my %dumpreply;
12175:     unless (defined($cached)) {
12176: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12177: 	$result=\%dumpreply;
12178: 	my ($tmp) = keys(%dumpreply);
12179: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12180: 	    &do_cache_new('courseres',$hashid,$result,600);
12181: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12182: 	    return $tmp;
12183: 	} elsif ($tmp =~ /^(error)/) {
12184: 	    $result=undef;
12185: 	    &do_cache_new('courseres',$hashid,$result,600);
12186: 	}
12187:     }
12188:     return $result;
12189: }
12190: 
12191: sub devalidateuserresdata {
12192:     my ($uname,$udom)=@_;
12193:     my $hashid="$udom:$uname";
12194:     &devalidate_cache_new('userres',$hashid);
12195: }
12196: 
12197: sub get_userresdata {
12198:     my ($uname,$udom)=@_;
12199:     #most student don\'t have any data set, check if there is some data
12200:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12201: 
12202:     my $hashid="$udom:$uname";
12203:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12204:     if (!defined($cached)) {
12205: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12206: 	$result=\%resourcedata;
12207: 	&do_cache_new('userres',$hashid,$result,600);
12208:     }
12209:     my ($tmp)=keys(%$result);
12210:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12211: 	return $result;
12212:     }
12213:     #error 2 occurs when the .db doesn't exist
12214:     if ($tmp!~/error: 2 /) {
12215:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12216: 	    &logthis("<font color=\"blue\">WARNING:".
12217: 		     " Trying to get resource data for ".
12218: 		     $uname." at ".$udom.": ".
12219: 		     $tmp."</font>");
12220:         }
12221:     } elsif ($tmp=~/error: 2 /) {
12222: 	#&EXT_cache_set($udom,$uname);
12223: 	&do_cache_new('userres',$hashid,undef,600);
12224: 	undef($tmp); # not really an error so don't send it back
12225:     }
12226:     return $tmp;
12227: }
12228: #----------------------------------------------- resdata - return resource data
12229: #  Purpose:
12230: #    Return resource data for either users or for a course.
12231: #  Parameters:
12232: #     $name      - Course/user name.
12233: #     $domain    - Name of the domain the user/course is registered on.
12234: #     $type      - Type of thing $name is (must be 'course' or 'user')
12235: #     $mapp      - decluttered URL of enclosing map  
12236: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12237: #     $recurseup - Ref to array of map URLs, starting with map containing
12238: #                  $mapp up through hierarchy of nested maps to top level map.  
12239: #     $courseid  - CourseID (first part of param identifier).
12240: #     $modifier  - Middle part of param identifier.
12241: #     $what      - Last part of param identifier.
12242: #     @which     - Array of names of resources desired.
12243: #  Returns:
12244: #     The value of the first reasource in @which that is found in the
12245: #     resource hash.
12246: #  Exceptional Conditions:
12247: #     If the $type passed in is not valid (not the string 'course' or 
12248: #     'user', an undefined  reference is returned.
12249: #     If none of the resources are found, an undef is returned
12250: sub resdata {
12251:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12252:         $modifier,$what,@which)=@_;
12253:     my $result;
12254:     if ($type eq 'course') {
12255: 	$result=&get_courseresdata($name,$domain);
12256:     } elsif ($type eq 'user') {
12257: 	$result=&get_userresdata($name,$domain);
12258:     }
12259:     if (!ref($result)) { return $result; }    
12260:     foreach my $item (@which) {
12261:         if ($item->[1] eq 'course') {
12262:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12263:                 unless ($$recursed) {
12264:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12265:                     $$recursed = 1;
12266:                 }
12267:                 foreach my $item (@${recurseup}) {
12268:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12269:                     last if (defined($result->{$norecursechk}));
12270:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12271:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12272:                 }
12273:             }
12274:         }
12275:         if (defined($result->{$item->[0]})) {
12276: 	    return [$result->{$item->[0]},$item->[1]];
12277: 	}
12278:     }
12279:     return undef;
12280: }
12281: 
12282: sub get_domain_lti {
12283:     my ($cdom,$context) = @_;
12284:     my ($name,$cachename,%lti);
12285:     if ($context eq 'consumer') {
12286:         $name = 'ltitools';
12287:     } elsif ($context eq 'provider') {
12288:         $name = 'lti';
12289:     } elsif ($context eq 'linkprot') {
12290:         $name = 'ltisec';
12291:     } else {
12292:         return %lti;
12293:     }
12294: 
12295:     if ($context eq 'linkprot') {
12296:         $cachename = $context;
12297:     } else {
12298:         $cachename = $name;
12299:     }
12300:     
12301:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12302:     if (defined($cached)) {
12303:         if (ref($result) eq 'HASH') {
12304:             %lti = %{$result};
12305:         }
12306:     } else {
12307:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12308:         if (ref($domconfig{$name}) eq 'HASH') {
12309:             if ($context eq 'linkprot') {
12310:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12311:                     %lti = %{$domconfig{$name}{'linkprot'}};
12312:                 }
12313:             } else {
12314:                 %lti = %{$domconfig{$name}};
12315:             }
12316:             if (($context eq 'consumer') && (keys(%lti))) {
12317:                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12318:                 if (ref($encdomconfig{$name}) eq 'HASH') {
12319:                     foreach my $id (keys(%lti)) {
12320:                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12321:                             foreach my $item ('key','secret') {
12322:                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12323:                             }
12324:                         }
12325:                     }
12326:                 }
12327:             }
12328:         }
12329:         my $cachetime = 24*60*60;
12330:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12331:     }
12332:     return %lti;
12333: }
12334: 
12335: sub get_course_lti {
12336:     my ($cnum,$cdom) = @_;
12337:     my $hashid=$cdom.'_'.$cnum;
12338:     my %courselti;
12339:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
12340:     if (defined($cached)) {
12341:         if (ref($result) eq 'HASH') {
12342:             %courselti = %{$result};
12343:         }
12344:     } else {
12345:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12346:         my $cachetime = 24*60*60;
12347:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12348:     }
12349:     return %courselti;
12350: }
12351: 
12352: sub courselti_itemid {
12353:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12354:     my ($chome,$itemid);
12355:     $chome = &homeserver($cnum,$cdom);
12356:     return if ($chome eq 'no_host');
12357:     if (ref($params) eq 'HASH') {
12358:         my $items = &freeze_escape($params);
12359:         my $rep;
12360:         if (grep { $_ eq $chome } current_machine_ids()) {
12361:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12362:         } else {
12363:             my $escurl = &escape($url);
12364:             my $escmethod = &escape($method);
12365:             my $items = &freeze_escape($params);
12366:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12367:         }
12368:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12369:                 ($rep eq 'unknown_cmd')) {
12370:             $itemid = $rep;
12371:         }
12372:     }
12373:     return $itemid;
12374: }
12375: 
12376: sub domainlti_itemid {
12377:     my ($cdom,$url,$method,$params,$context) = @_;
12378:     my ($primary_id,$itemid);
12379:     $primary_id = &domain($cdom,'primary');
12380:     return if ($primary_id eq '');
12381:     if (ref($params) eq 'HASH') {
12382:         my $items = &freeze_escape($params);
12383:         my $rep;
12384:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12385:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12386:         } else {
12387:             my $cnum = '';
12388:             my $escurl = &escape($url);
12389:             my $escmethod = &escape($method);
12390:             my $items = &freeze_escape($params);
12391:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12392:         }
12393:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12394:                 ($rep eq 'unknown_cmd')) {
12395:             $itemid = $rep;
12396:         }
12397:     }
12398:     return $itemid;
12399: }
12400: 
12401: sub get_numsuppfiles {
12402:     my ($cnum,$cdom,$ignorecache)=@_;
12403:     my $hashid=$cnum.':'.$cdom;
12404:     my ($suppcount,$cached);
12405:     unless ($ignorecache) {
12406:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12407:     }
12408:     unless (defined($cached)) {
12409:         my $chome=&homeserver($cnum,$cdom);
12410:         unless ($chome eq 'no_host') {
12411:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12412:             my $suppmap = 'supplemental.sequence';
12413:             ($suppcount,$supptools,$errors) =
12414:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12415:                                                          $supptools,$errors);
12416:         }
12417:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12418:     }
12419:     return $suppcount;
12420: }
12421: 
12422: #
12423: # EXT resource caching routines
12424: #
12425: 
12426: {
12427: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12428: #
12429: # The course for which we cache
12430: my $cachedmapkey='';
12431: # The cached recursive maps for this course
12432: my %cachedmaps=();
12433: # When this was last done
12434: my $cachedmaptime='';
12435: 
12436: sub clear_EXT_cache_status {
12437:     &delenv('cache.EXT.');
12438: }
12439: 
12440: sub EXT_cache_status {
12441:     my ($target_domain,$target_user) = @_;
12442:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12443:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12444:         # We know already the user has no data
12445:         return 1;
12446:     } else {
12447:         return 0;
12448:     }
12449: }
12450: 
12451: sub EXT_cache_set {
12452:     my ($target_domain,$target_user) = @_;
12453:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12454:     #&appenv({$cachename => time});
12455: }
12456: 
12457: # --------------------------------------------------------- Value of a Variable
12458: sub EXT {
12459: 
12460:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12461:     unless ($varname) { return ''; }
12462:     #get real user name/domain, courseid and symb
12463:     my $courseid;
12464:     my $publicuser;
12465:     if ($symbparm) {
12466: 	$symbparm=&get_symb_from_alias($symbparm);
12467:     }
12468:     if (!($uname && $udom)) {
12469:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12470:       if (!$symbparm) {	$symbparm=$cursymb; }
12471:     } else {
12472: 	$courseid=$env{'request.course.id'};
12473:     }
12474:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12475:     my $rest;
12476:     if (defined($therest[0])) {
12477:        $rest=join('.',@therest);
12478:     } else {
12479:        $rest='';
12480:     }
12481: 
12482:     my $qualifierrest=$qualifier;
12483:     if ($rest) { $qualifierrest.='.'.$rest; }
12484:     my $spacequalifierrest=$space;
12485:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12486:     if ($realm eq 'user') {
12487: # --------------------------------------------------------------- user.resource
12488: 	if ($space eq 'resource') {
12489: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12490: 		  || defined($Apache::lonhomework::parsing_a_task))
12491: 		 &&
12492: 		 ($symbparm eq &symbread()) ) {
12493: 		# if we are in the middle of processing the resource the
12494: 		# get the value we are planning on committing
12495:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12496:                     return $Apache::lonhomework::results{$qualifierrest};
12497:                 } else {
12498:                     return $Apache::lonhomework::history{$qualifierrest};
12499:                 }
12500: 	    } else {
12501: 		my %restored;
12502: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12503: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12504: 		} else {
12505: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12506: 		}
12507: 		return $restored{$qualifierrest};
12508: 	    }
12509: # ----------------------------------------------------------------- user.access
12510:         } elsif ($space eq 'access') {
12511: 	    # FIXME - not supporting calls for a specific user
12512:             return &allowed($qualifier,$rest);
12513: # ------------------------------------------ user.preferences, user.environment
12514:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12515: 	    if (($uname eq $env{'user.name'}) &&
12516: 		($udom eq $env{'user.domain'})) {
12517: 		return $env{join('.',('environment',$qualifierrest))};
12518: 	    } else {
12519: 		my %returnhash;
12520: 		if (!$publicuser) {
12521: 		    %returnhash=&userenvironment($udom,$uname,
12522: 						 $qualifierrest);
12523: 		}
12524: 		return $returnhash{$qualifierrest};
12525: 	    }
12526: # ----------------------------------------------------------------- user.course
12527:         } elsif ($space eq 'course') {
12528: 	    # FIXME - not supporting calls for a specific user
12529:             return $env{join('.',('request.course',$qualifier))};
12530: # ------------------------------------------------------------------- user.role
12531:         } elsif ($space eq 'role') {
12532: 	    # FIXME - not supporting calls for a specific user
12533:             my ($role,$where)=split(/\./,$env{'request.role'});
12534:             if ($qualifier eq 'value') {
12535: 		return $role;
12536:             } elsif ($qualifier eq 'extent') {
12537:                 return $where;
12538:             }
12539: # ----------------------------------------------------------------- user.domain
12540:         } elsif ($space eq 'domain') {
12541:             return $udom;
12542: # ------------------------------------------------------------------- user.name
12543:         } elsif ($space eq 'name') {
12544:             return $uname;
12545: # ---------------------------------------------------- Any other user namespace
12546:         } else {
12547: 	    my %reply;
12548: 	    if (!$publicuser) {
12549: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12550: 	    }
12551: 	    return $reply{$qualifierrest};
12552:         }
12553:     } elsif ($realm eq 'query') {
12554: # ---------------------------------------------- pull stuff out of query string
12555:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12556: 						[$spacequalifierrest]);
12557: 	return $env{'form.'.$spacequalifierrest}; 
12558:    } elsif ($realm eq 'request') {
12559: # ------------------------------------------------------------- request.browser
12560:         if ($space eq 'browser') {
12561:             return $env{'browser.'.$qualifier};
12562: # ------------------------------------------------------------ request.filename
12563:         } else {
12564:             return $env{'request.'.$spacequalifierrest};
12565:         }
12566:     } elsif ($realm eq 'course') {
12567: # ---------------------------------------------------------- course.description
12568:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12569:     } elsif ($realm eq 'resource') {
12570: 
12571: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12572: 	    if (!$symbparm) { $symbparm=&symbread(); }
12573: 	}
12574: 
12575:         if ($qualifier eq '') {
12576: 	    if ($space eq 'title') {
12577: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12578: 	        return &gettitle($symbparm);
12579: 	    }
12580: 	
12581: 	    if ($space eq 'map') {
12582: 	        my ($map) = &decode_symb($symbparm);
12583: 	        return &symbread($map);
12584: 	    }
12585:             if ($space eq 'maptitle') {
12586:                 my ($map) = &decode_symb($symbparm);
12587:                 return &gettitle($map);
12588:             }
12589: 	    if ($space eq 'filename') {
12590: 	        if ($symbparm) {
12591: 		    return &clutter((&decode_symb($symbparm))[2]);
12592: 	        }
12593: 	        return &hreflocation('',$env{'request.filename'});
12594: 	    }
12595: 
12596:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12597:                 if ($space eq 'visibleparts') {
12598:                     my $navmap = Apache::lonnavmaps::navmap->new();
12599:                     my $item;
12600:                     if (ref($navmap)) {
12601:                         my $res = $navmap->getBySymb($symbparm);
12602:                         my $parts = $res->parts();
12603:                         if (ref($parts) eq 'ARRAY') {
12604:                             $item = join(',',@{$parts});
12605:                         }
12606:                         undef($navmap);
12607:                     }
12608:                     return $item;
12609:                 }
12610:             }
12611:         }
12612: 
12613: 	my ($section, $group, @groups, @recurseup, $recursed);
12614:         if (ref($recurseupref) eq 'ARRAY') {
12615:             @recurseup = @{$recurseupref};
12616:             $recursed = 1;
12617:         }
12618: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12619:         if (($courseid eq '') && ($cid)) {
12620:             $courseid = $cid;
12621:         }
12622: 	if (($symbparm && $courseid) && 
12623: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12624: 
12625: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12626: 
12627: # ----------------------------------------------------- Cascading lookup scheme
12628: 	    my $symbp=$symbparm;
12629: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12630: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12631:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12632: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12633: 	    if (($env{'user.name'} eq $uname) &&
12634: 		($env{'user.domain'} eq $udom)) {
12635: 		$section=$env{'request.course.sec'};
12636:                 @groups = split(/:/,$env{'request.course.groups'});  
12637:                 @groups=&sort_course_groups($courseid,@groups); 
12638: 	    } else {
12639: 		if (! defined($usection)) {
12640: 		    $section=&getsection($udom,$uname,$courseid);
12641: 		} else {
12642: 		    $section = $usection;
12643: 		}
12644:                 @groups = &get_users_groups($udom,$uname,$courseid);
12645: 	    }
12646: 
12647: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12648: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12649:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12650: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12651: 
12652: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12653: 	    my $courselevelr=$courseid.'.'.$symbparm;
12654:             $courseleveli=$courseid.'.'.$recurseparm;
12655: 	    $courselevelm=$courseid.'.'.$mapparm;
12656: 
12657: # ----------------------------------------------------------- first, check user
12658: 
12659: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12660:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12661: 				       ([$courselevelr,'resource'],
12662: 					[$courselevelm,'map'     ],
12663:                                         [$courseleveli,'map'     ],
12664: 					[$courselevel, 'course'  ]));
12665: 	    if (defined($userreply)) { return &get_reply($userreply); }
12666: 
12667: # ------------------------------------------------ second, check some of course
12668:             my $coursereply;
12669:             if (@groups > 0) {
12670:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12671:                                        $recurseparm,$mapparm,$spacequalifierrest,
12672:                                        $mapp,\$recursed,\@recurseup);
12673:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12674:             }
12675: 
12676: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12677: 				  $env{'course.'.$courseid.'.domain'},
12678: 				  'course',$mapp,\$recursed,\@recurseup,
12679:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12680: 				  ([$seclevelr,   'resource'],
12681: 				   [$seclevelm,   'map'     ],
12682:                                    [$secleveli,   'map'     ],
12683: 				   [$seclevel,    'course'  ],
12684: 				   [$courselevelr,'resource']));
12685: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12686: 
12687: # ------------------------------------------------------ third, check map parms
12688: 	    my %parmhash=();
12689: 	    my $thisparm='';
12690: 	    if (tie(%parmhash,'GDBM_File',
12691: 		    $env{'request.course.fn'}.'_parms.db',
12692: 		    &GDBM_READER(),0640)) {
12693: 		$thisparm=$parmhash{$symbparm};
12694: 		untie(%parmhash);
12695: 	    }
12696: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12697: 	}
12698: # ------------------------------------------ fourth, look in resource metadata
12699:  
12700:         my $what = $spacequalifierrest;
12701: 	$what=~s/\./\_/;
12702: 	my $filename;
12703: 	if (!$symbparm) { $symbparm=&symbread(); }
12704: 	if ($symbparm) {
12705: 	    $filename=(&decode_symb($symbparm))[2];
12706: 	} else {
12707: 	    $filename=$env{'request.filename'};
12708: 	}
12709:         my $toolsymb;
12710:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12711:             $toolsymb = $symbparm;
12712:         }
12713: 	my $metadata=&metadata($filename,$what,$toolsymb);
12714: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12715: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12716: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12717: 
12718: # ----------------------------------------------- fifth, look in rest of course
12719: 	if ($symbparm && defined($courseid) && 
12720: 	    $courseid eq $env{'request.course.id'}) {
12721: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12722: 				     $env{'course.'.$courseid.'.domain'},
12723: 				     'course',$mapp,\$recursed,\@recurseup,
12724:                                      $courseid,'.',$spacequalifierrest,
12725: 				     ([$courselevelm,'map'   ],
12726:                                       [$courseleveli,'map'   ],
12727: 				      [$courselevel, 'course']));
12728: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12729: 	}
12730: # ------------------------------------------------------------------ Cascade up
12731: 	unless ($space eq '0') {
12732: 	    my @parts=split(/_/,$space);
12733: 	    my $id=pop(@parts);
12734: 	    my $part=join('_',@parts);
12735: 	    if ($part eq '') { $part='0'; }
12736: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12737: 				 $symbparm,$udom,$uname,$section,1);
12738: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12739: 	}
12740: 	if ($recurse) { return undef; }
12741: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12742: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12743: # ---------------------------------------------------- Any other user namespace
12744:     } elsif ($realm eq 'environment') {
12745: # ----------------------------------------------------------------- environment
12746: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12747: 	    return $env{'environment.'.$spacequalifierrest};
12748: 	} else {
12749: 	    if ($uname eq 'anonymous' && $udom eq '') {
12750: 		return '';
12751: 	    }
12752: 	    my %returnhash=&userenvironment($udom,$uname,
12753: 					    $spacequalifierrest);
12754: 	    return $returnhash{$spacequalifierrest};
12755: 	}
12756:     } elsif ($realm eq 'system') {
12757: # ----------------------------------------------------------------- system.time
12758: 	if ($space eq 'time') {
12759: 	    return time;
12760:         }
12761:     } elsif ($realm eq 'server') {
12762: # ----------------------------------------------------------------- system.time
12763: 	if ($space eq 'name') {
12764: 	    return $ENV{'SERVER_NAME'};
12765:         }
12766:     } elsif ($realm eq 'client') {
12767:         if ($space eq 'remote_addr') {
12768:             return &get_requestor_ip();
12769:         }
12770:     }
12771:     return '';
12772: }
12773: 
12774: sub get_reply {
12775:     my ($reply_value) = @_;
12776:     if (ref($reply_value) eq 'ARRAY') {
12777:         if (wantarray) {
12778: 	    return @$reply_value;
12779:         }
12780:         return $reply_value->[0];
12781:     } else {
12782:         return $reply_value;
12783:     }
12784: }
12785: 
12786: sub check_group_parms {
12787:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12788:         $recursed,$recurseupref) = @_;
12789:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12790:                   [$what,'course']);
12791:     my $coursereply;
12792:     foreach my $group (@{$groups}) {
12793:         my @groupitems = ();
12794:         foreach my $level (@levels) {
12795:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12796:              push(@groupitems,[$item,$level->[1]]);
12797:         }
12798:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12799:                                    $env{'course.'.$courseid.'.domain'},
12800:                                    'course',$mapp,$recursed,$recurseupref,
12801:                                    $courseid,'.['.$group.'].',$what,
12802:                                    @groupitems);
12803:         last if (defined($coursereply));
12804:     }
12805:     return $coursereply;
12806: }
12807: 
12808: sub get_map_hierarchy {
12809:     my ($mapname,$courseid) = @_;
12810:     my @recurseup = ();
12811:     if ($mapname) {
12812:         if (($cachedmapkey eq $courseid) &&
12813:             (abs($cachedmaptime-time)<5)) {
12814:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12815:                 return @{$cachedmaps{$mapname}};
12816:             }
12817:         }
12818:         my $navmap = Apache::lonnavmaps::navmap->new();
12819:         if (ref($navmap)) {
12820:             @recurseup = $navmap->recurseup_maps($mapname);
12821:             undef($navmap);
12822:             $cachedmaps{$mapname} = \@recurseup;
12823:             $cachedmaptime=time;
12824:             $cachedmapkey=$courseid;
12825:         }
12826:     }
12827:     return @recurseup;
12828: }
12829: 
12830: }
12831: 
12832: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12833:     my ($courseid,@groups) = @_;
12834:     @groups = sort(@groups);
12835:     return @groups;
12836: }
12837: 
12838: sub packages_tab_default {
12839:     my ($uri,$varname,$toolsymb)=@_;
12840:     my (undef,$part,$name)=split(/\./,$varname);
12841: 
12842:     my (@extension,@specifics,$do_default);
12843:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12844: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12845: 	if ($pack_type eq 'default') {
12846: 	    $do_default=1;
12847: 	} elsif ($pack_type eq 'extension') {
12848: 	    push(@extension,[$package,$pack_type,$pack_part]);
12849: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12850: 	    # only look at packages defaults for packages that this id is
12851: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12852: 	}
12853:     }
12854:     # first look for a package that matches the requested part id
12855:     foreach my $package (@specifics) {
12856: 	my (undef,$pack_type,$pack_part)=@{$package};
12857: 	next if ($pack_part ne $part);
12858: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12859: 	    return $packagetab{"$pack_type&$name&default"};
12860: 	}
12861:     }
12862:     # look for any possible matching non extension_ package
12863:     foreach my $package (@specifics) {
12864: 	my (undef,$pack_type,$pack_part)=@{$package};
12865: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12866: 	    return $packagetab{"$pack_type&$name&default"};
12867: 	}
12868: 	if ($pack_type eq 'part') { $pack_part='0'; }
12869: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12870: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12871: 	}
12872:     }
12873:     # look for any posible extension_ match
12874:     foreach my $package (@extension) {
12875: 	my ($package,$pack_type)=@{$package};
12876: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12877: 	    return $packagetab{"$pack_type&$name&default"};
12878: 	}
12879: 	if (defined($packagetab{$package."&$name&default"})) {
12880: 	    return $packagetab{$package."&$name&default"};
12881: 	}
12882:     }
12883:     # look for a global default setting
12884:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12885: 	return $packagetab{"default&$name&default"};
12886:     }
12887:     return undef;
12888: }
12889: 
12890: sub add_prefix_and_part {
12891:     my ($prefix,$part)=@_;
12892:     my $keyroot;
12893:     if (defined($prefix) && $prefix !~ /^__/) {
12894: 	# prefix that has a part already
12895: 	$keyroot=$prefix;
12896:     } elsif (defined($prefix)) {
12897: 	# prefix that is missing a part
12898: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12899:     } else {
12900: 	# no prefix at all
12901: 	if (defined($part)) { $keyroot='_'.$part; }
12902:     }
12903:     return $keyroot;
12904: }
12905: 
12906: # ---------------------------------------------------------------- Get metadata
12907: 
12908: my %metaentry;
12909: my %importedpartids;
12910: my %importedrespids;
12911: sub metadata {
12912:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12913:     $uri=&declutter($uri);
12914:     # if it is a non metadata possible uri return quickly
12915:     if (($uri eq '') || 
12916: 	(($uri =~ m|^/*adm/|) && 
12917: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12918:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12919: 	return undef;
12920:     }
12921:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12922: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12923: 	return undef;
12924:     }
12925:     my $filename=$uri;
12926:     $uri=~s/\.meta$//;
12927: #
12928: # Is the metadata already cached?
12929: # Look at timestamp of caching
12930: # Everything is cached by the main uri, libraries are never directly cached
12931: #
12932:     if (!defined($liburi)) {
12933: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12934: 	if (defined($cached)) { return $result->{':'.$what}; }
12935:     }
12936: 
12937: #
12938: # If the uri is for an external tool the file from
12939: # which metadata should be retrieved depends on whether
12940: # the tool had been configured to be gradable (set in the Course
12941: # Editor or Resource Editor).
12942: #
12943: # If a valid symb has been included as the third arg in the call
12944: # to &metadata() that can be used to retrieve the value of
12945: # parameter_0_gradable set for the resource, and included in the
12946: # uploaded map containing the tool. The value is retrieved via
12947: # &EXT(), if a valid symb is available.  Otherwise the value of
12948: # gradable in the exttool_$marker.db file for the tool instance
12949: # is retrieved via &get().
12950: #
12951: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12952: # hiddenresource and encrypturl (during course initialization)
12953: # the map-level parameter for resource.0.gradable included in the 
12954: # uploaded map containing the tool will not yet have been stored
12955: # in the user_course_parms.db file for the user's session, so in 
12956: # this case fall back to retrieving gradable status from the
12957: # exttool_$marker.db file.
12958: #
12959: # In order to avoid an infinite loop, &metadata() will return
12960: # before a call to &EXT(), if the uri is for an external tool
12961: # and the $what for which metadata is being requested is
12962: # parameter_0_gradable or 0_gradable.
12963: #
12964: 
12965:     if ($uri =~ /ext\.tool$/) {
12966:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12967:             return;
12968:         } else {
12969:             my ($checked,$use_passback);
12970:             if ($toolsymb ne '') {
12971:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12972:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12973:                     $checked = 1;
12974:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12975:                         $use_passback = 1;
12976:                     }
12977:                 }
12978:             }
12979:             unless ($checked) {
12980:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12981:                 $marker=~s/\D//g;
12982:                 if ($marker) {
12983:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12984:                     $use_passback = $toolsettings{'gradable'};
12985:                 }
12986:             }
12987:             if ($use_passback) {
12988:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12989:             } else {
12990:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12991:             }
12992:         }
12993:     }
12994: 
12995:     {
12996: # Imported parts would go here
12997:         my @origfiletagids=();
12998:         my $importedparts=0;
12999: 
13000: # Imported responseids would go here
13001:         my $importedresponses=0;
13002: #
13003: # Is this a recursive call for a library?
13004: #
13005: #	if (! exists($metacache{$uri})) {
13006: #	    $metacache{$uri}={};
13007: #	}
13008: 	my $cachetime = 60*60;
13009:         if ($liburi) {
13010: 	    $liburi=&declutter($liburi);
13011:             $filename=$liburi;
13012:         } else {
13013: 	    &devalidate_cache_new('meta',$uri);
13014: 	    undef(%metaentry);
13015: 	}
13016:         my %metathesekeys=();
13017:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13018: 	my $metastring;
13019: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13020: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13021: 	    $metastring = 
13022: 		&Apache::lonnet::ssi_body($which,
13023: 					  ('grade_target' => 'meta'));
13024: 	    $cachetime = 1; # only want this cached in the child not long term
13025: 	} elsif (($uri !~ m -^(editupload)/-) && 
13026:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13027: 	    my $file=&filelocation('',&clutter($filename));
13028: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13029: 	    $metastring=&getfile($file);
13030: 	}
13031:         my $parser=HTML::LCParser->new(\$metastring);
13032:         my $token;
13033:         undef %metathesekeys;
13034:         while ($token=$parser->get_token) {
13035: 	    if ($token->[0] eq 'S') {
13036: 		if (defined($token->[2]->{'package'})) {
13037: #
13038: # This is a package - get package info
13039: #
13040: 		    my $package=$token->[2]->{'package'};
13041: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13042: 		    if (defined($token->[2]->{'id'})) { 
13043: 			$keyroot.='_'.$token->[2]->{'id'}; 
13044: 		    }
13045: 		    if ($metaentry{':packages'}) {
13046: 			$metaentry{':packages'}.=','.$package.$keyroot;
13047: 		    } else {
13048: 			$metaentry{':packages'}=$package.$keyroot;
13049: 		    }
13050: 		    foreach my $pack_entry (keys(%packagetab)) {
13051: 			my $part=$keyroot;
13052: 			$part=~s/^\_//;
13053: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13054: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13055: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13056: 			    # ignore package.tab specified default values
13057:                             # here &package_tab_default() will fetch those
13058: 			    if ($subp eq 'default') { next; }
13059: 			    my $value=$packagetab{$pack_entry};
13060: 			    my $unikey;
13061: 			    if ($pack =~ /_0$/) {
13062: 				$unikey='parameter_0_'.$name;
13063: 				$part=0;
13064: 			    } else {
13065: 				$unikey='parameter'.$keyroot.'_'.$name;
13066: 			    }
13067: 			    if ($subp eq 'display') {
13068: 				$value.=' [Part: '.$part.']';
13069: 			    }
13070: 			    $metaentry{':'.$unikey.'.part'}=$part;
13071: 			    $metathesekeys{$unikey}=1;
13072: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13073: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13074: 			    }
13075: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13076: 				$metaentry{':'.$unikey}=
13077: 				    $metaentry{':'.$unikey.'.default'};
13078: 			    }
13079: 			}
13080: 		    }
13081: 		} else {
13082: #
13083: # This is not a package - some other kind of start tag
13084: #
13085: 		    my $entry=$token->[1];
13086: 		    my $unikey='';
13087: 
13088: 		    if ($entry eq 'import') {
13089: #
13090: # Importing a library here
13091: #
13092:                         my $location=$parser->get_text('/import');
13093:                         my $dir=$filename;
13094:                         $dir=~s|[^/]*$||;
13095:                         $location=&filelocation($dir,$location);
13096: 
13097:                         my $importid=$token->[2]->{'id'};
13098:                         my $importmode=$token->[2]->{'importmode'};
13099: #
13100: # Check metadata for imported file to
13101: # see if it contained response items
13102: #
13103:                         my ($origfile,@libfilekeys);
13104:                         my %currmetaentry = %metaentry;
13105:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13106:                                                            $depthcount+1));
13107:                         if (grep(/^responseorder$/,@libfilekeys)) {
13108:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13109:                                                              undef,$depthcount+1);
13110:                             if ($libresponseorder ne '') {
13111:                                 if ($#origfiletagids<0) {
13112:                                     undef(%importedrespids);
13113:                                     undef(%importedpartids);
13114:                                 }
13115:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13116:                                 if (@respids) {
13117:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13118:                                 }
13119:                                 if ($importedrespids{$importid} ne '') {
13120:                                     $importedresponses = 1;
13121: # We need to get the original file and the imported file to get the response order correct
13122: # Load and inspect original file
13123:                                     if ($#origfiletagids<0) {
13124:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13125:                                         $origfile=&getfile($origfilelocation);
13126:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13127:                                     }
13128:                                 }
13129:                             }
13130:                         }
13131: # Do not overwrite contents of %metaentry hash for resource itself with 
13132: # hash populated for imported library file
13133:                         %metaentry = %currmetaentry;
13134:                         undef(%currmetaentry);
13135:                         if ($importmode eq 'part') {
13136: # Import as part(s)
13137:                            $importedparts=1;
13138: # We need to get the original file and the imported file to get the part order correct
13139: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13140: # Load and inspect original file if we didn't do that already
13141:                            if ($#origfiletagids<0) {
13142:                                undef(%importedrespids);
13143:                                undef(%importedpartids);
13144:                                if ($origfile eq '') {
13145:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13146:                                    $origfile=&getfile($origfilelocation);
13147:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13148:                                }
13149:                            }
13150:                            my @impfilepartids;
13151: # If <partorder> tag is included in metadata for the imported file
13152: # get the parts in the imported file from that.
13153:                            if (grep(/^partorder$/,@libfilekeys)) {
13154:                                %currmetaentry = %metaentry;
13155:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13156:                                                             $depthcount+1);
13157:                                %metaentry = %currmetaentry;
13158:                                undef(%currmetaentry);
13159:                                if ($libpartorder ne '') {
13160:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13161:                                }
13162:                            } else {
13163: # If no <partorder> tag available, load and inspect imported file
13164:                                my $impfile=&getfile($location);
13165:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13166:                            }
13167:                            if ($#impfilepartids>=0) {
13168: # This problem had parts
13169:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13170:                            } else {
13171: # Importing by turning a single problem into a problem part
13172: # It gets the import-tags ID as part-ID
13173:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13174:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13175:                            }
13176:                         } else {
13177: # Import as problem or as normal import
13178:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13179:                             unless ($importmode eq 'problem') {
13180: # Normal import
13181:                                 if (defined($token->[2]->{'id'})) {
13182:                                     $unikey.='_'.$token->[2]->{'id'};
13183:                                 }
13184:                             }
13185: # Check metadata for imported file to
13186: # see if it contained parts
13187:                             if (grep(/^partorder$/,@libfilekeys)) {
13188:                                 %currmetaentry = %metaentry;
13189:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13190:                                                              $depthcount+1);
13191:                                 %metaentry = %currmetaentry;
13192:                                 undef(%currmetaentry);
13193:                                 if ($libpartorder ne '') {
13194:                                     $importedparts = 1;
13195:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13196:                                 }
13197:                             }
13198:                         }
13199: 			if ($depthcount<20) {
13200: 			    my $metadata = 
13201: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13202: 					  $depthcount+1);
13203: 			    foreach my $meta (split(',',$metadata)) {
13204: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13205: 				$metathesekeys{$meta}=1;
13206: 			    }
13207:                         }
13208: 		    } else {
13209: #
13210: # Not importing, some other kind of non-package, non-library start tag
13211: # 
13212:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13213:                         if (defined($token->[2]->{'id'})) {
13214:                             $unikey.='_'.$token->[2]->{'id'};
13215:                         }
13216: 			if (defined($token->[2]->{'name'})) { 
13217: 			    $unikey.='_'.$token->[2]->{'name'}; 
13218: 			}
13219: 			$metathesekeys{$unikey}=1;
13220: 			foreach my $param (@{$token->[3]}) {
13221: 			    $metaentry{':'.$unikey.'.'.$param} =
13222: 				$token->[2]->{$param};
13223: 			}
13224: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13225: 			my $default=$metaentry{':'.$unikey.'.default'};
13226: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13227: 		 # only ws inside the tag, and not in default, so use default
13228: 		 # as value
13229: 			    $metaentry{':'.$unikey}=$default;
13230: 			} elsif ( $internaltext =~ /\S/ ) {
13231: 		  # something interesting inside the tag
13232: 			    $metaentry{':'.$unikey}=$internaltext;
13233: 			} else {
13234: 		  # no interesting values, don't set a default
13235: 			}
13236: # end of not-a-package not-a-library import
13237: 		    }
13238: # end of not-a-package start tag
13239: 		}
13240: # the next is the end of "start tag"
13241: 	    }
13242: 	}
13243: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13244: 	$extension = lc($extension);
13245: 	if ($extension eq 'htm') { $extension='html'; }
13246: 
13247: 	foreach my $key (keys(%packagetab)) {
13248: 	    #no specific packages #how's our extension
13249: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13250: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13251: 					 \%metathesekeys);
13252: 	}
13253: 
13254: 	if (!exists($metaentry{':packages'})
13255: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13256: 	    foreach my $key (keys(%packagetab)) {
13257: 		#no specific packages well let's get default then
13258: 		if ($key!~/^default&/) { next; }
13259: 		&metadata_create_package_def($uri,$key,'default',
13260: 					     \%metathesekeys);
13261: 	    }
13262: 	}
13263: # are there custom rights to evaluate
13264: 	if ($metaentry{':copyright'} eq 'custom') {
13265: 
13266:     #
13267:     # Importing a rights file here
13268:     #
13269: 	    unless ($depthcount) {
13270: 		my $location=$metaentry{':customdistributionfile'};
13271: 		my $dir=$filename;
13272: 		$dir=~s|[^/]*$||;
13273: 		$location=&filelocation($dir,$location);
13274: 		my $rights_metadata =
13275: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13276: 			      $depthcount+1);
13277: 		foreach my $rights (split(',',$rights_metadata)) {
13278: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13279: 		    $metathesekeys{$rights}=1;
13280: 		}
13281: 	    }
13282: 	}
13283: 	# uniqifiy package listing
13284: 	my %seen;
13285: 	my @uniq_packages =
13286: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13287: 	$metaentry{':packages'} = join(',',@uniq_packages);
13288: 
13289:         if (($importedresponses) || ($importedparts)) {
13290:             if ($importedparts) {
13291: # We had imported parts and need to rebuild partorder
13292:                 $metaentry{':partorder'}='';
13293:                 $metathesekeys{'partorder'}=1;
13294:             }
13295:             if ($importedresponses) {
13296: # We had imported responses and need to rebuil responseorder
13297:                 $metaentry{':responseorder'}='';
13298:                 $metathesekeys{'responseorder'}=1;
13299:             }
13300:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13301:                 my $origid = $origfiletagids[$index+1];
13302:                 if ($origfiletagids[$index] eq 'part') {
13303: # Original part, part of the problem
13304:                     if ($importedparts) {
13305:                         $metaentry{':partorder'}.=','.$origid;
13306:                     }
13307:                 } elsif ($origfiletagids[$index] eq 'import') {
13308:                     if ($importedparts) {
13309: # We have imported parts at this position
13310:                         if ($importedpartids{$origid} ne '') {
13311:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13312:                         }
13313:                     }
13314:                     if ($importedresponses) {
13315: # We have imported responses at this position
13316:                         if ($importedrespids{$origid} ne '') {
13317:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13318:                         }
13319:                     }
13320:                 } else {
13321: # Original response item, part of the problem
13322:                     if ($importedresponses) {
13323:                         $metaentry{':responseorder'}.=','.$origid;
13324:                     }
13325:                 }
13326:             }
13327:             if ($importedparts) {
13328:                 $metaentry{':partorder'}=~s/^\,//;
13329:             }
13330:             if ($importedresponses) {
13331:                 $metaentry{':responseorder'}=~s/^\,//;
13332:             }
13333:         }
13334: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13335: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13336: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13337:         unless ($liburi) {
13338: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13339:         }
13340: # this is the end of "was not already recently cached
13341:     }
13342:     return $metaentry{':'.$what};
13343: }
13344: 
13345: sub metadata_create_package_def {
13346:     my ($uri,$key,$package,$metathesekeys)=@_;
13347:     my ($pack,$name,$subp)=split(/\&/,$key);
13348:     if ($subp eq 'default') { next; }
13349:     
13350:     if (defined($metaentry{':packages'})) {
13351: 	$metaentry{':packages'}.=','.$package;
13352:     } else {
13353: 	$metaentry{':packages'}=$package;
13354:     }
13355:     my $value=$packagetab{$key};
13356:     my $unikey;
13357:     $unikey='parameter_0_'.$name;
13358:     $metaentry{':'.$unikey.'.part'}=0;
13359:     $$metathesekeys{$unikey}=1;
13360:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13361: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13362:     }
13363:     if (defined($metaentry{':'.$unikey.'.default'})) {
13364: 	$metaentry{':'.$unikey}=
13365: 	    $metaentry{':'.$unikey.'.default'};
13366:     }
13367: }
13368: 
13369: sub metadata_generate_part0 {
13370:     my ($metadata,$metacache,$uri) = @_;
13371:     my %allnames;
13372:     foreach my $metakey (keys(%$metadata)) {
13373: 	if ($metakey=~/^parameter\_(.*)/) {
13374: 	  my $part=$$metacache{':'.$metakey.'.part'};
13375: 	  my $name=$$metacache{':'.$metakey.'.name'};
13376: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13377: 	    $allnames{$name}=$part;
13378: 	  }
13379: 	}
13380:     }
13381:     foreach my $name (keys(%allnames)) {
13382:       $$metadata{"parameter_0_$name"}=1;
13383:       my $key=":parameter_0_$name";
13384:       $$metacache{"$key.part"}='0';
13385:       $$metacache{"$key.name"}=$name;
13386:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13387: 					   $allnames{$name}.'_'.$name.
13388: 					   '.type'};
13389:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13390: 			     '.display'};
13391:       my $expr='[Part: '.$allnames{$name}.']';
13392:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13393:       $$metacache{"$key.display"}=$olddis;
13394:     }
13395: }
13396: 
13397: # ------------------------------------------------------ Devalidate title cache
13398: 
13399: sub devalidate_title_cache {
13400:     my ($url)=@_;
13401:     if (!$env{'request.course.id'}) { return; }
13402:     my $symb=&symbread($url);
13403:     if (!$symb) { return; }
13404:     my $key=$env{'request.course.id'}."\0".$symb;
13405:     &devalidate_cache_new('title',$key);
13406: }
13407: 
13408: # ------------------------------------------------- Get the title of a course
13409: 
13410: sub current_course_title {
13411:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13412: }
13413: # ------------------------------------------------- Get the title of a resource
13414: 
13415: sub gettitle {
13416:     my $urlsymb=shift;
13417:     my $symb=&symbread($urlsymb);
13418:     if ($symb) {
13419: 	my $key=$env{'request.course.id'}."\0".$symb;
13420: 	my ($result,$cached)=&is_cached_new('title',$key);
13421: 	if (defined($cached)) { 
13422: 	    return $result;
13423: 	}
13424: 	my ($map,$resid,$url)=&decode_symb($symb);
13425: 	my $title='';
13426: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13427: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13428: 	} else {
13429: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13430: 		    &GDBM_READER(),0640)) {
13431: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13432: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13433: 		untie(%bighash);
13434: 	    }
13435: 	}
13436: 	$title=~s/\&colon\;/\:/gs;
13437: 	if ($title) {
13438: # Remember both $symb and $title for dynamic metadata
13439:             $accesshash{$symb.'___crstitle'}=$title;
13440:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13441: # Cache this title and then return it
13442: 	    return &do_cache_new('title',$key,$title,600);
13443: 	}
13444: 	$urlsymb=$url;
13445:     }
13446:     my $title=&metadata($urlsymb,'title');
13447:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13448:     return $title;
13449: }
13450: 
13451: sub get_slot {
13452:     my ($which,$cnum,$cdom)=@_;
13453:     if (!$cnum || !$cdom) {
13454: 	(undef,my $courseid)=&whichuser();
13455: 	$cdom=$env{'course.'.$courseid.'.domain'};
13456: 	$cnum=$env{'course.'.$courseid.'.num'};
13457:     }
13458:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13459:     my %slotinfo;
13460:     if (exists($remembered{$key})) {
13461: 	$slotinfo{$which} = $remembered{$key};
13462:     } else {
13463: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13464: 	&Apache::lonhomework::showhash(%slotinfo);
13465: 	my ($tmp)=keys(%slotinfo);
13466: 	if ($tmp=~/^error:/) { return (); }
13467: 	$remembered{$key} = $slotinfo{$which};
13468:     }
13469:     if (ref($slotinfo{$which}) eq 'HASH') {
13470: 	return %{$slotinfo{$which}};
13471:     }
13472:     return $slotinfo{$which};
13473: }
13474: 
13475: sub get_reservable_slots {
13476:     my ($cnum,$cdom,$uname,$udom) = @_;
13477:     my $now = time;
13478:     my $reservable_info;
13479:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13480:     if (exists($remembered{$key})) {
13481:         $reservable_info = $remembered{$key};
13482:     } else {
13483:         my %resv;
13484:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13485:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13486:         $reservable_info = \%resv;
13487:         $remembered{$key} = $reservable_info;
13488:     }
13489:     return $reservable_info;
13490: }
13491: 
13492: sub get_course_slots {
13493:     my ($cnum,$cdom) = @_;
13494:     my $hashid=$cnum.':'.$cdom;
13495:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13496:     if (defined($cached)) {
13497:         if (ref($result) eq 'HASH') {
13498:             return %{$result};
13499:         }
13500:     } else {
13501:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13502:         my ($tmp) = keys(%slots);
13503:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13504:             &do_cache_new('allslots',$hashid,\%slots,600);
13505:             return %slots;
13506:         }
13507:     }
13508:     return;
13509: }
13510: 
13511: sub devalidate_slots_cache {
13512:     my ($cnum,$cdom)=@_;
13513:     my $hashid=$cnum.':'.$cdom;
13514:     &devalidate_cache_new('allslots',$hashid);
13515: }
13516: 
13517: sub get_coursechange {
13518:     my ($cdom,$cnum) = @_;
13519:     if ($cdom eq '' || $cnum eq '') {
13520:         return unless ($env{'request.course.id'});
13521:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13522:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13523:     }
13524:     my $hashid=$cdom.'_'.$cnum;
13525:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13526:     if ((defined($cached)) && ($change ne '')) {
13527:         return $change;
13528:     } else {
13529:         my %crshash;
13530:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13531:         if ($crshash{'internal.contentchange'} eq '') {
13532:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13533:             if ($change eq '') {
13534:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13535:                 $change = $crshash{'internal.created'};
13536:             }
13537:         } else {
13538:             $change = $crshash{'internal.contentchange'};
13539:         }
13540:         my $cachetime = 600;
13541:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13542:     }
13543:     return $change;
13544: }
13545: 
13546: sub devalidate_coursechange_cache {
13547:     my ($cnum,$cdom)=@_;
13548:     my $hashid=$cnum.':'.$cdom;
13549:     &devalidate_cache_new('crschange',$hashid);
13550: }
13551: 
13552: # ------------------------------------------------- Update symbolic store links
13553: 
13554: sub symblist {
13555:     my ($mapname,%newhash)=@_;
13556:     $mapname=&deversion(&declutter($mapname));
13557:     my %hash;
13558:     if (($env{'request.course.fn'}) && (%newhash)) {
13559:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13560:                       &GDBM_WRCREAT(),0640)) {
13561: 	    foreach my $url (keys(%newhash)) {
13562: 		next if ($url eq 'last_known'
13563: 			 && $env{'form.no_update_last_known'});
13564: 		$hash{declutter($url)}=&encode_symb($mapname,
13565: 						    $newhash{$url}->[1],
13566: 						    $newhash{$url}->[0]);
13567:             }
13568:             if (untie(%hash)) {
13569: 		return 'ok';
13570:             }
13571:         }
13572:     }
13573:     return 'error';
13574: }
13575: 
13576: # --------------------------------------------------------------- Verify a symb
13577: 
13578: sub symbverify {
13579:     my ($symb,$thisurl,$encstate)=@_;
13580:     my $thisfn=$thisurl;
13581:     $thisfn=&declutter($thisfn);
13582: # direct jump to resource in page or to a sequence - will construct own symbs
13583:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13584: # check URL part
13585:     my ($map,$resid,$url)=&decode_symb($symb);
13586: 
13587:     unless ($url eq $thisfn) { return 0; }
13588: 
13589:     $symb=&symbclean($symb);
13590:     $thisurl=&deversion($thisurl);
13591:     $thisfn=&deversion($thisfn);
13592: 
13593:     my %bighash;
13594:     my $okay=0;
13595: 
13596:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13597:                             &GDBM_READER(),0640)) {
13598:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13599:             $thisurl =~ s/\?.+$//;
13600:             if ($map =~ m{^uploaded/.+\.page$}) {
13601:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13602:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13603:             }
13604:         }
13605:         my $ids;
13606:         if ($map =~ m{^uploaded/.+\.page$}) {
13607:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13608:         } else {
13609:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13610:         }
13611:         unless ($ids) {
13612:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13613:             $ids=$bighash{$idkey};
13614:         }
13615:         if ($ids) {
13616: # ------------------------------------------------------------------- Has ID(s)
13617:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13618:                 $symb =~ s/\?.+$//;
13619:             }
13620: 	    foreach my $id (split(/\,/,$ids)) {
13621: 	       my ($mapid,$resid)=split(/\./,$id);
13622:                if (
13623:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13624:    eq $symb) {
13625:                    if (ref($encstate)) {
13626:                        $$encstate = $bighash{'encrypted_'.$id};
13627:                    }
13628: 		   if (($env{'request.role.adv'}) ||
13629: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13630:                        ($thisurl eq '/adm/navmaps')) {
13631: 		       $okay=1;
13632:                        last;
13633: 		   }
13634: 	       }
13635: 	   }
13636:         }
13637: 	untie(%bighash);
13638:     }
13639:     return $okay;
13640: }
13641: 
13642: # --------------------------------------------------------------- Clean-up symb
13643: 
13644: sub symbclean {
13645:     my $symb=shift;
13646:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13647: # remove version from map
13648:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13649: 
13650: # remove version from URL
13651:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13652: 
13653: # remove wrapper
13654: 
13655:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13656:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13657:     return $symb;
13658: }
13659: 
13660: # ---------------------------------------------- Split symb to find map and url
13661: 
13662: sub encode_symb {
13663:     my ($map,$resid,$url)=@_;
13664:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13665: }
13666: 
13667: sub decode_symb {
13668:     my $symb=shift;
13669:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13670:     my ($map,$resid,$url)=split(/___/,$symb);
13671:     return (&fixversion($map),$resid,&fixversion($url));
13672: }
13673: 
13674: sub fixversion {
13675:     my $fn=shift;
13676:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13677:     my %bighash;
13678:     my $uri=&clutter($fn);
13679:     my $key=$env{'request.course.id'}.'_'.$uri;
13680: # is this cached?
13681:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13682:     if (defined($cached)) { return $result; }
13683: # unfortunately not cached, or expired
13684:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13685: 	    &GDBM_READER(),0640)) {
13686:  	if ($bighash{'version_'.$uri}) {
13687:  	    my $version=$bighash{'version_'.$uri};
13688:  	    unless (($version eq 'mostrecent') || 
13689: 		    ($version==&getversion($uri))) {
13690:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13691:  	    }
13692:  	}
13693:  	untie %bighash;
13694:     }
13695:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13696: }
13697: 
13698: sub deversion {
13699:     my $url=shift;
13700:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13701:     return $url;
13702: }
13703: 
13704: # ------------------------------------------------------ Return symb list entry
13705: 
13706: sub symbread {
13707:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13708:         $ignoresymbdb,$noenccheck)=@_;
13709:     my $cache_str='request.symbread.cached.'.$thisfn;
13710:     if (defined($env{$cache_str})) {
13711:         unless (ref($possibles) eq 'HASH') {
13712:             if ($ignorecachednull) {
13713:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13714:             } else {
13715:                 return $env{$cache_str};
13716:             }
13717:         }
13718:     }
13719: # no filename provided? try from environment
13720:     unless ($thisfn) {
13721:         if ($env{'request.symb'}) {
13722:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13723: 	}
13724: 	$thisfn=$env{'request.filename'};
13725:     }
13726:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13727: # is that filename actually a symb? Verify, clean, and return
13728:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13729: 	if (&symbverify($thisfn,$1)) {
13730: 	    return $env{$cache_str}=&symbclean($thisfn);
13731: 	}
13732:     }
13733:     $thisfn=declutter($thisfn);
13734:     my %hash;
13735:     my %bighash;
13736:     my $syval='';
13737:     if (($env{'request.course.fn'}) && ($thisfn)) {
13738:         my $targetfn = $thisfn;
13739:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13740:             $targetfn = 'adm/wrapper/'.$thisfn;
13741:         }
13742: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13743: 	    $targetfn=$1;
13744: 	}
13745:         unless ($ignoresymbdb) {
13746:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13747:                           &GDBM_READER(),0640)) {
13748: 	        $syval=$hash{$targetfn};
13749:                 untie(%hash);
13750:             }
13751:             if ($syval && $checkforblock) {
13752:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13753:                 if (@blockers) {
13754:                     $syval='';
13755:                 }
13756:             }
13757:         }
13758: # ---------------------------------------------------------- There was an entry
13759:         if ($syval) {
13760: 	    #unless ($syval=~/\_\d+$/) {
13761: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13762: 		    #&appenv({'request.ambiguous' => $thisfn});
13763: 		    #return $env{$cache_str}='';
13764: 		#}    
13765: 		#$syval.=$1;
13766: 	    #}
13767:         } else {
13768: # ------------------------------------------------------- Was not in symb table
13769:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13770:                             &GDBM_READER(),0640)) {
13771: # ---------------------------------------------- Get ID(s) for current resource
13772:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13773:               unless ($ids) { 
13774:                  $ids=$bighash{'ids_/'.$thisfn};
13775:               }
13776:               unless ($ids) {
13777: # alias?
13778: 		  $ids=$bighash{'mapalias_'.$thisfn};
13779:               }
13780:               if ($ids) {
13781: # ------------------------------------------------------------------- Has ID(s)
13782:                  my @possibilities=split(/\,/,$ids);
13783:                  if ($#possibilities==0) {
13784: # ----------------------------------------------- There is only one possibility
13785: 		     my ($mapid,$resid)=split(/\./,$ids);
13786: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13787: 						    $resid,$thisfn);
13788:                      if (ref($possibles) eq 'HASH') {
13789:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13790:                              $possibles->{$syval} = 1;
13791:                          }
13792:                      }
13793:                      if ($checkforblock) {
13794:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13795:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13796:                              if (@blockers) {
13797:                                  $syval = '';
13798:                                  untie(%bighash);
13799:                                  return $env{$cache_str}='';
13800:                              }
13801:                          }
13802:                      }
13803:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13804: # ------------------------------------------ There is more than one possibility
13805:                      my $realpossible=0;
13806:                      foreach my $id (@possibilities) {
13807: 			 my $file=$bighash{'src_'.$id};
13808:                          my $canaccess;
13809:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13810:                              $canaccess = 1;
13811:                          } else { 
13812:                              $canaccess = &allowed('bre',$file);
13813:                          }
13814:                          if ($canaccess) {
13815:          		     my ($mapid,$resid)=split(/\./,$id);
13816:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13817:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13818: 						             $resid,$thisfn);
13819:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13820:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13821:                                  if ($checkforblock) {
13822:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13823:                                      if (@blockers > 0) {
13824:                                          $syval = '';
13825:                                      } else {
13826:                                          $syval = $poss_syval;
13827:                                          $realpossible++;
13828:                                      }
13829:                                  } else {
13830:                                      $syval = $poss_syval;
13831:                                      $realpossible++;
13832:                                  }
13833:                                  if ($syval) {
13834:                                      if (ref($possibles) eq 'HASH') {
13835:                                          $possibles->{$syval} = 1;
13836:                                      }
13837:                                  }
13838:                              }
13839: 			 }
13840:                      }
13841: 		     if ($realpossible!=1) { $syval=''; }
13842:                  } else {
13843:                      $syval='';
13844:                  }
13845: 	      }
13846:               untie(%bighash);
13847:            }
13848:         }
13849:         if ($syval) {
13850: 	    return $env{$cache_str}=$syval;
13851:         }
13852:     }
13853:     &appenv({'request.ambiguous' => $thisfn});
13854:     return $env{$cache_str}='';
13855: }
13856: 
13857: # ---------------------------------------------------------- Return random seed
13858: 
13859: sub numval {
13860:     my $txt=shift;
13861:     $txt=~tr/A-J/0-9/;
13862:     $txt=~tr/a-j/0-9/;
13863:     $txt=~tr/K-T/0-9/;
13864:     $txt=~tr/k-t/0-9/;
13865:     $txt=~tr/U-Z/0-5/;
13866:     $txt=~tr/u-z/0-5/;
13867:     $txt=~s/\D//g;
13868:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13869:     return int($txt);
13870: }
13871: 
13872: sub numval2 {
13873:     my $txt=shift;
13874:     $txt=~tr/A-J/0-9/;
13875:     $txt=~tr/a-j/0-9/;
13876:     $txt=~tr/K-T/0-9/;
13877:     $txt=~tr/k-t/0-9/;
13878:     $txt=~tr/U-Z/0-5/;
13879:     $txt=~tr/u-z/0-5/;
13880:     $txt=~s/\D//g;
13881:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13882:     my $total;
13883:     foreach my $val (@txts) { $total+=$val; }
13884:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13885:     return int($total);
13886: }
13887: 
13888: sub numval3 {
13889:     use integer;
13890:     my $txt=shift;
13891:     $txt=~tr/A-J/0-9/;
13892:     $txt=~tr/a-j/0-9/;
13893:     $txt=~tr/K-T/0-9/;
13894:     $txt=~tr/k-t/0-9/;
13895:     $txt=~tr/U-Z/0-5/;
13896:     $txt=~tr/u-z/0-5/;
13897:     $txt=~s/\D//g;
13898:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13899:     my $total;
13900:     foreach my $val (@txts) { $total+=$val; }
13901:     if ($_64bit) { $total=(($total<<32)>>32); }
13902:     return $total;
13903: }
13904: 
13905: sub digest {
13906:     my ($data)=@_;
13907:     my $digest=&Digest::MD5::md5($data);
13908:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13909:     my ($e,$f);
13910:     {
13911:         use integer;
13912:         $e=($a+$b);
13913:         $f=($c+$d);
13914:         if ($_64bit) {
13915:             $e=(($e<<32)>>32);
13916:             $f=(($f<<32)>>32);
13917:         }
13918:     }
13919:     if (wantarray) {
13920: 	return ($e,$f);
13921:     } else {
13922: 	my $g;
13923: 	{
13924: 	    use integer;
13925: 	    $g=($e+$f);
13926: 	    if ($_64bit) {
13927: 		$g=(($g<<32)>>32);
13928: 	    }
13929: 	}
13930: 	return $g;
13931:     }
13932: }
13933: 
13934: sub latest_rnd_algorithm_id {
13935:     return '64bit5';
13936: }
13937: 
13938: sub get_rand_alg {
13939:     my ($courseid)=@_;
13940:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13941:     if ($courseid) {
13942: 	return $env{"course.$courseid.rndseed"};
13943:     }
13944:     return &latest_rnd_algorithm_id();
13945: }
13946: 
13947: sub validCODE {
13948:     my ($CODE)=@_;
13949:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13950:     return 0;
13951: }
13952: 
13953: sub getCODE {
13954:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13955:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13956: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13957: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13958: 	return $Apache::lonhomework::history{'resource.CODE'};
13959:     }
13960:     return undef;
13961: }
13962: #
13963: #  Determines the random seed for a specific context:
13964: #
13965: # parameters:
13966: #   symb      - in course context the symb for the seed.
13967: #   course_id - The course id of the form domain_coursenum.
13968: #   domain    - Domain for the user.
13969: #   course    - Course for the user.
13970: #   cenv      - environment of the course.
13971: #
13972: # NOTE:
13973: #   All parameters are picked out of the environment if missing
13974: #   or not defined.
13975: #   If a symb cannot be determined the current time is used instead.
13976: #
13977: #  For a given well defined symb, courside, domain, username,
13978: #  and course environment, the seed is reproducible.
13979: #
13980: sub rndseed {
13981:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13982:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13983:     if (!defined($symb)) {
13984: 	unless ($symb=$wsymb) { return time; }
13985:     }
13986:     if (!defined $courseid) { 
13987: 	$courseid=$wcourseid; 
13988:     }
13989:     if (!defined $domain) { $domain=$wdomain; }
13990:     if (!defined $username) { $username=$wusername }
13991: 
13992:     my $which;
13993:     if (defined($cenv->{'rndseed'})) {
13994: 	$which = $cenv->{'rndseed'};
13995:     } else {
13996: 	$which =&get_rand_alg($courseid);
13997:     }
13998:     if (defined(&getCODE())) {
13999: 
14000: 	if ($which eq '64bit5') {
14001: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14002: 	} elsif ($which eq '64bit4') {
14003: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14004: 	} else {
14005: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14006: 	}
14007:     } elsif ($which eq '64bit5') {
14008: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14009:     } elsif ($which eq '64bit4') {
14010: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14011:     } elsif ($which eq '64bit3') {
14012: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14013:     } elsif ($which eq '64bit2') {
14014: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14015:     } elsif ($which eq '64bit') {
14016: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14017:     }
14018:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14019: }
14020: 
14021: sub rndseed_32bit {
14022:     my ($symb,$courseid,$domain,$username)=@_;
14023:     {
14024: 	use integer;
14025: 	my $symbchck=unpack("%32C*",$symb) << 27;
14026: 	my $symbseed=numval($symb) << 22;
14027: 	my $namechck=unpack("%32C*",$username) << 17;
14028: 	my $nameseed=numval($username) << 12;
14029: 	my $domainseed=unpack("%32C*",$domain) << 7;
14030: 	my $courseseed=unpack("%32C*",$courseid);
14031: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14032: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14033: 	#&logthis("rndseed :$num:$symb");
14034: 	if ($_64bit) { $num=(($num<<32)>>32); }
14035: 	return $num;
14036:     }
14037: }
14038: 
14039: sub rndseed_64bit {
14040:     my ($symb,$courseid,$domain,$username)=@_;
14041:     {
14042: 	use integer;
14043: 	my $symbchck=unpack("%32S*",$symb) << 21;
14044: 	my $symbseed=numval($symb) << 10;
14045: 	my $namechck=unpack("%32S*",$username);
14046: 	
14047: 	my $nameseed=numval($username) << 21;
14048: 	my $domainseed=unpack("%32S*",$domain) << 10;
14049: 	my $courseseed=unpack("%32S*",$courseid);
14050: 	
14051: 	my $num1=$symbchck+$symbseed+$namechck;
14052: 	my $num2=$nameseed+$domainseed+$courseseed;
14053: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14054: 	#&logthis("rndseed :$num:$symb");
14055: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14056: 	return "$num1,$num2";
14057:     }
14058: }
14059: 
14060: sub rndseed_64bit2 {
14061:     my ($symb,$courseid,$domain,$username)=@_;
14062:     {
14063: 	use integer;
14064: 	# strings need to be an even # of cahracters long, it it is odd the
14065:         # last characters gets thrown away
14066: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14067: 	my $symbseed=numval($symb) << 10;
14068: 	my $namechck=unpack("%32S*",$username.' ');
14069: 	
14070: 	my $nameseed=numval($username) << 21;
14071: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14072: 	my $courseseed=unpack("%32S*",$courseid.' ');
14073: 	
14074: 	my $num1=$symbchck+$symbseed+$namechck;
14075: 	my $num2=$nameseed+$domainseed+$courseseed;
14076: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14077: 	#&logthis("rndseed :$num:$symb");
14078: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14079: 	return "$num1,$num2";
14080:     }
14081: }
14082: 
14083: sub rndseed_64bit3 {
14084:     my ($symb,$courseid,$domain,$username)=@_;
14085:     {
14086: 	use integer;
14087: 	# strings need to be an even # of cahracters long, it it is odd the
14088:         # last characters gets thrown away
14089: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14090: 	my $symbseed=numval2($symb) << 10;
14091: 	my $namechck=unpack("%32S*",$username.' ');
14092: 	
14093: 	my $nameseed=numval2($username) << 21;
14094: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14095: 	my $courseseed=unpack("%32S*",$courseid.' ');
14096: 	
14097: 	my $num1=$symbchck+$symbseed+$namechck;
14098: 	my $num2=$nameseed+$domainseed+$courseseed;
14099: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14100: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14101: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14102: 	
14103: 	return "$num1:$num2";
14104:     }
14105: }
14106: 
14107: sub rndseed_64bit4 {
14108:     my ($symb,$courseid,$domain,$username)=@_;
14109:     {
14110: 	use integer;
14111: 	# strings need to be an even # of cahracters long, it it is odd the
14112:         # last characters gets thrown away
14113: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14114: 	my $symbseed=numval3($symb) << 10;
14115: 	my $namechck=unpack("%32S*",$username.' ');
14116: 	
14117: 	my $nameseed=numval3($username) << 21;
14118: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14119: 	my $courseseed=unpack("%32S*",$courseid.' ');
14120: 	
14121: 	my $num1=$symbchck+$symbseed+$namechck;
14122: 	my $num2=$nameseed+$domainseed+$courseseed;
14123: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14124: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14125: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14126: 	
14127: 	return "$num1:$num2";
14128:     }
14129: }
14130: 
14131: sub rndseed_64bit5 {
14132:     my ($symb,$courseid,$domain,$username)=@_;
14133:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14134:     return "$num1:$num2";
14135: }
14136: 
14137: sub rndseed_CODE_64bit {
14138:     my ($symb,$courseid,$domain,$username)=@_;
14139:     {
14140: 	use integer;
14141: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14142: 	my $symbseed=numval2($symb);
14143: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14144: 	my $CODEseed=numval(&getCODE());
14145: 	my $courseseed=unpack("%32S*",$courseid.' ');
14146: 	my $num1=$symbseed+$CODEchck;
14147: 	my $num2=$CODEseed+$courseseed+$symbchck;
14148: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14149: 	#&logthis("rndseed :$num1:$num2:$symb");
14150: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14151: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14152: 	return "$num1:$num2";
14153:     }
14154: }
14155: 
14156: sub rndseed_CODE_64bit4 {
14157:     my ($symb,$courseid,$domain,$username)=@_;
14158:     {
14159: 	use integer;
14160: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14161: 	my $symbseed=numval3($symb);
14162: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14163: 	my $CODEseed=numval3(&getCODE());
14164: 	my $courseseed=unpack("%32S*",$courseid.' ');
14165: 	my $num1=$symbseed+$CODEchck;
14166: 	my $num2=$CODEseed+$courseseed+$symbchck;
14167: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14168: 	#&logthis("rndseed :$num1:$num2:$symb");
14169: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14170: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14171: 	return "$num1:$num2";
14172:     }
14173: }
14174: 
14175: sub rndseed_CODE_64bit5 {
14176:     my ($symb,$courseid,$domain,$username)=@_;
14177:     my $code = &getCODE();
14178:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14179:     return "$num1:$num2";
14180: }
14181: 
14182: sub setup_random_from_rndseed {
14183:     my ($rndseed)=@_;
14184:     if ($rndseed =~/([,:])/) {
14185:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14186:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14187:             &Math::Random::random_set_seed_from_phrase($rndseed);
14188:         } else {
14189:             &Math::Random::random_set_seed($num1,$num2);
14190:         }
14191:     } else {
14192: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14193:     }
14194: }
14195: 
14196: sub latest_receipt_algorithm_id {
14197:     return 'receipt3';
14198: }
14199: 
14200: sub recunique {
14201:     my $fucourseid=shift;
14202:     my $unique;
14203:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14204: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14205: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14206:     } else {
14207: 	$unique=$perlvar{'lonReceipt'};
14208:     }
14209:     return unpack("%32C*",$unique);
14210: }
14211: 
14212: sub recprefix {
14213:     my $fucourseid=shift;
14214:     my $prefix;
14215:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14216: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14217: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14218:     } else {
14219: 	$prefix=$perlvar{'lonHostID'};
14220:     }
14221:     return unpack("%32C*",$prefix);
14222: }
14223: 
14224: sub ireceipt {
14225:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14226: 
14227:     my $return =&recprefix($fucourseid).'-';
14228: 
14229:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14230: 	$env{'request.state'} eq 'construct') {
14231: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14232: 	return $return;
14233:     }
14234: 
14235:     my $cuname=unpack("%32C*",$funame);
14236:     my $cudom=unpack("%32C*",$fudom);
14237:     my $cucourseid=unpack("%32C*",$fucourseid);
14238:     my $cusymb=unpack("%32C*",$fusymb);
14239:     my $cunique=&recunique($fucourseid);
14240:     my $cpart=unpack("%32S*",$part);
14241:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14242: 
14243: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14244: 			       
14245: 	$return.= ($cunique%$cuname+
14246: 		   $cunique%$cudom+
14247: 		   $cusymb%$cuname+
14248: 		   $cusymb%$cudom+
14249: 		   $cucourseid%$cuname+
14250: 		   $cucourseid%$cudom+
14251: 		   $cpart%$cuname+
14252: 		   $cpart%$cudom);
14253:     } else {
14254: 	$return.= ($cunique%$cuname+
14255: 		   $cunique%$cudom+
14256: 		   $cusymb%$cuname+
14257: 		   $cusymb%$cudom+
14258: 		   $cucourseid%$cuname+
14259: 		   $cucourseid%$cudom);
14260:     }
14261:     return $return;
14262: }
14263: 
14264: sub receipt {
14265:     my ($part)=@_;
14266:     my ($symb,$courseid,$domain,$name) = &whichuser();
14267:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14268: }
14269: 
14270: sub whichuser {
14271:     my ($passedsymb)=@_;
14272:     my ($symb,$courseid,$domain,$name,$publicuser);
14273:     if (defined($env{'form.grade_symb'})) {
14274: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14275: 	my $allowed=&allowed('vgr',$tmp_courseid);
14276: 	if (!$allowed &&
14277: 	    exists($env{'request.course.sec'}) &&
14278: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14279: 	    $allowed=&allowed('vgr',$tmp_courseid.
14280: 			      '/'.$env{'request.course.sec'});
14281: 	}
14282: 	if ($allowed) {
14283: 	    ($symb)=&get_env_multiple('form.grade_symb');
14284: 	    $courseid=$tmp_courseid;
14285: 	    ($domain)=&get_env_multiple('form.grade_domain');
14286: 	    ($name)=&get_env_multiple('form.grade_username');
14287: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14288: 	}
14289:     }
14290:     if (!$passedsymb) {
14291: 	$symb=&symbread();
14292:     } else {
14293: 	$symb=$passedsymb;
14294:     }
14295:     $courseid=$env{'request.course.id'};
14296:     $domain=$env{'user.domain'};
14297:     $name=$env{'user.name'};
14298:     if ($name eq 'public' && $domain eq 'public') {
14299: 	if (!defined($env{'form.username'})) {
14300: 	    $env{'form.username'}.=time.rand(10000000);
14301: 	}
14302: 	$name.=$env{'form.username'};
14303:     }
14304:     return ($symb,$courseid,$domain,$name,$publicuser);
14305: 
14306: }
14307: 
14308: # ------------------------------------------------------------ Serves up a file
14309: # returns either the contents of the file or 
14310: # -1 if the file doesn't exist
14311: #
14312: # if the target is a file that was uploaded via DOCS, 
14313: # a check will be made to see if a current copy exists on the local server,
14314: # if it does this will be served, otherwise a copy will be retrieved from
14315: # the home server for the course and stored in /home/httpd/html/userfiles on
14316: # the local server.   
14317: 
14318: sub getfile {
14319:     my ($file) = @_;
14320:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14321:     &repcopy($file);
14322:     return &readfile($file);
14323: }
14324: 
14325: sub repcopy_userfile {
14326:     my ($file)=@_;
14327:     my $londocroot = $perlvar{'lonDocRoot'};
14328:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14329:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14330:     my ($cdom,$cnum,$filename) = 
14331: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14332:     my $uri="/uploaded/$cdom/$cnum/$filename";
14333:     if (-e "$file") {
14334: # we already have a local copy, check it out
14335: 	my @fileinfo = stat($file);
14336: 	my $rtncode;
14337: 	my $info;
14338: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14339: 	if ($lwpresp ne 'ok') {
14340: # there is no such file anymore, even though we had a local copy
14341: 	    if ($rtncode eq '404') {
14342: 		unlink($file);
14343: 	    }
14344: 	    return -1;
14345: 	}
14346: 	if ($info < $fileinfo[9]) {
14347: # nice, the file we have is up-to-date, just say okay
14348: 	    return 'ok';
14349: 	} else {
14350: # the file is outdated, get rid of it
14351: 	    unlink($file);
14352: 	}
14353:     }
14354: # one way or the other, at this point, we don't have the file
14355: # construct the correct path for the file
14356:     my @parts = ($cdom,$cnum); 
14357:     if ($filename =~ m|^(.+)/[^/]+$|) {
14358: 	push @parts, split(/\//,$1);
14359:     }
14360:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14361:     foreach my $part (@parts) {
14362: 	$path .= '/'.$part;
14363: 	if (!-e $path) {
14364: 	    mkdir($path,0770);
14365: 	}
14366:     }
14367: # now the path exists for sure
14368: # get a user agent
14369:     my $transferfile=$file.'.in.transfer';
14370: # FIXME: this should flock
14371:     if (-e $transferfile) { return 'ok'; }
14372:     my $request;
14373:     $uri=~s/^\///;
14374:     my $homeserver = &homeserver($cnum,$cdom);
14375:     my $hostname = &hostname($homeserver);
14376:     my $protocol = $protocol{$homeserver};
14377:     $protocol = 'http' if ($protocol ne 'https');
14378:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14379:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14380: # did it work?
14381:     if ($response->is_error()) {
14382: 	unlink($transferfile);
14383: 	&logthis("Userfile repcopy failed for $uri");
14384: 	return -1;
14385:     }
14386: # worked, rename the transfer file
14387:     rename($transferfile,$file);
14388:     return 'ok';
14389: }
14390: 
14391: sub tokenwrapper {
14392:     my $uri=shift;
14393:     $uri=~s|^https?\://([^/]+)||;
14394:     $uri=~s|^/||;
14395:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14396:     my $token=$1;
14397:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14398:     if ($udom && $uname && $file) {
14399: 	$file=~s|(\?\.*)*$||;
14400:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14401:         my $homeserver = &homeserver($uname,$udom);
14402:         my $hostname = &hostname($homeserver);
14403:         my $protocol = $protocol{$homeserver};
14404:         $protocol = 'http' if ($protocol ne 'https');
14405:         return $protocol.'://'.$hostname.'/'.$uri.
14406:                (($uri=~/\?/)?'&':'?').'token='.$token.
14407:                                '&tokenissued='.$perlvar{'lonHostID'};
14408:     } else {
14409:         return '/adm/notfound.html';
14410:     }
14411: }
14412: 
14413: # call with reqtype HEAD: get last modification time
14414: # call with reqtype GET: get the file contents
14415: # Do not call this with reqtype GET for large files! It loads everything into memory
14416: #
14417: sub getuploaded {
14418:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14419:     $uri=~s/^\///;
14420:     my $homeserver = &homeserver($cnum,$cdom);
14421:     my $hostname = &hostname($homeserver);
14422:     my $protocol = $protocol{$homeserver};
14423:     $protocol = 'http' if ($protocol ne 'https');
14424:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14425:     my $request=new HTTP::Request($reqtype,$uri);
14426:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14427:     $$rtncode = $response->code;
14428:     if (! $response->is_success()) {
14429: 	return 'failed';
14430:     }      
14431:     if ($reqtype eq 'HEAD') {
14432: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14433:     } elsif ($reqtype eq 'GET') {
14434: 	$$info = $response->content;
14435:     }
14436:     return 'ok';
14437: }
14438: 
14439: sub readfile {
14440:     my $file = shift;
14441:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14442:     my $fh;
14443:     open($fh,"<",$file);
14444:     my $a='';
14445:     while (my $line = <$fh>) { $a .= $line; }
14446:     return $a;
14447: }
14448: 
14449: sub filelocation {
14450:     my ($dir,$file) = @_;
14451:     my $location;
14452:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14453: 
14454:     if ($file =~ m-^/adm/-) {
14455: 	$file=~s-^/adm/wrapper/-/-;
14456: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14457:     }
14458: 
14459:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14460:         $location = $file;
14461:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14462:         my ($udom,$uname,$filename)=
14463:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14464:         my $home=&homeserver($uname,$udom);
14465:         my $is_me=0;
14466:         my @ids=&current_machine_ids();
14467:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14468:         if ($is_me) {
14469:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14470:         } else {
14471:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14472:   	      $udom.'/'.$uname.'/'.$filename;
14473:         }
14474:     } elsif ($file =~ m-^/adm/-) {
14475: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14476:     } else {
14477:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14478:         $file=~s:^/(res|priv)/:/:;
14479:         my $space=$1;
14480:         if ( !( $file =~ m:^/:) ) {
14481:             $location = $dir. '/'.$file;
14482:         } else {
14483:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14484:         }
14485:     }
14486:     $location=~s://+:/:g; # remove duplicate /
14487:     while ($location=~m{/\.\./}) {
14488: 	if ($location =~ m{/[^/]+/\.\./}) {
14489: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14490: 	} else {
14491: 	    $location=~ s{/\.\./}{/}g;
14492: 	}
14493:     } #remove dir/..
14494:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14495:     return $location;
14496: }
14497: 
14498: sub hreflocation {
14499:     my ($dir,$file)=@_;
14500:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14501: 	$file=filelocation($dir,$file);
14502:     } elsif ($file=~m-^/adm/-) {
14503: 	$file=~s-^/adm/wrapper/-/-;
14504: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14505:     }
14506:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14507: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14508:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14509: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14510: 	        {/uploaded/$1/$2/}x;
14511:     }
14512:     if ($file=~ m{^/userfiles/}) {
14513: 	$file =~ s{^/userfiles/}{/uploaded/};
14514:     }
14515:     return $file;
14516: }
14517: 
14518: 
14519: 
14520: 
14521: 
14522: sub current_machine_domains {
14523:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14524: }
14525: 
14526: sub machine_domains {
14527:     my ($hostname) = @_;
14528:     my @domains;
14529:     my %hostname = &all_hostnames();
14530:     while( my($id, $name) = each(%hostname)) {
14531: #	&logthis("-$id-$name-$hostname-");
14532: 	if ($hostname eq $name) {
14533: 	    push(@domains,&host_domain($id));
14534: 	}
14535:     }
14536:     return @domains;
14537: }
14538: 
14539: sub current_machine_ids {
14540:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14541: }
14542: 
14543: sub machine_ids {
14544:     my ($hostname) = @_;
14545:     $hostname ||= &hostname($perlvar{'lonHostID'});
14546:     my @ids;
14547:     my %name_to_host = &all_names();
14548:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14549: 	return @{ $name_to_host{$hostname} };
14550:     }
14551:     return;
14552: }
14553: 
14554: sub additional_machine_domains {
14555:     my @domains;
14556:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14557:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14558:             while (my $line = <$fh>) {
14559:                 chomp($line);           
14560:                 $line =~ s/\s//g;
14561:                 push(@domains,$line);
14562:             }
14563:             close($fh);
14564:         }
14565:     }
14566:     return @domains;
14567: }
14568: 
14569: sub default_login_domain {
14570:     my $domain = $perlvar{'lonDefDomain'};
14571:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14572:     foreach my $posdom (&current_machine_domains(),
14573:                         &additional_machine_domains()) {
14574:         if (lc($posdom) eq lc($testdomain)) {
14575:             $domain=$posdom;
14576:             last;
14577:         }
14578:     }
14579:     return $domain;
14580: }
14581: 
14582: sub shared_institution {
14583:     my ($dom,$lonhost) = @_;
14584:     if ($lonhost eq '') {
14585:         $lonhost = $perlvar{'lonHostID'};
14586:     }
14587:     my $same_intdom;
14588:     my $hostintdom = &internet_dom($lonhost);
14589:     if ($hostintdom ne '') {
14590:         my %iphost = &get_iphost();
14591:         my $primary_id = &domain($dom,'primary');
14592:         my $primary_ip = &get_host_ip($primary_id);
14593:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14594:             foreach my $id (@{$iphost{$primary_ip}}) {
14595:                 my $intdom = &internet_dom($id);
14596:                 if ($intdom eq $hostintdom) {
14597:                     $same_intdom = 1;
14598:                     last;
14599:                 }
14600:             }
14601:         }
14602:     }
14603:     return $same_intdom;
14604: }
14605: 
14606: sub uses_sts {
14607:     my ($ignore_cache) = @_;
14608:     my $lonhost = $perlvar{'lonHostID'};
14609:     my $hostname = &hostname($lonhost);
14610:     my $sts_on;
14611:     if ($protocol{$lonhost} eq 'https') {
14612:         my $cachetime = 12*3600;
14613:         if (!$ignore_cache) {
14614:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14615:             if (defined($cached)) {
14616:                 return $sts_on;
14617:             }
14618:         }
14619:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14620:         my $request=new HTTP::Request('HEAD',$url);
14621:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14622:         if ($response->is_success) {
14623:             my $has_sts = $response->header('Strict-Transport-Security');
14624:             if ($has_sts eq '') {
14625:                 $sts_on = 0;
14626:             } else {
14627:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14628:                     my $maxage = $1;
14629:                     if ($maxage) {
14630:                         $sts_on = 1;
14631:                     } else {
14632:                         $sts_on = 0;
14633:                     }
14634:                 } else {
14635:                     $sts_on = 0;
14636:                 }
14637:             }
14638:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14639:         }
14640:     }
14641:     return;
14642: }
14643: 
14644: sub waf_allssl {
14645:     my ($host_name) = @_;
14646:     my $alias = &get_proxy_alias();
14647:     if ($host_name eq '') {
14648:         $host_name = $ENV{'SERVER_NAME'};
14649:     }
14650:     if (($host_name ne '') && ($alias eq $host_name)) {
14651:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14652:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14653:         if ($defdomdefaults{'waf_sslopt'}) {
14654:             return $defdomdefaults{'waf_sslopt'};
14655:         }
14656:     }
14657:     return;
14658: }
14659: 
14660: sub get_requestor_ip {
14661:     my ($r,$nolookup,$noproxy) = @_;
14662:     my $from_ip;
14663:     if (ref($r)) {
14664:         if ($r->can('useragent_ip')) {
14665:             if ($noproxy && $r->can('client_ip')) {
14666:                 $from_ip = $r->client_ip();
14667:             } else {
14668:                 $from_ip = $r->useragent_ip();
14669:             }
14670:         } elsif ($r->connection->can('remote_ip')) {
14671:             $from_ip = $r->connection->remote_ip();
14672:         } else {
14673:             $from_ip = $r->get_remote_host($nolookup);
14674:         }
14675:     } else {
14676:         $from_ip = $ENV{'REMOTE_ADDR'};
14677:     }
14678:     return $from_ip if ($noproxy); 
14679:     # Who controls proxy settings for server
14680:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14681:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14682:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14683:         if ($proxyinfo->{'vpnint'}) {
14684:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14685:                 return $from_ip;
14686:             }
14687:         }
14688:         if ($proxyinfo->{'trusted'}) {
14689:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14690:                 my $ipheader = $proxyinfo->{'ipheader'};
14691:                 my ($ip,$xfor);
14692:                 if (ref($r)) {
14693:                     if ($ipheader) {
14694:                         $ip = $r->headers_in->{$ipheader};
14695:                     }
14696:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14697:                 } else {
14698:                     if ($ipheader) {
14699:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14700:                     }
14701:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14702:                 }
14703:                 if (($ip eq '') && ($xfor ne '')) {
14704:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14705:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14706:                             $ip = $poss_ip;
14707:                             last;
14708:                         }
14709:                     }
14710:                 }
14711:                 if ($ip ne '') {
14712:                     return $ip;
14713:                 }
14714:             }
14715:         }
14716:     }
14717:     return $from_ip;
14718: }
14719: 
14720: sub get_proxy_settings {
14721:     my ($dom_in_use) = @_;
14722:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14723:     my $proxyinfo = {
14724:                        ipheader => $domdefaults{'waf_ipheader'},
14725:                        trusted  => $domdefaults{'waf_trusted'},
14726:                        vpnint   => $domdefaults{'waf_vpnint'},
14727:                        vpnext   => $domdefaults{'waf_vpnext'},
14728:                        sslopt   => $domdefaults{'waf_sslopt'},
14729:                     };
14730:     return $proxyinfo;
14731: }
14732: 
14733: sub ip_match {
14734:     my ($ip,$pattern_str) = @_;
14735:     $ip=Net::CIDR::cidrvalidate($ip);
14736:     if ($ip) {
14737:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14738:     }
14739:     return;
14740: }
14741: 
14742: sub get_proxy_alias {
14743:     my ($lonid) = @_;
14744:     if ($lonid eq '') {
14745:         $lonid = $perlvar{'lonHostID'};
14746:     }
14747:     if (!defined(&hostname($lonid))) {
14748:         return;
14749:     }
14750:     if ($lonid ne '') {
14751:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14752:         if ($cached) {
14753:             return $alias;
14754:         }
14755:         my $dom = &Apache::lonnet::host_domain($lonid);
14756:         if ($dom ne '') {
14757:             my $cachetime = 60*60*24;
14758:             my %domconfig =
14759:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14760:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14761:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14762:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14763:                 }
14764:             }
14765:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14766:         }
14767:     }
14768:     return;
14769: }
14770: 
14771: sub use_proxy_alias {
14772:     my ($r,$lonid) = @_;
14773:     my $alias = &get_proxy_alias($lonid);
14774:     if ($alias) {
14775:         my $dom = &host_domain($lonid);
14776:         if ($dom ne '') {
14777:             my $proxyinfo = &get_proxy_settings($dom);
14778:             my ($vpnint,$remote_ip);
14779:             if (ref($proxyinfo) eq 'HASH') {
14780:                 $vpnint = $proxyinfo->{'vpnint'};
14781:                 if ($vpnint) {
14782:                     $remote_ip = &get_requestor_ip($r,1,1);
14783:                 }
14784:             }
14785:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14786:                 return $alias;
14787:             }
14788:         }
14789:     }
14790:     return;
14791: }
14792: 
14793: sub alias_sso {
14794:     my ($lonid) = @_;
14795:     if ($lonid eq '') {
14796:         $lonid = $perlvar{'lonHostID'};
14797:     }
14798:     if (!defined(&hostname($lonid))) {
14799:         return;
14800:     }
14801:     if ($lonid ne '') {
14802:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14803:         if ($cached) {
14804:             return $use_alias;
14805:         }
14806:         my $dom = &Apache::lonnet::host_domain($lonid);
14807:         if ($dom ne '') {
14808:             my $cachetime = 60*60*24;
14809:             my %domconfig =
14810:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14811:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14812:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14813:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14814:                 }
14815:             }
14816:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14817:         }
14818:     }
14819:     return;
14820: }
14821: 
14822: sub get_saml_landing {
14823:     my ($lonid) = @_;
14824:     if ($lonid eq '') {
14825:         my $defdom = &default_login_domain();
14826:         my @hosts = &current_machine_ids();
14827:         if (@hosts > 1) {
14828:             foreach my $hostid (@hosts) {
14829:                 if (&host_domain($hostid) eq $defdom) {
14830:                     $lonid = $hostid;
14831:                     last;
14832:                 }
14833:             }
14834:         } else {
14835:             $lonid = $perlvar{'lonHostID'};
14836:         }
14837:         if ($lonid) {
14838:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14839:                 return;
14840:             }
14841:         } else {
14842:             return;
14843:         }
14844:     } elsif (!defined(&hostname($lonid))) {
14845:         return;
14846:     }
14847:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14848:     if ($cached) {
14849:         return $landing;
14850:     }
14851:     my $dom = &Apache::lonnet::host_domain($lonid);
14852:     if ($dom ne '') {
14853:         my $cachetime = 60*60*24;
14854:         my %domconfig =
14855:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
14856:         if (ref($domconfig{'login'}) eq 'HASH') {
14857:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14858:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14859:                     $landing = 1;
14860:                 }
14861:             }
14862:         }
14863:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14864:     }
14865:     return;
14866: }
14867: 
14868: # ------------------------------------------------------------- Declutters URLs
14869: 
14870: sub declutter {
14871:     my $thisfn=shift;
14872:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14873:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14874:         $thisfn=~s{^/home/httpd/html}{};
14875:     }
14876:     $thisfn=~s/^\///;
14877:     $thisfn=~s|^adm/wrapper/||;
14878:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14879:     $thisfn=~s/^res\///;
14880:     $thisfn=~s/^priv\///;
14881:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14882:         $thisfn=~s/\?.+$//;
14883:     }
14884:     return $thisfn;
14885: }
14886: 
14887: # ------------------------------------------------------------- Clutter up URLs
14888: 
14889: sub clutter {
14890:     my $thisfn='/'.&declutter(shift);
14891:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14892: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14893:        $thisfn='/res'.$thisfn; 
14894:     }
14895:     if ($thisfn !~m|^/adm|) {
14896: 	if ($thisfn =~ m|^/ext/|) {
14897: 	    $thisfn='/adm/wrapper'.$thisfn;
14898: 	} else {
14899: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14900: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14901: 	    if ($embstyle eq 'ssi'
14902: 		|| ($embstyle eq 'hdn')
14903: 		|| ($embstyle eq 'rat')
14904: 		|| ($embstyle eq 'prv')
14905: 		|| ($embstyle eq 'ign')) {
14906: 		#do nothing with these
14907: 	    } elsif (($embstyle eq 'img') 
14908: 		|| ($embstyle eq 'emb')
14909: 		|| ($embstyle eq 'wrp')) {
14910: 		$thisfn='/adm/wrapper'.$thisfn;
14911: 	    } elsif ($embstyle eq 'unk'
14912: 		     && $thisfn!~/\.(sequence|page)$/) {
14913: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14914: 	    } else {
14915: #		&logthis("Got a blank emb style");
14916: 	    }
14917: 	}
14918:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14919:         $thisfn='/adm/wrapper'.$thisfn;
14920:     }
14921:     return $thisfn;
14922: }
14923: 
14924: sub clutter_with_no_wrapper {
14925:     my $uri = &clutter(shift);
14926:     if ($uri =~ m-^/adm/-) {
14927: 	$uri =~ s-^/adm/wrapper/-/-;
14928: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14929:     }
14930:     return $uri;
14931: }
14932: 
14933: sub freeze_escape {
14934:     my ($value)=@_;
14935:     if (ref($value)) {
14936: 	$value=&nfreeze($value);
14937: 	return '__FROZEN__'.&escape($value);
14938:     }
14939:     return &escape($value);
14940: }
14941: 
14942: 
14943: sub thaw_unescape {
14944:     my ($value)=@_;
14945:     if ($value =~ /^__FROZEN__/) {
14946: 	substr($value,0,10,undef);
14947: 	$value=&unescape($value);
14948: 	return &thaw($value);
14949:     }
14950:     return &unescape($value);
14951: }
14952: 
14953: sub correct_line_ends {
14954:     my ($result)=@_;
14955:     $$result =~s/\r\n/\n/mg;
14956:     $$result =~s/\r/\n/mg;
14957: }
14958: # ================================================================ Main Program
14959: 
14960: sub goodbye {
14961:    &logthis("Starting Shut down");
14962: #not converted to using infrastruture and probably shouldn't be
14963:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14964: #converted
14965: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14966:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14967: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14968: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14969: #1.1 only
14970: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14971: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14972: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14973: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14974:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14975:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14976:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14977:    &flushcourselogs();
14978:    &logthis("Shutting down");
14979: }
14980: 
14981: sub get_dns {
14982:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14983:     if (!$ignore_cache) {
14984: 	my ($content,$cached)=
14985: 	    &Apache::lonnet::is_cached_new('dns',$url);
14986: 	if ($cached) {
14987: 	    &$func($content,$hashref);
14988: 	    return;
14989: 	}
14990:     }
14991: 
14992:     my %alldns;
14993:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14994:         foreach my $dns (<$config>) {
14995: 	    next if ($dns !~ /^\^(\S*)/x);
14996:             my $line = $1;
14997:             my ($host,$protocol) = split(/:/,$line);
14998:             if ($protocol ne 'https') {
14999:                 $protocol = 'http';
15000:             }
15001: 	    $alldns{$host} = $protocol;
15002:         }
15003:         close($config);
15004:     }
15005:     while (%alldns) {
15006: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15007:         my ($contents,@content);
15008:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15009:             my $command = (split('/',$url))[3];
15010:             my ($dir,$file) = &parse_getdns_url($command,$url);
15011:             delete($alldns{$dns});
15012:             next if (($dir eq '') || ($file eq ''));
15013:             if (open(my $config,'<',"$dir/$file")) {
15014:                 @content = <$config>;
15015:                 close($config);
15016:             }
15017:             if ($url eq '/adm/dns/loncapaCRL') {
15018:                 $contents = join('',@content);
15019:             }
15020:         } else {
15021: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15022:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15023:             delete($alldns{$dns});
15024: 	    next if ($response->is_error());
15025:             if ($url eq '/adm/dns/loncapaCRL') {
15026:                 $contents = $response->content;
15027:             } else {
15028:                 @content = split("\n",$response->content);
15029:             }
15030:         }
15031:         if ($url eq '/adm/dns/loncapaCRL') {
15032:             return &$func($contents);
15033:         } else {
15034: 	    unless ($nocache) {
15035: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15036: 	    }
15037: 	    &$func(\@content,$hashref);
15038:             return;
15039:         }
15040:     }
15041:     my $which = (split('/',$url,4))[3];
15042:     if ($which eq 'loncapaCRL') {
15043:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15044:         if (-e $diskfile) {
15045:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15046:         } else {
15047:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15048:         }
15049:     } else {
15050:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15051:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15052:             my @content = <$config>;
15053:             close($config);
15054:             &$func(\@content,$hashref);
15055:         }
15056:     }
15057:     return;
15058: }
15059: 
15060: # ------------------------------------------------------Get DNS checksums file
15061: sub parse_dns_checksums_tab {
15062:     my ($lines,$hashref) = @_;
15063:     my $lonhost = $perlvar{'lonHostID'};
15064:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
15065:     my $loncaparev = &get_server_loncaparev($machine_dom);
15066:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15067:     my $webconfdir = '/etc/httpd/conf';
15068:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15069:         $webconfdir = '/etc/apache2';
15070:     } elsif ($distro =~ /^sles(\d+)$/) {
15071:         if ($1 >= 10) {
15072:             $webconfdir = '/etc/apache2';
15073:         }
15074:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15075:         if ($1 >= 10.0) {
15076:             $webconfdir = '/etc/apache2';
15077:         }
15078:     }
15079:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15080:     my (%chksum,%revnum);
15081:     if (ref($lines) eq 'ARRAY') {
15082:         chomp(@{$lines});
15083:         my $version = shift(@{$lines});
15084:         if ($version eq $release) {  
15085:             foreach my $line (@{$lines}) {
15086:                 my ($file,$version,$shasum) = split(/,/,$line);
15087:                 if ($file =~ m{^/etc/httpd/conf}) {
15088:                     if ($webconfdir eq '/etc/apache2') {
15089:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15090:                     }
15091:                 }
15092:                 $chksum{$file} = $shasum;
15093:                 $revnum{$file} = $version;
15094:             }
15095:             if (ref($hashref) eq 'HASH') {
15096:                 %{$hashref} = (
15097:                                 sums     => \%chksum,
15098:                                 versions => \%revnum,
15099:                               );
15100:             }
15101:         }
15102:     }
15103:     return;
15104: }
15105: 
15106: sub fetch_dns_checksums {
15107:     my %checksums;
15108:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
15109:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15110:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15111:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15112:              \%checksums);
15113:     return \%checksums;
15114: }
15115: 
15116: sub fetch_crl_pemfile {
15117:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15118: }
15119: 
15120: sub save_crl_pem {
15121:     my ($content) = @_;
15122:     my ($msg,$hadchanges);
15123:     if ($content ne '') {
15124:         my $now = time;
15125:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15126:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15127:         if (open(my $fh,'>',"$tmpcrl")) {
15128:             print $fh $content;
15129:             close($fh);
15130:             if (-e $lonca) {
15131:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15132:                     my $check = <PIPE>;
15133:                     close(PIPE);
15134:                     chomp($check);
15135:                     if ($check eq 'verify OK') {
15136:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15137:                         my $backup;
15138:                         if (-e $dest) {
15139:                             if (&File::Copy::move($dest,"$dest.bak")) {
15140:                                 $backup = 'ok';
15141:                             }
15142:                         }
15143:                         if (&File::Copy::move($tmpcrl,$dest)) {
15144:                             $msg = 'ok';
15145:                             if ($backup) {
15146:                                 my (%oldnums,%newnums);
15147:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15148:                                     while (<PIPE>) {
15149:                                         $oldnums{(split(/:/))[1]} = 1;
15150:                                     }
15151:                                     close(PIPE);
15152:                                 }
15153:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15154:                                     while(<PIPE>) {
15155:                                         $newnums{(split(/:/))[1]} = 1;
15156:                                     }
15157:                                     close(PIPE);
15158:                                 }
15159:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15160:                                     unless (exists($oldnums{$key})) {
15161:                                         $hadchanges = 1;
15162:                                         last;
15163:                                     }
15164:                                 }
15165:                                 unless ($hadchanges) {
15166:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15167:                                         unless (exists($newnums{$key})) {
15168:                                             $hadchanges = 1;
15169:                                             last;
15170:                                         }
15171:                                     }
15172:                                 }
15173:                             }
15174:                         }
15175:                     } else {
15176:                         unlink($tmpcrl);
15177:                     }
15178:                 } else {
15179:                     unlink($tmpcrl);
15180:                 }
15181:             } else {
15182:                 unlink($tmpcrl);
15183:             }
15184:         }
15185:     }
15186:     return ($msg,$hadchanges);
15187: }
15188: 
15189: sub parse_getdns_url {
15190:     my ($command,$url) = @_;
15191:     my $dir = $perlvar{'lonTabDir'};
15192:     my $file;
15193:     if ($command eq 'hosts') {
15194:         $file = 'dns_hosts.tab';
15195:     } elsif ($command eq 'domain') {
15196:         $file = 'dns_domain.tab';
15197:     } elsif ($command eq 'checksums') {
15198:         my $version = (split('/',$url))[4];
15199:         $file = "dns_checksums/$version.tab",
15200:     } elsif ($command eq 'loncapaCRL') {
15201:         $dir = $perlvar{'lonCertificateDirectory'};
15202:         $file = $perlvar{'lonnetCertRevocationList'};
15203:     }
15204:     return ($dir,$file);
15205: }
15206: 
15207: # ------------------------------------------------------------ Read domain file
15208: {
15209:     my $loaded;
15210:     my %domain;
15211: 
15212:     sub parse_domain_tab {
15213: 	my ($lines) = @_;
15214: 	foreach my $line (@$lines) {
15215: 	    next if ($line =~ /^(\#|\s*$ )/x);
15216: 
15217: 	    chomp($line);
15218: 	    my ($name,@elements) = split(/:/,$line,9);
15219: 	    my %this_domain;
15220: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15221: 			       'lang_def', 'city', 'longi', 'lati',
15222: 			       'primary') {
15223: 		$this_domain{$field} = shift(@elements);
15224: 	    }
15225: 	    $domain{$name} = \%this_domain;
15226: 	}
15227:     }
15228: 
15229:     sub reset_domain_info {
15230: 	undef($loaded);
15231: 	undef(%domain);
15232:     }
15233: 
15234:     sub load_domain_tab {
15235: 	my ($ignore_cache,$nocache) = @_;
15236: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15237: 	my $fh;
15238: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15239: 	    my @lines = <$fh>;
15240: 	    &parse_domain_tab(\@lines);
15241: 	}
15242: 	close($fh);
15243: 	$loaded = 1;
15244:     }
15245: 
15246:     sub domain {
15247: 	&load_domain_tab() if (!$loaded);
15248: 
15249: 	my ($name,$what) = @_;
15250: 	return if ( !exists($domain{$name}) );
15251: 
15252: 	if (!$what) {
15253: 	    return $domain{$name}{'description'};
15254: 	}
15255: 	return $domain{$name}{$what};
15256:     }
15257: 
15258:     sub domain_info {
15259:         &load_domain_tab() if (!$loaded);
15260:         return %domain;
15261:     }
15262: 
15263: }
15264: 
15265: 
15266: # ------------------------------------------------------------- Read hosts file
15267: {
15268:     my %hostname;
15269:     my %hostdom;
15270:     my %libserv;
15271:     my $loaded;
15272:     my %name_to_host;
15273:     my %internetdom;
15274:     my %LC_dns_serv;
15275: 
15276:     sub parse_hosts_tab {
15277: 	my ($file) = @_;
15278: 	foreach my $configline (@$file) {
15279: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15280:             chomp($configline);
15281: 	    if ($configline =~ /^\^/) {
15282:                 if ($configline =~ /^\^([\w.\-]+)/) {
15283:                     $LC_dns_serv{$1} = 1;
15284:                 }
15285:                 next;
15286:             }
15287: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15288: 	    $name=~s/\s//g;
15289: 	    if ($id && $domain && $role && $name) {
15290:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15291:                     my $curr = $hostname{$id};
15292:                     my $skip;
15293:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15294:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15295:                             $skip = 1;
15296:                         } else {
15297:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15298:                         }
15299:                     }
15300:                     unless ($skip) {
15301:                         push(@{$name_to_host{$name}},$id);
15302:                     }
15303:                 } else {
15304:                     push(@{$name_to_host{$name}},$id);
15305:                 }
15306: 		$hostname{$id}=$name;
15307: 		$hostdom{$id}=$domain;
15308: 		if ($role eq 'library') { $libserv{$id}=$name; }
15309:                 if (defined($protocol)) {
15310:                     if ($protocol eq 'https') {
15311:                         $protocol{$id} = $protocol;
15312:                     } else {
15313:                         $protocol{$id} = 'http'; 
15314:                     }
15315:                 } else {
15316:                     $protocol{$id} = 'http';
15317:                 }
15318:                 if (defined($intdom)) {
15319:                     $internetdom{$id} = $intdom;
15320:                 }
15321: 	    }
15322: 	}
15323:     }
15324:     
15325:     sub reset_hosts_info {
15326: 	&purge_remembered();
15327: 	&reset_domain_info();
15328: 	&reset_hosts_ip_info();
15329:         undef(%internetdom);
15330: 	undef(%name_to_host);
15331: 	undef(%hostname);
15332: 	undef(%hostdom);
15333: 	undef(%libserv);
15334: 	undef($loaded);
15335:     }
15336: 
15337:     sub load_hosts_tab {
15338: 	my ($ignore_cache,$nocache) = @_;
15339: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15340: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15341: 	my @config = <$config>;
15342: 	&parse_hosts_tab(\@config);
15343: 	close($config);
15344: 	$loaded=1;
15345:     }
15346: 
15347:     sub hostname {
15348: 	&load_hosts_tab() if (!$loaded);
15349: 
15350: 	my ($lonid) = @_;
15351: 	return $hostname{$lonid};
15352:     }
15353: 
15354:     sub all_hostnames {
15355: 	&load_hosts_tab() if (!$loaded);
15356: 
15357: 	return %hostname;
15358:     }
15359: 
15360:     sub all_names {
15361:         my ($ignore_cache,$nocache) = @_;
15362: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15363: 
15364: 	return %name_to_host;
15365:     }
15366: 
15367:     sub all_host_domain {
15368:         &load_hosts_tab() if (!$loaded);
15369:         return %hostdom;
15370:     }
15371: 
15372:     sub all_host_intdom {
15373:         &load_hosts_tab() if (!$loaded);
15374:         return %internetdom;
15375:     }
15376: 
15377:     sub is_library {
15378: 	&load_hosts_tab() if (!$loaded);
15379: 
15380: 	return exists($libserv{$_[0]});
15381:     }
15382: 
15383:     sub all_library {
15384: 	&load_hosts_tab() if (!$loaded);
15385: 
15386: 	return %libserv;
15387:     }
15388: 
15389:     sub unique_library {
15390: 	#2x reverse removes all hostnames that appear more than once
15391:         my %unique = reverse &all_library();
15392:         return reverse %unique;
15393:     }
15394: 
15395:     sub get_servers {
15396: 	&load_hosts_tab() if (!$loaded);
15397: 
15398: 	my ($domain,$type) = @_;
15399: 	my %possible_hosts = ($type eq 'library') ? %libserv
15400: 	                                          : %hostname;
15401: 	my %result;
15402: 	if (ref($domain) eq 'ARRAY') {
15403: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15404: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15405: 		    $result{$host} = $hostname;
15406: 		}
15407: 	    }
15408: 	} else {
15409: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15410: 		if ($hostdom{$host} eq $domain) {
15411: 		    $result{$host} = $hostname;
15412: 		}
15413: 	    }
15414: 	}
15415: 	return %result;
15416:     }
15417: 
15418:     sub get_unique_servers {
15419:         my %unique = reverse &get_servers(@_);
15420: 	return reverse %unique;
15421:     }
15422: 
15423:     sub host_domain {
15424: 	&load_hosts_tab() if (!$loaded);
15425: 
15426: 	my ($lonid) = @_;
15427: 	return $hostdom{$lonid};
15428:     }
15429: 
15430:     sub all_domains {
15431: 	&load_hosts_tab() if (!$loaded);
15432: 
15433: 	my %seen;
15434: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15435: 	return @uniq;
15436:     }
15437: 
15438:     sub internet_dom {
15439:         &load_hosts_tab() if (!$loaded);
15440: 
15441:         my ($lonid) = @_;
15442:         return $internetdom{$lonid};
15443:     }
15444: 
15445:     sub is_LC_dns {
15446:         &load_hosts_tab() if (!$loaded);
15447: 
15448:         my ($hostname) = @_;
15449:         return exists($LC_dns_serv{$hostname});
15450:     }
15451: 
15452: }
15453: 
15454: { 
15455:     my %iphost;
15456:     my %name_to_ip;
15457:     my %lonid_to_ip;
15458: 
15459:     sub get_hosts_from_ip {
15460: 	my ($ip) = @_;
15461: 	my %iphosts = &get_iphost();
15462: 	if (ref($iphosts{$ip})) {
15463: 	    return @{$iphosts{$ip}};
15464: 	}
15465: 	return;
15466:     }
15467:     
15468:     sub reset_hosts_ip_info {
15469: 	undef(%iphost);
15470: 	undef(%name_to_ip);
15471: 	undef(%lonid_to_ip);
15472:     }
15473: 
15474:     sub get_host_ip {
15475: 	my ($lonid) = @_;
15476: 	if (exists($lonid_to_ip{$lonid})) {
15477: 	    return $lonid_to_ip{$lonid};
15478: 	}
15479: 	my $name=&hostname($lonid);
15480:    	my $ip = gethostbyname($name);
15481: 	return if (!$ip || length($ip) ne 4);
15482: 	$ip=inet_ntoa($ip);
15483: 	$name_to_ip{$name}   = $ip;
15484: 	$lonid_to_ip{$lonid} = $ip;
15485: 	return $ip;
15486:     }
15487:     
15488:     sub get_iphost {
15489: 	my ($ignore_cache,$nocache) = @_;
15490: 
15491: 	if (!$ignore_cache) {
15492: 	    if (%iphost) {
15493: 		return %iphost;
15494: 	    }
15495: 	    my ($ip_info,$cached)=
15496: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15497: 	    if ($cached) {
15498: 		%iphost      = %{$ip_info->[0]};
15499: 		%name_to_ip  = %{$ip_info->[1]};
15500: 		%lonid_to_ip = %{$ip_info->[2]};
15501: 		return %iphost;
15502: 	    }
15503: 	}
15504: 
15505: 	# get yesterday's info for fallback
15506: 	my %old_name_to_ip;
15507: 	my ($ip_info,$cached)=
15508: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15509: 	if ($cached) {
15510: 	    %old_name_to_ip = %{$ip_info->[1]};
15511: 	}
15512: 
15513: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15514: 	foreach my $name (keys(%name_to_host)) {
15515: 	    my $ip;
15516: 	    if (!exists($name_to_ip{$name})) {
15517: 		$ip = gethostbyname($name);
15518: 		if (!$ip || length($ip) ne 4) {
15519: 		    if (defined($old_name_to_ip{$name})) {
15520: 			$ip = $old_name_to_ip{$name};
15521: 			&logthis("Can't find $name defaulting to old $ip");
15522: 		    } else {
15523: 			&logthis("Name $name no IP found");
15524: 			next;
15525: 		    }
15526: 		} else {
15527: 		    $ip=inet_ntoa($ip);
15528: 		}
15529: 		$name_to_ip{$name} = $ip;
15530: 	    } else {
15531: 		$ip = $name_to_ip{$name};
15532: 	    }
15533: 	    foreach my $id (@{ $name_to_host{$name} }) {
15534: 		$lonid_to_ip{$id} = $ip;
15535: 	    }
15536: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15537: 	}
15538:         unless ($nocache) {
15539: 	    &do_cache_new('iphost','iphost',
15540: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15541: 		          48*60*60);
15542:         }
15543: 
15544: 	return %iphost;
15545:     }
15546: 
15547:     #
15548:     #  Given a DNS returns the loncapa host name for that DNS 
15549:     # 
15550:     sub host_from_dns {
15551:         my ($dns) = @_;
15552:         my @hosts;
15553:         my $ip;
15554: 
15555:         if (exists($name_to_ip{$dns})) {
15556:             $ip = $name_to_ip{$dns};
15557:         }
15558:         if (!$ip) {
15559:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15560:             if (length($ip) == 4) { 
15561: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15562:             }
15563:         }
15564:         if ($ip) {
15565: 	    @hosts = get_hosts_from_ip($ip);
15566: 	    return $hosts[0];
15567:         }
15568:         return undef;
15569:     }
15570: 
15571:     sub get_internet_names {
15572:         my ($lonid) = @_;
15573:         return if ($lonid eq '');
15574:         my ($idnref,$cached)=
15575:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15576:         if ($cached) {
15577:             return $idnref;
15578:         }
15579:         my $ip = &get_host_ip($lonid);
15580:         my @hosts = &get_hosts_from_ip($ip);
15581:         my %iphost = &get_iphost();
15582:         my (@idns,%seen);
15583:         foreach my $id (@hosts) {
15584:             my $dom = &host_domain($id);
15585:             my $prim_id = &domain($dom,'primary');
15586:             my $prim_ip = &get_host_ip($prim_id);
15587:             next if ($seen{$prim_ip});
15588:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15589:                 foreach my $id (@{$iphost{$prim_ip}}) {
15590:                     my $intdom = &internet_dom($id);
15591:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15592:                         push(@idns,$intdom);
15593:                     }
15594:                 }
15595:             }
15596:             $seen{$prim_ip} = 1;
15597:         }
15598:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15599:     }
15600: 
15601: }
15602: 
15603: sub all_loncaparevs {
15604:     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);
15605: }
15606: 
15607: # ---------------------------------------------------------- Read loncaparev table
15608: {
15609:     sub load_loncaparevs { 
15610:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15611:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15612:                 while (my $configline=<$config>) {
15613:                     chomp($configline);
15614:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15615:                     $loncaparevs{$hostid}=$loncaparev;
15616:                 }
15617:                 close($config);
15618:             }
15619:         }
15620:     }
15621: }
15622: 
15623: # ---------------------------------------------------------- Read serverhostID table
15624: {
15625:     sub load_serverhomeIDs {
15626:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15627:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15628:                 while (my $configline=<$config>) {
15629:                     chomp($configline);
15630:                     my ($name,$id)=split(/:/,$configline);
15631:                     $serverhomeIDs{$name}=$id;
15632:                 }
15633:                 close($config);
15634:             }
15635:         }
15636:     }
15637: }
15638: 
15639: 
15640: BEGIN {
15641: 
15642: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15643:     unless ($readit) {
15644: {
15645:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15646:     %perlvar = (%perlvar,%{$configvars});
15647: }
15648: 
15649: 
15650: # ------------------------------------------------------ Read spare server file
15651: {
15652:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15653: 
15654:     while (my $configline=<$config>) {
15655:        chomp($configline);
15656:        if ($configline) {
15657: 	   my ($host,$type) = split(':',$configline,2);
15658: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15659: 	   push(@{ $spareid{$type} }, $host);
15660:        }
15661:     }
15662:     close($config);
15663: }
15664: # ------------------------------------------------------------ Read permissions
15665: {
15666:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15667: 
15668:     while (my $configline=<$config>) {
15669: 	chomp($configline);
15670: 	if ($configline) {
15671: 	    my ($role,$perm)=split(/ /,$configline);
15672: 	    if ($perm ne '') { $pr{$role}=$perm; }
15673: 	}
15674:     }
15675:     close($config);
15676: }
15677: 
15678: # -------------------------------------------- Read plain texts for permissions
15679: {
15680:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15681: 
15682:     while (my $configline=<$config>) {
15683: 	chomp($configline);
15684: 	if ($configline) {
15685: 	    my ($short,@plain)=split(/:/,$configline);
15686:             %{$prp{$short}} = ();
15687: 	    if (@plain > 0) {
15688:                 $prp{$short}{'std'} = $plain[0];
15689:                 for (my $i=1; $i<@plain; $i++) {
15690:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15691:                 }
15692:             }
15693: 	}
15694:     }
15695:     close($config);
15696: }
15697: 
15698: # ---------------------------------------------------------- Read package table
15699: {
15700:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15701: 
15702:     while (my $configline=<$config>) {
15703: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15704: 	chomp($configline);
15705: 	my ($short,$plain)=split(/:/,$configline);
15706: 	my ($pack,$name)=split(/\&/,$short);
15707: 	if ($plain ne '') {
15708: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15709: 	    $packagetab{$short}=$plain; 
15710: 	}
15711:     }
15712:     close($config);
15713: }
15714: 
15715: # ---------------------------------------------------------- Read loncaparev table
15716: 
15717: &load_loncaparevs();
15718: 
15719: # ---------------------------------------------------------- Read serverhostID table
15720: 
15721: &load_serverhomeIDs();
15722: 
15723: # ---------------------------------------------------------- Read releaseslist XML
15724: {
15725:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15726:     if (-e $file) {
15727:         my $parser = HTML::LCParser->new($file);
15728:         while (my $token = $parser->get_token()) {
15729:             if ($token->[0] eq 'S') {
15730:                 my $item = $token->[1];
15731:                 my $name = $token->[2]{'name'};
15732:                 my $value = $token->[2]{'value'};
15733:                 my $valuematch = $token->[2]{'valuematch'};
15734:                 my $namematch = $token->[2]{'namematch'};
15735:                 if ($item eq 'parameter') {
15736:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15737:                         my $release = $parser->get_text();
15738:                         $release =~ s/(^\s*|\s*$ )//gx;
15739:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15740:                     }
15741:                 } elsif ($item ne '' && $name ne '') {
15742:                     my $release = $parser->get_text();
15743:                     $release =~ s/(^\s*|\s*$ )//gx;
15744:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15745:                 }
15746:             }
15747:         }
15748:     }
15749: }
15750: 
15751: # ---------------------------------------------------------- Read managers table
15752: {
15753:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15754:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15755:             while (my $configline=<$config>) {
15756:                 chomp($configline);
15757:                 next if ($configline =~ /^\#/);
15758:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15759:                     $managerstab{$configline} = 1;
15760:                 }
15761:             }
15762:             close($config);
15763:         }
15764:     }
15765: }
15766: 
15767: # ------------- set up temporary directory
15768: {
15769:     $tmpdir = LONCAPA::tempdir();
15770: 
15771: }
15772: 
15773: # ------------- set default texengine (domain default overrides this)
15774: {
15775:     $deftex = LONCAPA::texengine();
15776: }
15777: 
15778: # ------------- set default minimum length for passwords for internal auth users
15779: {
15780:     $passwdmin = LONCAPA::passwd_min();
15781: }
15782: 
15783: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15784: 				'compress_threshold'=> 20_000,
15785:  			        });
15786: 
15787: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15788: $dumpcount=0;
15789: $locknum=0;
15790: 
15791: &logtouch();
15792: &logthis('<font color="yellow">INFO: Read configuration</font>');
15793: $readit=1;
15794:     {
15795: 	use integer;
15796: 	my $test=(2**32)+1;
15797: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15798: 	&logthis(" Detected 64bit platform ($_64bit)");
15799:     }
15800: }
15801: }
15802: 
15803: 1;
15804: __END__
15805: 
15806: =pod
15807: 
15808: =head1 NAME
15809: 
15810: Apache::lonnet - Subroutines to ask questions about things in the network.
15811: 
15812: =head1 SYNOPSIS
15813: 
15814: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15815: 
15816:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15817: 
15818: Common parameters:
15819: 
15820: =over 4
15821: 
15822: =item *
15823: 
15824: $uname : an internal username (if $cname expecting a course Id specifically)
15825: 
15826: =item *
15827: 
15828: $udom : a domain (if $cdom expecting a course's domain specifically)
15829: 
15830: =item *
15831: 
15832: $symb : a resource instance identifier
15833: 
15834: =item *
15835: 
15836: $namespace : the name of a .db file that contains the data needed or
15837: being set.
15838: 
15839: =back
15840: 
15841: =head1 OVERVIEW
15842: 
15843: lonnet provides subroutines which interact with the
15844: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15845: about classes, users, and resources.
15846: 
15847: For many of these objects you can also use this to store data about
15848: them or modify them in various ways.
15849: 
15850: =head2 Symbs
15851: 
15852: To identify a specific instance of a resource, LON-CAPA uses symbols
15853: or "symbs"X<symb>. These identifiers are built from the URL of the
15854: map, the resource number of the resource in the map, and the URL of
15855: the resource itself. The latter is somewhat redundant, but might help
15856: if maps change.
15857: 
15858: An example is
15859: 
15860:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15861: 
15862: The respective map entry is
15863: 
15864:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15865:   title="Problem 2">
15866:  </resource>
15867: 
15868: Symbs are used by the random number generator, as well as to store and
15869: restore data specific to a certain instance of for example a problem.
15870: 
15871: =head2 Storing And Retrieving Data
15872: 
15873: X<store()>X<cstore()>X<restore()>Three of the most important functions
15874: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15875: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15876: is is the non-critical message twin of cstore. These functions are for
15877: handlers to store a perl hash to a user's permanent data space in an
15878: easy manner, and to retrieve it again on another call. It is expected
15879: that a handler would use this once at the beginning to retrieve data,
15880: and then again once at the end to send only the new data back.
15881: 
15882: The data is stored in the user's data directory on the user's
15883: homeserver under the ID of the course.
15884: 
15885: The hash that is returned by restore will have all of the previous
15886: value for all of the elements of the hash.
15887: 
15888: Example:
15889: 
15890:  #creating a hash
15891:  my %hash;
15892:  $hash{'foo'}='bar';
15893: 
15894:  #storing it
15895:  &Apache::lonnet::cstore(\%hash);
15896: 
15897:  #changing a value
15898:  $hash{'foo'}='notbar';
15899: 
15900:  #adding a new value
15901:  $hash{'bar'}='foo';
15902:  &Apache::lonnet::cstore(\%hash);
15903: 
15904:  #retrieving the hash
15905:  my %history=&Apache::lonnet::restore();
15906: 
15907:  #print the hash
15908:  foreach my $key (sort(keys(%history))) {
15909:    print("\%history{$key} = $history{$key}");
15910:  }
15911: 
15912: Will print out:
15913: 
15914:  %history{1:foo} = bar
15915:  %history{1:keys} = foo:timestamp
15916:  %history{1:timestamp} = 990455579
15917:  %history{2:bar} = foo
15918:  %history{2:foo} = notbar
15919:  %history{2:keys} = foo:bar:timestamp
15920:  %history{2:timestamp} = 990455580
15921:  %history{bar} = foo
15922:  %history{foo} = notbar
15923:  %history{timestamp} = 990455580
15924:  %history{version} = 2
15925: 
15926: Note that the special hash entries C<keys>, C<version> and
15927: C<timestamp> were added to the hash. C<version> will be equal to the
15928: total number of versions of the data that have been stored. The
15929: C<timestamp> attribute will be the UNIX time the hash was
15930: stored. C<keys> is available in every historical section to list which
15931: keys were added or changed at a specific historical revision of a
15932: hash.
15933: 
15934: B<Warning>: do not store the hash that restore returns directly. This
15935: will cause a mess since it will restore the historical keys as if the
15936: were new keys. I.E. 1:foo will become 1:1:foo etc.
15937: 
15938: Calling convention:
15939: 
15940:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15941:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15942: 
15943: For more detailed information, see lonnet specific documentation.
15944: 
15945: =head1 RETURN MESSAGES
15946: 
15947: =over 4
15948: 
15949: =item * B<con_lost>: unable to contact remote host
15950: 
15951: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15952: when the connection is brought back up
15953: 
15954: =item * B<con_failed>: unable to contact remote host and unable to save message
15955: for later delivery
15956: 
15957: =item * B<error:>: an error a occurred, a description of the error follows the :
15958: 
15959: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15960: that was requested
15961: 
15962: =back
15963: 
15964: =head1 PUBLIC SUBROUTINES
15965: 
15966: =head2 Session Environment Functions
15967: 
15968: =over 4
15969: 
15970: =item * 
15971: X<appenv()>
15972: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15973: the user envirnoment file, and will be restored for each access this
15974: user makes during this session, also modifies the %env for the current
15975: process. Optional rolesarrayref - if defined contains a reference to an array
15976: of roles which are exempt from the restriction on modifying user.role entries 
15977: in the user's environment.db and in %env.    
15978: 
15979: =item *
15980: X<delenv()>
15981: B<delenv($delthis,$regexp)>: removes all items from the session
15982: environment file that begin with $delthis. If the 
15983: optional second arg - $regexp - is true, $delthis is treated as a 
15984: regular expression, otherwise \Q$delthis\E is used. 
15985: The values are also deleted from the current processes %env.
15986: 
15987: =item * get_env_multiple($name) 
15988: 
15989: gets $name from the %env hash, it seemlessly handles the cases where multiple
15990: values may be defined and end up as an array ref.
15991: 
15992: returns an array of values
15993: 
15994: =back
15995: 
15996: =head2 User Information
15997: 
15998: =over 4
15999: 
16000: =item *
16001: X<queryauthenticate()>
16002: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16003: authentication scheme
16004: 
16005: =item *
16006: X<authenticate()>
16007: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16008: authenticate user from domain's lib servers (first use the current
16009: one). C<$upass> should be the users password.
16010: $checkdefauth is optional (value is 1 if a check should be made to
16011:    authenticate user using default authentication method, and allow
16012:    account creation if username does not have account in the domain).
16013: $clientcancheckhost is optional (value is 1 if checking whether the
16014:    server can host will occur on the client side in lonauth.pm).   
16015: 
16016: =item *
16017: X<homeserver()>
16018: B<homeserver($uname,$udom)>: find the server which has
16019: the user's directory and files (there must be only one), this caches
16020: the answer, and also caches if there is a borken connection.
16021: 
16022: =item *
16023: X<idget()>
16024: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16025: a list of student/employee IDs or clicker IDs
16026: (student/employee IDs are a unique resource in a domain, there must be 
16027: only 1 ID per username, and only 1 username per ID in a specific domain).
16028: clickerIDs are not necessarily unique, as students might share clickers.
16029: (returns hash: id=>name,id=>name)
16030: 
16031: =item *
16032: X<idrget()>
16033: B<idrget($udom,@unames)>: find the IDs behind a list of
16034: usernames (returns hash: name=>id,name=>id)
16035: 
16036: =item *
16037: X<idput()>
16038: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16039: names and associated student/employee IDs or clicker IDs.
16040: 
16041: =item *
16042: X<iddel()>
16043: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16044: student/employee ID or clicker ID username look-ups from domain.
16045: The homeserver ($uhome) and namespace ($namespace) are optional.
16046: If no $uhome is provided, it will be determined usig &homeserver()
16047: for each user.  If no $namespace is provided, the default is ids.
16048: 
16049: =item *
16050: X<updateclickers()>
16051: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16052: clicker ID-to-username look-ups in clickers.db on library server.
16053: Permitted actions are add or del (i.e., add or delete). The 
16054: clickers.db contains clickerID as keys (escaped), and each corresponding
16055: value is an escaped comma-separated list of usernames (for whom the
16056: library server is the homeserver), who registered that particular ID.
16057: If $critical is true, the update will be sent via &critical, otherwise
16058: &reply() will be used.
16059: 
16060: =item *
16061: X<rolesinit()>
16062: B<rolesinit($udom,$username)>: get user privileges.
16063: returns user role, first access and timer interval hashes
16064: 
16065: =item *
16066: X<privileged()>
16067: B<privileged($username,$domain)>: returns a true if user has a
16068: privileged and active role (i.e. su or dc), false otherwise.
16069: 
16070: =item *
16071: X<getsection()>
16072: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16073: course $cname, return section name/number or '' for "not in course"
16074: and '-1' for "no section"
16075: 
16076: =item *
16077: X<userenvironment()>
16078: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16079: passed in @what from the requested user's environment, returns a hash
16080: 
16081: =item * 
16082: X<userlog_query()>
16083: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16084: activity.log file. %filters defines filters applied when parsing the
16085: log file. These can be start or end timestamps, or the type of action
16086: - log to look for Login or Logout events, check for Checkin or
16087: Checkout, role for role selection. The response is in the form
16088: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16089: escaped strings of the action recorded in the activity.log file.
16090: 
16091: =back
16092: 
16093: =head2 User Roles
16094: 
16095: =over 4
16096: 
16097: =item *
16098: 
16099: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16100: returns codes for allowed actions.
16101: 
16102: The first argument is required, all others are optional.
16103: 
16104: $priv is the privilege being checked.
16105: $uri contains additional information about what is being checked for access (e.g.,
16106: URL, course ID etc.). 
16107: $symb is the unique resource instance identifier in a course; if needed,
16108: but not provided, it will be retrieved via a call to &symbread(). 
16109: $role is the role for which a priv is being checked (only used if priv is evb). 
16110: $clientip is the user's IP address (only used when checking for access to portfolio 
16111: files).
16112: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16113: prevents recursive calls to &allowed.
16114: 
16115:  F: full access
16116:  U,I,K: authentication modes (cxx only)
16117:  '': forbidden
16118:  1: user needs to choose course
16119:  2: browse allowed
16120:  A: passphrase authentication needed
16121:  B: access temporarily blocked because of a blocking event in a course.
16122:  D: access blocked because access is required via session initiated via deep-link 
16123: 
16124: =item *
16125: 
16126: constructaccess($url,$setpriv) : check for access to construction space URL
16127: 
16128: See if the owner domain and name in the URL match those in the
16129: expected environment.  If so, return three element list
16130: ($ownername,$ownerdomain,$ownerhome).
16131: 
16132: Otherwise return the null string.
16133: 
16134: If second argument 'setpriv' is true, it assigns the privileges,
16135: and returns the same three element list, unless the owner has
16136: blocked "ad hoc" Domain Coordinator access to the Author Space,
16137: in which case the null string is returned.
16138: 
16139: =item *
16140: 
16141: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16142: define a custom role rolename set privileges in format of lonTabs/roles.tab
16143: for system, domain, and course level. $uname and $udom are optional (current
16144: user's username and domain will be used when either of $uname or $udom are absent.
16145: 
16146: =item *
16147: 
16148: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16149: (rolesplain.tab); plain text explanation of a user role term.
16150: $type is Course (default) or Community.
16151: If $forcedefault evaluates to true, text returned will be default 
16152: text for $type. Otherwise, if this is a course, the text returned 
16153: will be a custom name for the role (if defined in the course's 
16154: environment).  If no custom name is defined the default is returned.
16155:    
16156: =item *
16157: 
16158: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16159: All arguments are optional. Returns a hash of a roles, either for
16160: co-author/assistant author roles for a user's Construction Space
16161: (default), or if $context is 'userroles', roles for the user himself,
16162: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16163: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16164: For each key, value is set to colon-separated start and end times for
16165: the role.  If no username and domain are specified, will default to
16166: current user/domain. Types, roles, and roledoms are references to arrays
16167: of role statuses (active, future or previous), roles 
16168: (e.g., cc,in, st etc.) and domains of the roles which can be used
16169: to restrict the list of roles reported. If no array ref is 
16170: provided for types, will default to return only active roles.
16171: 
16172: =item *
16173: 
16174: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16175: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16176: 
16177: Additional optional arguments are: $type (if role checking is to be restricted 
16178: to certain user status types -- previous (expired roles), active (currently
16179: available roles) or future (roles available in the future), and
16180: $hideprivileged -- if true will not report course roles for users who
16181: have active Domain Coordinator role in course's domain or in additional
16182: domains (specified in 'Domains to check for privileged users' in course
16183: environment -- set via:  Course Settings -> Classlists and staff listing).
16184: 
16185: =item *
16186: 
16187: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16188: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16189: $possdomains and $possroles are optional array refs -- to domains to check and
16190: roles to check.  If $possdomains is not specified, a dump will be done of the
16191: users' roles.db to check for a dc or su role in any domain. This can be
16192: time consuming if &privileged is called repeatedly (e.g., when displaying a
16193: classlist), so in such cases, supplying a $possdomains array is preferred, as
16194: this then allows &privileged_by_domain() to be used, which caches the identity
16195: of privileged users, eliminating the need for repeated calls to &dump().
16196: 
16197: =item *
16198: 
16199: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16200: where the outer hash keys are domains specified in the $possdomains array ref,
16201: next inner hash keys are privileged roles specified in the $roles array ref,
16202: and the innermost hash contains key = value pairs for username:domain = end:start
16203: for active or future "privileged" users with that role in that domain. To avoid
16204: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16205: innerhash are cached using priv_$role and $dom as the identifiers.
16206: 
16207: =back
16208: 
16209: =head2 User Modification
16210: 
16211: =over 4
16212: 
16213: =item *
16214: 
16215: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16216: user for the level given by URL.  Optional start and end dates (leave empty
16217: string or zero for "no date")
16218: 
16219: =item *
16220: 
16221: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16222: change a users, password, possible return values are: ok,
16223: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16224: refused
16225: 
16226: =item *
16227: 
16228: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16229: 
16230: =item *
16231: 
16232: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16233:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16234: 
16235: will update user information (firstname,middlename,lastname,generation,
16236: permanentemail), and if forceid is true, student/employee ID also.
16237: A user's institutional affiliation(s) can also be updated.
16238: User information fields will not be overwritten with empty entries 
16239: unless the field is included in the $candelete array reference.
16240: This array is included when a single user is modified via "Manage Users",
16241: or when Autoupdate.pl is run by cron in a domain.
16242: 
16243: =item *
16244: 
16245: modifystudent
16246: 
16247: modify a student's enrollment and identification information.
16248: The course id is resolved based on the current user's environment.  
16249: This means the invoking user must be a course coordinator or otherwise
16250: associated with a course.
16251: 
16252: This call is essentially a wrapper for lonnet::modifyuser and
16253: lonnet::modify_student_enrollment
16254: 
16255: Inputs: 
16256: 
16257: =over 4
16258: 
16259: =item B<$udom> Student's loncapa domain
16260: 
16261: =item B<$uname> Student's loncapa login name
16262: 
16263: =item B<$uid> Student/Employee ID
16264: 
16265: =item B<$umode> Student's authentication mode
16266: 
16267: =item B<$upass> Student's password
16268: 
16269: =item B<$first> Student's first name
16270: 
16271: =item B<$middle> Student's middle name
16272: 
16273: =item B<$last> Student's last name
16274: 
16275: =item B<$gene> Student's generation
16276: 
16277: =item B<$usec> Student's section in course
16278: 
16279: =item B<$end> Unix time of the roles expiration
16280: 
16281: =item B<$start> Unix time of the roles start date
16282: 
16283: =item B<$forceid> If defined, allow $uid to be changed
16284: 
16285: =item B<$desiredhome> server to use as home server for student
16286: 
16287: =item B<$email> Student's permanent e-mail address
16288: 
16289: =item B<$type> Type of enrollment (auto or manual)
16290: 
16291: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16292: 
16293: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16294: 
16295: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16296: 
16297: =item B<$context> role change context (shown in User Management Logs display in a course)
16298: 
16299: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16300: 
16301: =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.
16302: 
16303: =back
16304: 
16305: =item *
16306: 
16307: modify_student_enrollment
16308: 
16309: Change a student's enrollment status in a class.  The environment variable
16310: 'role.request.course' must be defined for this function to proceed.
16311: 
16312: Inputs:
16313: 
16314: =over 4
16315: 
16316: =item $udom, student's domain
16317: 
16318: =item $uname, student's name
16319: 
16320: =item $uid, student's user id
16321: 
16322: =item $first, student's first name
16323: 
16324: =item $middle
16325: 
16326: =item $last
16327: 
16328: =item $gene
16329: 
16330: =item $usec
16331: 
16332: =item $end
16333: 
16334: =item $start
16335: 
16336: =item $type
16337: 
16338: =item $locktype
16339: 
16340: =item $cid
16341: 
16342: =item $selfenroll
16343: 
16344: =item $context
16345: 
16346: =item $credits, number of credits student will earn from this class
16347: 
16348: =item $instsec, institutional course section code for student
16349: 
16350: =back
16351: 
16352: 
16353: =item *
16354: 
16355: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16356: custom role; give a custom role to a user for the level given by URL.  Specify
16357: name and domain of role author, and role name
16358: 
16359: =item *
16360: 
16361: revokerole($udom,$uname,$url,$role) : revoke a role for url
16362: 
16363: =item *
16364: 
16365: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16366: 
16367: =back
16368: 
16369: =head2 Course Infomation
16370: 
16371: =over 4
16372: 
16373: =item *
16374: 
16375: coursedescription($courseid,$options) : returns a hash of information about the
16376: specified course id, including all environment settings for the
16377: course, the description of the course will be in the hash under the
16378: key 'description'
16379: 
16380: $options is an optional parameter that if supplied is a hash reference that controls
16381: what how this function works.  It has the following key/values:
16382: 
16383: =over 4
16384: 
16385: =item freshen_cache
16386: 
16387: If defined, and the environment cache for the course is valid, it is 
16388: returned in the returned hash.
16389: 
16390: =item one_time
16391: 
16392: If defined, the last cache time is set to _now_
16393: 
16394: =item user
16395: 
16396: If defined, the supplied username is used instead of the current user.
16397: 
16398: 
16399: =back
16400: 
16401: =item *
16402: 
16403: resdata($name,$domain,$type,@which) : request for current parameter
16404: setting for a specific $type, where $type is either 'course' or 'user',
16405: @what should be a list of parameters to ask about. This routine caches
16406: answers for 10 minutes.
16407: 
16408: =item *
16409: 
16410: get_courseresdata($courseid, $domain) : dump the entire course resource
16411: data base, returning a hash that is keyed by the resource name and has
16412: values that are the resource value.  I believe that the timestamps and
16413: versions are also returned.
16414: 
16415: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16416: supplemental content area. This routine caches the number of files for 
16417: 10 minutes.
16418: 
16419: =back
16420: 
16421: =head2 Course Modification
16422: 
16423: =over 4
16424: 
16425: =item *
16426: 
16427: writecoursepref($courseid,%prefs) : write preferences (environment
16428: database) for a course
16429: 
16430: =item *
16431: 
16432: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16433: 
16434: =item *
16435: 
16436: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16437: 
16438: =item *
16439: 
16440: is_course($courseid), is_course($cdom, $cnum)
16441: 
16442: Accepts either a combined $courseid (in the form of domain_courseid) or the
16443: two component version $cdom, $cnum. It checks if the specified course exists.
16444: 
16445: Returns:
16446:     undef if the course doesn't exist, otherwise
16447:     in scalar context the combined courseid.
16448:     in list context the two components of the course identifier, domain and 
16449:     courseid.    
16450: 
16451: =back
16452: 
16453: =head2 Bubblesheet Configuration
16454: 
16455: =over 4
16456: 
16457: =item *
16458: 
16459: get_scantron_config($which)
16460: 
16461: $which - the name of the configuration to parse from the file.
16462: 
16463: Parses and returns the bubblesheet configuration line selected as a
16464: hash of configuration file fields.
16465: 
16466: 
16467: Returns:
16468:     If the named configuration is not in the file, an empty
16469:     hash is returned.
16470: 
16471:     a hash with the fields
16472:       name         - internal name for the this configuration setup
16473:       description  - text to display to operator that describes this config
16474:       CODElocation - if 0 or the string 'none'
16475:                           - no CODE exists for this config
16476:                      if -1 || the string 'letter'
16477:                           - a CODE exists for this config and is
16478:                             a string of letters
16479:                      Unsupported value (but planned for future support)
16480:                           if a positive integer
16481:                                - The CODE exists as the first n items from
16482:                                  the question section of the form
16483:                           if the string 'number'
16484:                                - The CODE exists for this config and is
16485:                                  a string of numbers
16486:       CODEstart   - (only matter if a CODE exists) column in the line where
16487:                      the CODE starts
16488:       CODElength  - length of the CODE
16489:       IDstart     - column where the student/employee ID starts
16490:       IDlength    - length of the student/employee ID info
16491:       Qstart      - column where the information from the bubbled
16492:                     'questions' start
16493:       Qlength     - number of columns comprising a single bubble line from
16494:                     the sheet. (usually either 1 or 10)
16495:       Qon         - either a single character representing the character used
16496:                     to signal a bubble was chosen in the positional setup, or
16497:                     the string 'letter' if the letter of the chosen bubble is
16498:                     in the final, or 'number' if a number representing the
16499:                     chosen bubble is in the file (1->A 0->J)
16500:       Qoff        - the character used to represent that a bubble was
16501:                     left blank
16502:       PaperID     - if the scanning process generates a unique number for each
16503:                     sheet scanned the column that this ID number starts in
16504:       PaperIDlength - number of columns that comprise the unique ID number
16505:                       for the sheet of paper
16506:       FirstName   - column that the first name starts in
16507:       FirstNameLength - number of columns that the first name spans
16508:       LastName    - column that the last name starts in
16509:       LastNameLength - number of columns that the last name spans
16510:       BubblesPerRow - number of bubbles available in each row used to
16511:                       bubble an answer. (If not specified, 10 assumed).
16512: 
16513: 
16514: =item *
16515: 
16516: get_scantronformat_file($cdom)
16517: 
16518: $cdom - the course's domain (optional); if not supplied, uses
16519: domain for current $env{'request.course.id'}.
16520: 
16521: Returns an array containing lines from the scantron format file for
16522: the domain of the course.
16523: 
16524: If a url for a custom.tab file is listed in domain's configuration.db,
16525: lines are from this file.
16526: 
16527: Otherwise, if a default.tab has been published in RES space by the
16528: domainconfig user, lines are from this file.
16529: 
16530: Otherwise, fall back to getting lines from the legacy file on the
16531: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16532: 
16533: =back
16534: 
16535: =head2 Resource Subroutines
16536: 
16537: =over 4
16538: 
16539: =item *
16540: 
16541: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16542: 
16543: =item *
16544: 
16545: repcopy($filename) : subscribes to the requested file, and attempts to
16546: replicate from the owning library server, Might return
16547: 'unavailable', 'not_found', 'forbidden', 'ok', or
16548: 'bad_request', also attempts to grab the metadata for the
16549: resource. Expects the local filesystem pathname
16550: (/home/httpd/html/res/....)
16551: 
16552: =back
16553: 
16554: =head2 Resource Information
16555: 
16556: =over 4
16557: 
16558: =item *
16559: 
16560: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16561: and returns the value of a variety of different possible values,
16562: $varname should be a request string, and the other parameters can be
16563: used to specify who and what one is asking about. Ordinarily, $cid 
16564: does not need to be specified, as it is retrived from 
16565: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16566: within lonuserstate::loadmap() when initializing a course, before
16567: $env{'request.course.id'} has been set, so it needs to be provided
16568: in that one case.
16569: 
16570: Possible values for $varname are environment.lastname (or other item
16571: from the envirnment hash), user.name (or someother aspect about the
16572: user), resource.0.maxtries (or some other part and parameter of a
16573: resource)
16574: 
16575: =item *
16576: 
16577: directcondval($number) : get current value of a condition; reads from a state
16578: string
16579: 
16580: =item *
16581: 
16582: condval($condidx) : value of condition index based on state
16583: 
16584: =item *
16585: 
16586: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16587: resource's metadata, $what should be either a specific key, or either
16588: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16589: packages that this resource currently uses, the last 3 arguments are 
16590: only used internally for recursive metadata.
16591: 
16592: the toolsymb is only used where the uri is for an external tool (for which
16593: the uri as well as the symb are guaranteed to be unique).
16594: 
16595: this function automatically caches all requests except any made recursively
16596: to retrieve a list of metadata keys for an imported library file ($liburi is 
16597: defined).
16598: 
16599: =item *
16600: 
16601: metadata_query($query,$custom,$customshow) : make a metadata query against the
16602: network of library servers; returns file handle of where SQL and regex results
16603: will be stored for query
16604: 
16605: =item *
16606: 
16607: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16608: return symbolic list entry (all arguments optional). 
16609: 
16610: Args: filename is the filename (including path) for the file for which a symb 
16611: is required; donotrecurse, if true will prevent calls to allowed() being made 
16612: to check access status if more than one resource was found in the bighash 
16613: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16614: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16615: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16616: cause possible symbs to be checked to determine if they are subject to content
16617: blocking, if so they will not be included as possible symbs; possibles is a
16618: ref to a hash, which, as a side effect, will be populated with all possible 
16619: symbs (content blocking not tested).
16620:  
16621: returns the data handle
16622: 
16623: =item *
16624: 
16625: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16626: and is a possible symb for the URL in $thisfn, and if is an encrypted
16627: resource that the user accessed using /enc/ returns a 1 on success, 0
16628: on failure, user must be in a course, as it assumes the existence of
16629: the course initial hash, and uses $env('request.course.id'}.  The third
16630: arg is an optional reference to a scalar.  If this arg is passed in the 
16631: call to symbverify, it will be set to 1 if the symb has been set to be 
16632: encrypted; otherwise it will be null.  
16633: 
16634: =item *
16635: 
16636: symbclean($symb) : removes versions numbers from a symb, returns the
16637: cleaned symb
16638: 
16639: =item *
16640: 
16641: is_on_map($uri) : checks if the $uri is somewhere on the current
16642: course map, user must be in a course for it to work.
16643: 
16644: =item *
16645: 
16646: numval($salt) : return random seed value (addend for rndseed)
16647: 
16648: =item *
16649: 
16650: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16651: a random seed, all arguments are optional, if they aren't sent it uses the
16652: environment to derive them. Note: if symb isn't sent and it can't get one
16653: from &symbread it will use the current time as its return value
16654: 
16655: =item *
16656: 
16657: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16658: unfakeable, receipt
16659: 
16660: =item *
16661: 
16662: receipt() : API to ireceipt working off of env values; given out to users
16663: 
16664: =item *
16665: 
16666: countacc($url) : count the number of accesses to a given URL
16667: 
16668: =item *
16669: 
16670: 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
16671: 
16672: =item *
16673: 
16674: 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)
16675: 
16676: =item *
16677: 
16678: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16679: 
16680: =item *
16681: 
16682: devalidate($symb) : devalidate temporary spreadsheet calculations,
16683: forcing spreadsheet to reevaluate the resource scores next time.
16684: 
16685: =item * 
16686: 
16687: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16688: when viewing in course context.
16689: 
16690:  input: six args -- filename (decluttered), course number, course domain,
16691:                     url, symb (if registered) and group (if this is a 
16692:                     group item -- e.g., bulletin board, group page etc.).
16693: 
16694:  output: array of five scalars --
16695:          $cfile -- url for file editing if editable on current server
16696:          $home -- homeserver of resource (i.e., for author if published,
16697:                                           or course if uploaded.).
16698:          $switchserver --  1 if server switch will be needed.
16699:          $forceedit -- 1 if icon/link should be to go to edit mode 
16700:          $forceview -- 1 if icon/link should be to go to view mode
16701: 
16702: =item *
16703: 
16704: is_course_upload($file,$cnum,$cdom)
16705: 
16706: Used in course context to determine if current file was uploaded to 
16707: the course (i.e., would be found in /userfiles/docs on the course's 
16708: homeserver.
16709: 
16710:   input: 3 args -- filename (decluttered), course number and course domain.
16711:   output: boolean -- 1 if file was uploaded.
16712: 
16713: =back
16714: 
16715: =head2 Storing/Retreiving Data
16716: 
16717: =over 4
16718: 
16719: =item *
16720: 
16721: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16722: permanently for this url; hashref needs to be given and should be a \%hashname;
16723: the remaining args aren't required and if they aren't passed or are '' they will
16724: be derived from the env (with the exception of $laststore, which is an 
16725: optional arg used when a user's submission is stored in grading).
16726: $laststore is $version=$timestamp, where $version is the most recent version
16727: number retrieved for the corresponding $symb in the $namespace db file, and
16728: $timestamp is the timestamp for that transaction (UNIX time).
16729: $laststore is currently only passed when cstore() is called by 
16730: structuretags::finalize_storage().
16731: 
16732: =item *
16733: 
16734: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16735: but uses critical subroutine
16736: 
16737: =item *
16738: 
16739: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16740: all args are optional
16741: 
16742: =item *
16743: 
16744: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16745: dumps the complete (or key matching regexp) namespace into a hash
16746: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16747: normally &store()ed into
16748: 
16749: $range should be either an integer '100' (give me the first 100
16750:                                            matching records)
16751:               or be  two integers sperated by a - with no spaces
16752:                  '30-50' (give me the 30th through the 50th matching
16753:                           records)
16754: 
16755: 
16756: =item *
16757: 
16758: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16759: replaces a &store() version of data with a replacement set of data
16760: for a particular resource in a namespace passed in the $storehash hash 
16761: reference. If $tolog is true, the transaction is logged in the courselog
16762: with an action=PUTSTORE.
16763: 
16764: =item *
16765: 
16766: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16767: works very similar to store/cstore, but all data is stored in a
16768: temporary location and can be reset using tmpreset, $storehash should
16769: be a hash reference, returns nothing on success
16770: 
16771: =item *
16772: 
16773: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16774: similar to restore, but all data is stored in a temporary location and
16775: can be reset using tmpreset. Returns a hash of values on success,
16776: error string otherwise.
16777: 
16778: =item *
16779: 
16780: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16781: deltes all keys for $symb form the temporary storage hash.
16782: 
16783: =item *
16784: 
16785: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16786: reference filled in from namesp ($udom and $uname are optional)
16787: 
16788: =item *
16789: 
16790: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16791: namesp ($udom and $uname are optional)
16792: 
16793: =item *
16794: 
16795: dump($namespace,$udom,$uname,$regexp,$range) : 
16796: dumps the complete (or key matching regexp) namespace into a hash
16797: ($udom, $uname, $regexp, $range are optional)
16798: 
16799: $range should be either an integer '100' (give me the first 100
16800:                                            matching records)
16801:               or be  two integers sperated by a - with no spaces
16802:                  '30-50' (give me the 30th through the 50th matching
16803:                           records)
16804: =item *
16805: 
16806: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16807: $store can be a scalar, an array reference, or if the amount to be 
16808: incremented is > 1, a hash reference.
16809: 
16810: ($udom and $uname are optional)
16811: 
16812: =item *
16813: 
16814: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16815: ($udom and $uname are optional)
16816: 
16817: =item *
16818: 
16819: cput($namespace,$storehash,$udom,$uname) : critical put
16820: ($udom and $uname are optional)
16821: 
16822: =item *
16823: 
16824: newput($namespace,$storehash,$udom,$uname) :
16825: 
16826: Attempts to store the items in the $storehash, but only if they don't
16827: currently exist, if this succeeds you can be certain that you have 
16828: successfully created a new key value pair in the $namespace db.
16829: 
16830: 
16831: Args:
16832:  $namespace: name of database to store values to
16833:  $storehash: hashref to store to the db
16834:  $udom: (optional) domain of user containing the db
16835:  $uname: (optional) name of user caontaining the db
16836: 
16837: Returns:
16838:  'ok' -> succeeded in storing all keys of $storehash
16839:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16840:                         least <key> already existed in the db (other
16841:                         requested keys may also already exist)
16842:  'error: <msg>' -> unable to tie the DB or other error occurred
16843:  'con_lost' -> unable to contact request server
16844:  'refused' -> action was not allowed by remote machine
16845: 
16846: 
16847: =item *
16848: 
16849: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16850: reference filled in from namesp (encrypts the return communication)
16851: ($udom and $uname are optional)
16852: 
16853: =item *
16854: 
16855: log($udom,$name,$home,$message) : write to permanent log for user; use
16856: critical subroutine
16857: 
16858: =item *
16859: 
16860: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16861: array reference filled in from namespace found in domain level on either
16862: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16863: 
16864: =item *
16865: 
16866: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16867: domain level either on specified domain server ($uhome) or primary domain 
16868: server ($udom and $uhome are optional)
16869: 
16870: =item * 
16871: 
16872: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16873: for: authentication, language, quotas, timezone, date locale, and portal URL in
16874: the target domain.
16875: 
16876: May also include additional key => value pairs for the following groups:
16877: 
16878: =over
16879: 
16880: =item
16881: disk quotas (MB allocated by default to portfolios and authoring spaces).
16882: 
16883: =over
16884: 
16885: =item defaultquota, authorquota
16886: 
16887: =back
16888: 
16889: =item
16890: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16891: portfolio for users).
16892: 
16893: =over
16894: 
16895: =item
16896: aboutme, blog, webdav, portfolio
16897: 
16898: =back
16899: 
16900: =item
16901: requestcourses: ability to request courses, and how requests are processed.
16902: 
16903: =over
16904: 
16905: =item
16906: official, unofficial, community, textbook, placement
16907: 
16908: =back
16909: 
16910: =item
16911: inststatus: types of institutional affiliation, and order in which they are displayed.
16912: 
16913: =over
16914: 
16915: =item
16916: inststatustypes, inststatusorder, inststatusguest
16917: 
16918: =back
16919: 
16920: =item
16921: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16922: for course's uploaded content.
16923: 
16924: =over
16925: 
16926: =item
16927: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16928: communityquota, textbookquota, placementquota
16929: 
16930: =back
16931: 
16932: =item
16933: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16934: on your servers.
16935: 
16936: =over
16937: 
16938: =item 
16939: remotesessions, hostedsessions
16940: 
16941: =back
16942: 
16943: =back
16944: 
16945: In cases where a domain coordinator has never used the "Set Domain Configuration"
16946: utility to create a configuration.db file on a domain's primary library server 
16947: only the following domain defaults: auth_def, auth_arg_def, lang_def
16948: -- corresponding values are authentication type (internal, krb4, krb5,
16949: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16950: will be available. Values are retrieved from cache (if current), unless the
16951: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16952: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16953: 
16954: Typical usage:
16955: 
16956: %domdefaults = &get_domain_defaults($target_domain);
16957: 
16958: =back
16959: 
16960: =head2 Network Status Functions
16961: 
16962: =over 4
16963: 
16964: =item *
16965: 
16966: dirlist() : return directory list based on URI (first arg).
16967: 
16968: Inputs: 1 required, 5 optional.
16969: 
16970: =over
16971: 
16972: =item 
16973: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16974: 
16975: =item
16976: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16977: 
16978: =item
16979: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16980: 
16981: =item
16982: $getpropath - boolean: 1 if prepend path using &propath(). 
16983: 
16984: =item
16985: $getuserdir - boolean: 1 if prepend path for "userfiles".
16986: 
16987: =item 
16988: $alternateRoot - path to prepend in place of path from $uri.
16989: 
16990: =back
16991: 
16992: Returns: Array of up to two items.
16993: 
16994: =over
16995: 
16996: a reference to an array of files/subdirectories
16997: 
16998: =over
16999: 
17000: Each element in the array of files/subdirectories is a & separated list of
17001: item name and the result of running stat on the item.  If dirlist was requested
17002: for a file instead of a directory, the item name will be ''. For a directory 
17003: listing, if the item is a metadata file, the element will end &N&M 
17004: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17005: default copyright set (1).  
17006: 
17007: =back
17008: 
17009: a scalar containing error condition (if encountered).
17010: 
17011: =over
17012: 
17013: =item 
17014: no_host (no homeserver identified for $username:$domain).
17015: 
17016: =item 
17017: no_such_host (server contacted for listing not identified as valid host).
17018: 
17019: =item 
17020: con_lost (connection to remote server failed).
17021: 
17022: =item 
17023: refused (invalid $username:$domain received on lond side).
17024: 
17025: =item 
17026: no_such_dir (directory at specified path on lond side does not exist). 
17027: 
17028: =item 
17029: empty (directory at specified path on lond side is empty).
17030: 
17031: =over
17032: 
17033: This is currently not encountered because the &ls3, &ls2, 
17034: &ls (_handler) routines on the lond side do not filter out
17035: . and .. from a directory listing. 
17036: 
17037: =back
17038: 
17039: =back
17040: 
17041: =back
17042: 
17043: =item *
17044: 
17045: spareserver() : find server with least workload from spare.tab
17046: 
17047: 
17048: =item *
17049: 
17050: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17051: if there is no corresponding loncapa host.
17052: 
17053: =back
17054: 
17055: 
17056: =head2 Apache Request
17057: 
17058: =over 4
17059: 
17060: =item *
17061: 
17062: ssi($url,%hash) : server side include, does a complete request cycle on url to
17063: localhost, posts hash
17064: 
17065: =back
17066: 
17067: =head2 Data to String to Data
17068: 
17069: =over 4
17070: 
17071: =item *
17072: 
17073: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17074: and '&' separators, supports elements that are arrayrefs and hashrefs
17075: 
17076: =item *
17077: 
17078: hashref2str($hashref) : convert a hashref into a string complete with
17079: escaping and '=' and '&' separators, supports elements that are
17080: arrayrefs and hashrefs
17081: 
17082: =item *
17083: 
17084: arrayref2str($arrayref) : convert an arrayref into a string complete
17085: with escaping and '&' separators, supports elements that are arrayrefs
17086: and hashrefs
17087: 
17088: =item *
17089: 
17090: str2hash($string) : convert string to hash using unescaping and
17091: splitting on '=' and '&', supports elements that are arrayrefs and
17092: hashrefs
17093: 
17094: =item *
17095: 
17096: str2array($string) : convert string to hash using unescaping and
17097: splitting on '&', supports elements that are arrayrefs and hashrefs
17098: 
17099: =back
17100: 
17101: =head2 Logging Routines
17102: 
17103: 
17104: These routines allow one to make log messages in the lonnet.log and
17105: lonnet.perm logfiles.
17106: 
17107: =over 4
17108: 
17109: =item *
17110: 
17111: logtouch() : make sure the logfile, lonnet.log, exists
17112: 
17113: =item *
17114: 
17115: logthis() : append message to the normal lonnet.log file, it gets
17116: preiodically rolled over and deleted.
17117: 
17118: =item *
17119: 
17120: logperm() : append a permanent message to lonnet.perm.log, this log
17121: file never gets deleted by any automated portion of the system, only
17122: messages of critical importance should go in here.
17123: 
17124: 
17125: =back
17126: 
17127: =head2 General File Helper Routines
17128: 
17129: =over 4
17130: 
17131: =item *
17132: 
17133: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17134: (a) files in /uploaded
17135:   (i) If a local copy of the file exists - 
17136:       compares modification date of local copy with last-modified date for 
17137:       definitive version stored on home server for course. If local copy is 
17138:       stale, requests a new version from the home server and stores it. 
17139:       If the original has been removed from the home server, then local copy 
17140:       is unlinked.
17141:   (ii) If local copy does not exist -
17142:       requests the file from the home server and stores it. 
17143:   
17144:   If $caller is 'uploadrep':  
17145:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17146:     for request for files originally uploaded via DOCS. 
17147:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17148:   
17149:   Otherwise:
17150:      This indicates a call from the content generation phase of the request.
17151:      -  returns the entire contents of the file or -1.
17152:      
17153: (b) files in /res
17154:    - returns the entire contents of a file or -1; 
17155:    it properly subscribes to and replicates the file if neccessary.
17156: 
17157: 
17158: =item *
17159: 
17160: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17161:                   reference
17162: 
17163: returns either a stat() list of data about the file or an empty list
17164: if the file doesn't exist or couldn't find out about it (connection
17165: problems or user unknown)
17166: 
17167: =item *
17168: 
17169: filelocation($dir,$file) : returns file system location of a file
17170: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17171: directory that relative $file lookups are to looked in ($dir of /a/dir
17172: and a file of ../bob will become /a/bob)
17173: 
17174: =item *
17175: 
17176: hreflocation($dir,$file) : returns file system location or a URL; same as
17177: filelocation except for hrefs
17178: 
17179: =item *
17180: 
17181: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17182: also removes beginning /home/httpd/html unless /priv/ follows it.
17183: 
17184: =back
17185: 
17186: =head2 Usererfile file routines (/uploaded*)
17187: 
17188: =over 4
17189: 
17190: =item *
17191: 
17192: userfileupload(): main rotine for putting a file in a user or course's
17193:                   filespace, arguments are,
17194: 
17195:  formname - required - this is the name of the element in $env where the
17196:            filename, and the contents of the file to create/modifed exist
17197:            the filename is in $env{'form.'.$formname.'.filename'} and the
17198:            contents of the file is located in $env{'form.'.$formname}
17199:  context - if coursedoc, store the file in the course of the active role
17200:              of the current user; 
17201:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17202:            if 'canceloverwrite': delete file in tmp/overwrites directory
17203:  subdir - required - subdirectory to put the file in under ../userfiles/
17204:          if undefined, it will be placed in "unknown"
17205: 
17206:  (This routine calls clean_filename() to remove any dangerous
17207:  characters from the filename, and then calls finuserfileupload() to
17208:  complete the transaction)
17209: 
17210:  returns either the url of the uploaded file (/uploaded/....) if successful
17211:  and /adm/notfound.html if unsuccessful
17212: 
17213: =item *
17214: 
17215: clean_filename(): routine for cleaing a filename up for storage in
17216:                  userfile space, argument is:
17217: 
17218:  filename - proposed filename
17219: 
17220: returns: the new clean filename
17221: 
17222: =item *
17223: 
17224: finishuserfileupload(): routine that creates and sends the file to
17225: userspace, probably shouldn't be called directly
17226: 
17227:   docuname: username or courseid of destination for the file
17228:   docudom: domain of user/course of destination for the file
17229:   formname: same as for userfileupload()
17230:   fname: filename (including subdirectories) for the file
17231:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17232:           if hashref, and context is scantron, will convert csv format to standard format
17233:   allfiles: reference to hash used to store objects found by parser
17234:   codebase: reference to hash used for codebases of java objects found by parser
17235:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17236:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17237:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17238:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17239:   context: if 'overwrite', will move the uploaded file from its temporary location to
17240:             userfiles to facilitate overwriting a previously uploaded file with same name.
17241:   mimetype: reference to scalar to accommodate mime type determined
17242:             from File::MMagic if $parser = parse.
17243: 
17244:  returns either the url of the uploaded file (/uploaded/....) if successful
17245:  and /adm/notfound.html if unsuccessful (or an error message if context 
17246:  was 'overwrite').
17247:  
17248: 
17249: =item *
17250: 
17251: renameuserfile(): renames an existing userfile to a new name
17252: 
17253:   Args:
17254:    docuname: username or courseid of destination for the file
17255:    docudom: domain of user/course of destination for the file
17256:    old: current file name (including any subdirs under userfiles)
17257:    new: desired file name (including any subdirs under userfiles)
17258: 
17259: =item *
17260: 
17261: mkdiruserfile(): creates a directory is a userfiles dir
17262: 
17263:   Args:
17264:    docuname: username or courseid of destination for the file
17265:    docudom: domain of user/course of destination for the file
17266:    dir: dir to create (including any subdirs under userfiles)
17267: 
17268: =item *
17269: 
17270: removeuserfile(): removes a file that exists in userfiles
17271: 
17272:   Args:
17273:    docuname: username or courseid of destination for the file
17274:    docudom: domain of user/course of destination for the file
17275:    fname: filname to delete (including any subdirs under userfiles)
17276: 
17277: =item *
17278: 
17279: removeuploadedurl(): convience function for removeuserfile()
17280: 
17281:   Args:
17282:    url:  a full /uploaded/... url to delete
17283: 
17284: =item * 
17285: 
17286: get_portfile_permissions():
17287:   Args:
17288:     domain: domain of user or course contain the portfolio files
17289:     user: name of user or num of course contain the portfolio files
17290:   Returns:
17291:     hashref of a dump of the proper file_permissions.db
17292:    
17293: 
17294: =item * 
17295: 
17296: get_access_controls():
17297: 
17298: Args:
17299:   current_permissions: the hash ref returned from get_portfile_permissions()
17300:   group: (optional) the group you want the files associated with
17301:   file: (optional) the file you want access info on
17302: 
17303: Returns:
17304:     a hash (keys are file names) of hashes containing
17305:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17306:         values are XML containing access control settings (see below) 
17307: 
17308: Internal notes:
17309: 
17310:  access controls are stored in file_permissions.db as key=value pairs.
17311:     key -> path to file/file_name\0uniqueID:scope_end_start
17312:         where scope -> public,guest,course,group,domains or users.
17313:               end -> UNIX time for end of access (0 -> no end date)
17314:               start -> UNIX time for start of access
17315: 
17316:     value -> XML description of access control
17317:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17318:             <start></start>
17319:             <end></end>
17320: 
17321:             <password></password>  for scope type = guest
17322: 
17323:             <domain></domain>     for scope type = course or group
17324:             <number></number>
17325:             <roles id="">
17326:              <role></role>
17327:              <access></access>
17328:              <section></section>
17329:              <group></group>
17330:             </roles>
17331: 
17332:             <dom></dom>         for scope type = domains
17333: 
17334:             <users>             for scope type = users
17335:              <user>
17336:               <uname></uname>
17337:               <udom></udom>
17338:              </user>
17339:             </users>
17340:            </scope> 
17341:               
17342:  Access data is also aggregated for each file in an additional key=value pair:
17343:  key -> path to file/file_name\0accesscontrol 
17344:  value -> reference to hash
17345:           hash contains key = value pairs
17346:           where key = uniqueID:scope_end_start
17347:                 value = UNIX time record was last updated
17348: 
17349:           Used to improve speed of look-ups of access controls for each file.  
17350:  
17351:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17352: 
17353: =item *
17354: 
17355: modify_access_controls():
17356: 
17357: Modifies access controls for a portfolio file
17358: Args
17359: 1. file name
17360: 2. reference to hash of required changes,
17361: 3. domain
17362: 4. username
17363:   where domain,username are the domain of the portfolio owner 
17364:   (either a user or a course) 
17365: 
17366: Returns:
17367: 1. result of additions or updates ('ok' or 'error', with error message). 
17368: 2. result of deletions ('ok' or 'error', with error message).
17369: 3. reference to hash of any new or updated access controls.
17370: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17371:    key = integer (inbound ID)
17372:    value = uniqueID
17373: 
17374: =item *
17375: 
17376: get_timebased_id():
17377: 
17378: Attempts to get a unique timestamp-based suffix for use with items added to a 
17379: course via the Course Editor (e.g., folders, composite pages, 
17380: group bulletin boards).
17381: 
17382: Args: (first three required; six others optional)
17383: 
17384: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17385:    docssequence, or name of group
17386: 
17387: 2. keyid (alphanumeric): name of temporary locking key in hash,
17388:    e.g., num, boardids
17389: 
17390: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17391:    file will be named nohist_namespace.db
17392: 
17393: 4. cdom: domain of course; default is current course domain from %env
17394: 
17395: 5. cnum: course number; default is current course number from %env
17396: 
17397: 6. idtype: set to concat if an additional digit is to be appended to the 
17398:    unix timestamp to form the suffix, if the plain timestamp is already
17399:    in use.  Default is to not do this, but simply increment the unix 
17400:    timestamp by 1 until a unique key is obtained.
17401: 
17402: 7. who: holder of locking key; defaults to user:domain for user.
17403: 
17404: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17405:    retrying); default is 3.
17406: 
17407: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17408: 
17409: Returns:
17410: 
17411: 1. suffix obtained (numeric)
17412: 
17413: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17414: 
17415: 3. error: contains (localized) error message if an error occurred.
17416: 
17417: 
17418: =back
17419: 
17420: =head2 HTTP Helper Routines
17421: 
17422: =over 4
17423: 
17424: =item *
17425: 
17426: escape() : unpack non-word characters into CGI-compatible hex codes
17427: 
17428: =item *
17429: 
17430: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17431: 
17432: =back
17433: 
17434: =head1 PRIVATE SUBROUTINES
17435: 
17436: =head2 Underlying communication routines (Shouldn't call)
17437: 
17438: =over 4
17439: 
17440: =item *
17441: 
17442: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17443: 
17444: =item *
17445: 
17446: reply() : uses subreply to send a message to remote machine, logs all failures
17447: 
17448: =item *
17449: 
17450: critical() : passes a critical message to another server; if cannot
17451: get through then place message in connection buffer directory and
17452: returns con_delayed, if incapable of saving message, returns
17453: con_failed
17454: 
17455: =item *
17456: 
17457: reconlonc() : tries to reconnect lonc client processes.
17458: 
17459: =back
17460: 
17461: =head2 Resource Access Logging
17462: 
17463: =over 4
17464: 
17465: =item *
17466: 
17467: flushcourselogs() : flush (save) buffer logs and access logs
17468: 
17469: =item *
17470: 
17471: courselog($what) : save message for course in hash
17472: 
17473: =item *
17474: 
17475: courseacclog($what) : save message for course using &courselog().  Perform
17476: special processing for specific resource types (problems, exams, quizzes, etc).
17477: 
17478: =item *
17479: 
17480: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17481: as a PerlChildExitHandler
17482: 
17483: =back
17484: 
17485: =head2 Other
17486: 
17487: =over 4
17488: 
17489: =item *
17490: 
17491: symblist($mapname,%newhash) : update symbolic storage links
17492: 
17493: =back
17494: 
17495: =cut
17496: 

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