File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1488: download - view: text, annotated - select for diffs
Sat Jun 11 14:20:42 2022 UTC (2 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Always remove line feeds from lines returned by get_scantronformat_file()
  so chomp() no longer needs to be included when using the output.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1488 2022/06/11 14:20:42 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use Net::CIDR;
  100: use Sys::Hostname::FQDN();
  101: use LONCAPA qw(:DEFAULT :match);
  102: use LONCAPA::Configuration;
  103: use LONCAPA::lonmetadata;
  104: use LONCAPA::Lond;
  105: use LONCAPA::LWPReq;
  106: use LONCAPA::transliterate;
  107: 
  108: use File::Copy;
  109: 
  110: my $readit;
  111: my $max_connection_retries = 20;     # Or some such value.
  112: 
  113: require Exporter;
  114: 
  115: our @ISA = qw (Exporter);
  116: our @EXPORT = qw(%env);
  117: 
  118: 
  119: # ------------------------------------ Logging (parameters, docs, slots, roles)
  120: {
  121:     my $logid;
  122:     sub write_log {
  123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  124:         if ($context eq 'course') {
  125:             if (($cnum eq '') || ($cdom eq '')) {
  126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  128:             }
  129:         }
  130: 	$logid ++;
  131:         my $now = time();
  132: 	my $id=$now.'00000'.$$.'00000'.$logid;
  133:         my $ip = &get_requestor_ip();
  134:         my $logentry = { 
  135:                           $id => {
  136:                                    'exe_uname' => $env{'user.name'},
  137:                                    'exe_udom'  => $env{'user.domain'},
  138:                                    'exe_time'  => $now,
  139:                                    'exe_ip'    => $ip,
  140:                                    'delflag'   => $delflag,
  141:                                    'logentry'  => $storehash,
  142:                                    'uname'     => $uname,
  143:                                    'udom'      => $udom,
  144:                                   }
  145:                        };
  146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  147:     }
  148: }
  149: 
  150: sub logtouch {
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     unless (-e "$execdir/logs/lonnet.log") {	
  153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  154: 	close $fh;
  155:     }
  156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  158: }
  159: 
  160: sub logthis {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  167: 	print $fh $logstring;
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub logperm {
  174:     my $message=shift;
  175:     my $execdir=$perlvar{'lonDaemons'};
  176:     my $now=time;
  177:     my $local=localtime($now);
  178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  179: 	print $fh "$now:$message:$local\n";
  180: 	close($fh);
  181:     }
  182:     return 1;
  183: }
  184: 
  185: sub create_connection {
  186:     my ($hostname,$lonid) = @_;
  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  188: 				     Type    => SOCK_STREAM,
  189: 				     Timeout => 10);
  190:     return 0 if (!$client);
  191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  192:     my $result = <$client>;
  193:     chomp($result);
  194:     return 1 if ($result eq 'done');
  195:     return 0;
  196: }
  197: 
  198: sub get_server_timezone {
  199:     my ($cnum,$cdom) = @_;
  200:     my $home=&homeserver($cnum,$cdom);
  201:     if ($home ne 'no_host') {
  202:         my $cachetime = 24*3600;
  203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  204:         if (defined($cached)) {
  205:             return $timezone;
  206:         } else {
  207:             my $timezone = &reply('servertimezone',$home);
  208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  209:         }
  210:     }
  211: }
  212: 
  213: sub get_server_distarch {
  214:     my ($lonhost,$ignore_cache) = @_;
  215:     if (defined($lonhost)) {
  216:         if (!defined(&hostname($lonhost))) {
  217:             return;
  218:         }
  219:         my $cachetime = 12*3600;
  220:         if (!$ignore_cache) {
  221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  222:             if (defined($cached)) {
  223:                 return $distarch;
  224:             }
  225:         }
  226:         my $rep = &reply('serverdistarch',$lonhost);
  227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  229:                 $rep eq '') {
  230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  231:         }
  232:     }
  233:     return;
  234: }
  235: 
  236: sub get_servercerts_info {
  237:     my ($lonhost,$hostname,$context) = @_;
  238:     return if ($lonhost eq '');
  239:     if ($hostname eq '') {
  240:         $hostname = &hostname($lonhost);
  241:     }
  242:     return if ($hostname eq '');
  243:     my ($rep,$uselocal);
  244:     if ($context eq 'install') {
  245:         $uselocal = 1;
  246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  247:         $uselocal = 1;
  248:     }
  249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  251:         if ($distro eq '') {
  252:             $uselocal = 0;
  253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  254:             if ($1 < 6) {
  255:                 $uselocal = 0;
  256:             }
  257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  258:             if ($1 < 12) {
  259:                 $uselocal = 0;
  260:             }
  261:         }
  262:     }
  263:     if ($uselocal) {
  264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  265:     } else {
  266:         $rep=&reply('servercerts',$lonhost);
  267:     }
  268:     my ($result,%returnhash);
  269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  270:         ($rep eq 'unknown_cmd')) {
  271:         $result = $rep;
  272:     } else {
  273:         $result = 'ok';
  274:         my @pairs=split(/\&/,$rep);
  275:         foreach my $item (@pairs) {
  276:             my ($key,$value)=split(/=/,$item,2);
  277:             my $what = &unescape($key);
  278:             $returnhash{$what}=&thaw_unescape($value);
  279:         }
  280:     }
  281:     return ($result,\%returnhash);
  282: }
  283: 
  284: sub get_server_loncaparev {
  285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  286:     if (defined($lonhost)) {
  287:         if (!defined(&hostname($lonhost))) {
  288:             undef($lonhost);
  289:         }
  290:     }
  291:     if (!defined($lonhost)) {
  292:         if (defined(&domain($dom,'primary'))) {
  293:             $lonhost=&domain($dom,'primary');
  294:             if ($lonhost eq 'no_host') {
  295:                 undef($lonhost);
  296:             }
  297:         }
  298:     }
  299:     if (defined($lonhost)) {
  300:         my $cachetime = 12*3600;
  301:         if (!$ignore_cache) {
  302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  303:             if (defined($cached)) {
  304:                 return $loncaparev;
  305:             }
  306:         }
  307:         my ($answer,$loncaparev);
  308:         my @ids=&current_machine_ids();
  309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  310:             $answer = $perlvar{'lonVersion'};
  311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  312:                 $loncaparev = $1;
  313:             }
  314:         } else {
  315:             $answer = &reply('serverloncaparev',$lonhost);
  316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  317:                 if ($caller eq 'loncron') {
  318:                     my $hostname = &hostname($lonhost);
  319:                     my $protocol = $protocol{$lonhost};
  320:                     $protocol = 'http' if ($protocol ne 'https');
  321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  322:                     my $request=new HTTP::Request('GET',$url);
  323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  324:                     unless ($response->is_error()) {
  325:                         my $content = $response->content;
  326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  327:                             $loncaparev = $1;
  328:                         }
  329:                     }
  330:                 } else {
  331:                     $loncaparev = $loncaparevs{$lonhost};
  332:                 }
  333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  334:                 $loncaparev = $1;
  335:             }
  336:         }
  337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  338:     }
  339: }
  340: 
  341: sub get_server_homeID {
  342:     my ($hostname,$ignore_cache,$caller) = @_;
  343:     unless ($ignore_cache) {
  344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  345:         if (defined($cached)) {
  346:             return $serverhomeID;
  347:         }
  348:     }
  349:     my $cachetime = 12*3600;
  350:     my $serverhomeID;
  351:     if ($caller eq 'loncron') { 
  352:         my @machine_ids = &machine_ids($hostname);
  353:         foreach my $id (@machine_ids) {
  354:             my $response = &reply('serverhomeID',$id);
  355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  356:                 $serverhomeID = $response;
  357:                 last;
  358:             }
  359:         }
  360:         if ($serverhomeID eq '') {
  361:             $serverhomeID = $machine_ids[-1];
  362:         }
  363:     } else {
  364:         $serverhomeID = $serverhomeIDs{$hostname};
  365:     }
  366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  367: }
  368: 
  369: sub get_remote_globals {
  370:     my ($lonhost,$whathash,$ignore_cache) = @_;
  371:     my ($result,%returnhash,%whatneeded);
  372:     if (ref($whathash) eq 'HASH') {
  373:         foreach my $what (sort(keys(%{$whathash}))) {
  374:             my $hashid = $lonhost.'-'.$what;
  375:             my ($response,$cached);
  376:             unless ($ignore_cache) {
  377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  378:             }
  379:             if (defined($cached)) {
  380:                 $returnhash{$what} = $response;
  381:             } else {
  382:                 $whatneeded{$what} = 1;
  383:             }
  384:         }
  385:         if (keys(%whatneeded) == 0) {
  386:             $result = 'ok';
  387:         } else {
  388:             my $requested = &freeze_escape(\%whatneeded);
  389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  391:                 ($rep eq 'unknown_cmd')) {
  392:                 $result = $rep;
  393:             } else {
  394:                 $result = 'ok';
  395:                 my @pairs=split(/\&/,$rep);
  396:                 foreach my $item (@pairs) {
  397:                     my ($key,$value)=split(/=/,$item,2);
  398:                     my $what = &unescape($key);
  399:                     my $hashid = $lonhost.'-'.$what;
  400:                     $returnhash{$what}=&thaw_unescape($value);
  401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  402:                 }
  403:             }
  404:         }
  405:     }
  406:     return ($result,\%returnhash);
  407: }
  408: 
  409: sub remote_devalidate_cache {
  410:     my ($lonhost,$cachekeys) = @_;
  411:     my $items;
  412:     return unless (ref($cachekeys) eq 'ARRAY');
  413:     my $cachestr = join('&',@{$cachekeys});
  414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  415:     return $response;
  416: }
  417: 
  418: # -------------------------------------------------- Non-critical communication
  419: sub subreply {
  420:     my ($cmd,$server)=@_;
  421:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  422:     #
  423:     #  With loncnew process trimming, there's a timing hole between lonc server
  424:     #  process exit and the master server picking up the listen on the AF_UNIX
  425:     #  socket.  In that time interval, a lock file will exist:
  426: 
  427:     my $lockfile=$peerfile.".lock";
  428:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  429: 	sleep(0.1);
  430:     }
  431:     # At this point, either a loncnew parent is listening or an old lonc
  432:     # or loncnew child is listening so we can connect or everything's dead.
  433:     #
  434:     #   We'll give the connection a few tries before abandoning it.  If
  435:     #   connection is not possible, we'll con_lost back to the client.
  436:     #   
  437:     my $client;
  438:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  439: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  440: 				      Type    => SOCK_STREAM,
  441: 				      Timeout => 10);
  442: 	if ($client) {
  443: 	    last;		# Connected!
  444: 	} else {
  445: 	    &create_connection(&hostname($server),$server);
  446: 	}
  447:         sleep(0.1);	# Try again later if failed connection.
  448:     }
  449:     my $answer;
  450:     if ($client) {
  451: 	print $client "sethost:$server:$cmd\n";
  452: 	$answer=<$client>;
  453: 	if (!$answer) { $answer="con_lost"; }
  454: 	chomp($answer);
  455:     } else {
  456: 	$answer = 'con_lost';	# Failed connection.
  457:     }
  458:     return $answer;
  459: }
  460: 
  461: sub reply {
  462:     my ($cmd,$server)=@_;
  463:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  464:     my $answer=subreply($cmd,$server);
  465:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  466:         my $logged = $cmd;
  467:         if ($cmd =~ /^encrypt:([^:]+):/) {
  468:             my $subcmd = $1;
  469:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  470:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  471:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  472:                 ($subcmd eq 'put')) {
  473:                 (undef,undef,my @rest) = split(/:/,$cmd);
  474:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  475:                     splice(@rest,2,1,'Hidden');
  476:                 } elsif ($subcmd eq 'passwd') {
  477:                     splice(@rest,2,2,('Hidden','Hidden'));
  478:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  479:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  480:                     splice(@rest,3,1,'Hidden');
  481:                 }
  482:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  483:             }
  484:         }
  485:         &logthis("<font color=\"blue\">WARNING:".
  486:                  " $logged to $server returned $answer</font>");
  487:     }
  488:     return $answer;
  489: }
  490: 
  491: # ----------------------------------------------------------- Send USR1 to lonc
  492: 
  493: sub reconlonc {
  494:     my ($lonid) = @_;
  495:     if ($lonid) {
  496:         my $hostname = &hostname($lonid);
  497: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  498: 	if ($hostname && -e $peerfile) {
  499: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  500: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  501: 					     Type    => SOCK_STREAM,
  502: 					     Timeout => 10);
  503: 	    if ($client) {
  504: 		print $client ("reset_retries\n");
  505: 		my $answer=<$client>;
  506: 		#reset just this one.
  507: 	    }
  508: 	}
  509: 	return;
  510:     }
  511: 
  512:     &logthis("Trying to reconnect lonc");
  513:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  514:     if (open(my $fh,"<",$loncfile)) {
  515: 	my $loncpid=<$fh>;
  516:         chomp($loncpid);
  517:         if (kill 0 => $loncpid) {
  518: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  519:             kill USR1 => $loncpid;
  520:             sleep 1;
  521:         } else {
  522: 	    &logthis(
  523:                "<font color=\"blue\">WARNING:".
  524:                " lonc at pid $loncpid not responding, giving up</font>");
  525:         }
  526:     } else {
  527: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  528:     }
  529: }
  530: 
  531: # ------------------------------------------------------ Critical communication
  532: 
  533: sub critical {
  534:     my ($cmd,$server)=@_;
  535:     unless (&hostname($server)) {
  536:         &logthis("<font color=\"blue\">WARNING:".
  537:                " Critical message to unknown server ($server)</font>");
  538:         return 'no_such_host';
  539:     }
  540:     my $answer=reply($cmd,$server);
  541:     if ($answer eq 'con_lost') {
  542: 	&reconlonc($server);
  543: 	my $answer=reply($cmd,$server);
  544:         if ($answer eq 'con_lost') {
  545:             my $now=time;
  546:             my $middlename=$cmd;
  547:             $middlename=substr($middlename,0,16);
  548:             $middlename=~s/\W//g;
  549:             my $dfilename=
  550:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  551:             $dumpcount++;
  552:             {
  553: 		my $dfh;
  554: 		if (open($dfh,">",$dfilename)) {
  555: 		    print $dfh "$cmd\n"; 
  556: 		    close($dfh);
  557: 		}
  558:             }
  559:             sleep 1;
  560:             my $wcmd='';
  561:             {
  562: 		my $dfh;
  563: 		if (open($dfh,"<",$dfilename)) {
  564: 		    $wcmd=<$dfh>; 
  565: 		    close($dfh);
  566: 		}
  567:             }
  568:             chomp($wcmd);
  569:             if ($wcmd eq $cmd) {
  570: 		&logthis("<font color=\"blue\">WARNING: ".
  571:                          "Connection buffer $dfilename: $cmd</font>");
  572:                 &logperm("D:$server:$cmd");
  573: 	        return 'con_delayed';
  574:             } else {
  575:                 &logthis("<font color=\"red\">CRITICAL:"
  576:                         ." Critical connection failed: $server $cmd</font>");
  577:                 &logperm("F:$server:$cmd");
  578:                 return 'con_failed';
  579:             }
  580:         }
  581:     }
  582:     return $answer;
  583: }
  584: 
  585: # ------------------------------------------- check if return value is an error
  586: 
  587: sub error {
  588:     my ($result) = @_;
  589:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  590: 	if ($2 == 2) { return undef; }
  591: 	return $1;
  592:     }
  593:     return undef;
  594: }
  595: 
  596: sub convert_and_load_session_env {
  597:     my ($lonidsdir,$handle)=@_;
  598:     my @profile;
  599:     {
  600: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  601: 	if (!$opened) {
  602: 	    return 0;
  603: 	}
  604: 	flock($idf,LOCK_SH);
  605: 	@profile=<$idf>;
  606: 	close($idf);
  607:     }
  608:     my %temp_env;
  609:     foreach my $line (@profile) {
  610: 	if ($line !~ m/=/) {
  611: 	    return 0;
  612: 	}
  613: 	chomp($line);
  614: 	my ($envname,$envvalue)=split(/=/,$line,2);
  615: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  616:     }
  617:     unlink("$lonidsdir/$handle.id");
  618:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  619: 	    0640)) {
  620: 	%disk_env = %temp_env;
  621: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  622: 	untie(%disk_env);
  623:     }
  624:     return 1;
  625: }
  626: 
  627: # ------------------------------------------- Transfer profile into environment
  628: my $env_loaded;
  629: sub transfer_profile_to_env {
  630:     my ($lonidsdir,$handle,$force_transfer) = @_;
  631:     if (!$force_transfer && $env_loaded) { return; } 
  632: 
  633:     if (!defined($lonidsdir)) {
  634: 	$lonidsdir = $perlvar{'lonIDsDir'};
  635:     }
  636:     if (!defined($handle)) {
  637:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  638:     }
  639: 
  640:     my $convert;
  641:     {
  642:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  643: 	if (!$opened) {
  644: 	    return;
  645: 	}
  646: 	flock($idf,LOCK_SH);
  647: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  648: 		&GDBM_READER(),0640)) {
  649: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  650: 	    untie(%disk_env);
  651: 	} else {
  652: 	    $convert = 1;
  653: 	}
  654:     }
  655:     if ($convert) {
  656: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  657: 	    &logthis("Failed to load session, or convert session.");
  658: 	}
  659:     }
  660: 
  661:     my %remove;
  662:     while ( my $envname = each(%env) ) {
  663:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  664:             if ($time < time-300) {
  665:                 $remove{$key}++;
  666:             }
  667:         }
  668:     }
  669: 
  670:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  671:     $env_loaded=1;
  672:     foreach my $expired_key (keys(%remove)) {
  673:         &delenv($expired_key);
  674:     }
  675: }
  676: 
  677: # ---------------------------------------------------- Check for valid session 
  678: sub check_for_valid_session {
  679:     my ($r,$name,$userhashref,$domref) = @_;
  680:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  681:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  682:     if ($name eq 'lonDAV') {
  683:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  684:     } else {
  685:         $lonidsdir=$r->dir_config('lonIDsDir');
  686:         if ($name eq '') {
  687:             $name = 'lonID';
  688:         }
  689:     }
  690:     if ($name eq 'lonID') {
  691:         $secure = 'lonSID';
  692:         $linkname = 'lonLinkID';
  693:         $pubname = 'lonPubID';
  694:         if (exists($cookies{$secure})) {
  695:             $lonid=$cookies{$secure};
  696:         } elsif (exists($cookies{$name})) {
  697:             $lonid=$cookies{$name};
  698:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  699:             $lonid=$cookies{$linkname};
  700:         } elsif (exists($cookies{$pubname})) {
  701:             $lonid=$cookies{$pubname};
  702:         }
  703:     } else {
  704:         $lonid=$cookies{$name};
  705:     }
  706:     return undef if (!$lonid);
  707: 
  708:     my $handle=&LONCAPA::clean_handle($lonid->value);
  709:     if (-l "$lonidsdir/$handle.id") {
  710:         my $link = readlink("$lonidsdir/$handle.id");
  711:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  712:             $handle = $1;
  713:         }
  714:     }
  715:     if (!-e "$lonidsdir/$handle.id") {
  716:         if ((ref($domref)) && ($name eq 'lonID') && 
  717:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  718:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  719:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  720:                 $$domref = $possudom;
  721:             }
  722:         }
  723:         return undef;
  724:     }
  725: 
  726:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  727:     return undef if (!$opened);
  728: 
  729:     flock($idf,LOCK_SH);
  730:     my %disk_env;
  731:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  732: 	    &GDBM_READER(),0640)) {
  733: 	return undef;	
  734:     }
  735: 
  736:     if (!defined($disk_env{'user.name'})
  737: 	|| !defined($disk_env{'user.domain'})) {
  738:         untie(%disk_env);
  739: 	return undef;
  740:     }
  741: 
  742:     if (ref($userhashref) eq 'HASH') {
  743:         $userhashref->{'name'} = $disk_env{'user.name'};
  744:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  745:         if ($disk_env{'request.role'}) {
  746:             $userhashref->{'role'} = $disk_env{'request.role'};
  747:         }
  748:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  749:         if ($userhashref->{'lti'}) {
  750:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  751:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  752:         }
  753:     }
  754:     untie(%disk_env);
  755: 
  756:     return $handle;
  757: }
  758: 
  759: sub timed_flock {
  760:     my ($file,$lock_type) = @_;
  761:     my $failed=0;
  762:     eval {
  763: 	local $SIG{__DIE__}='DEFAULT';
  764: 	local $SIG{ALRM}=sub {
  765: 	    $failed=1;
  766: 	    die("failed lock");
  767: 	};
  768: 	alarm(13);
  769: 	flock($file,$lock_type);
  770: 	alarm(0);
  771:     };
  772:     if ($failed) {
  773: 	return undef;
  774:     } else {
  775: 	return 1;
  776:     }
  777: }
  778: 
  779: sub get_sessionfile_vars {
  780:     my ($handle,$lonidsdir,$storearr) = @_;
  781:     my %returnhash;
  782:     unless (ref($storearr) eq 'ARRAY') {
  783:         return %returnhash;
  784:     }
  785:     if (-l "$lonidsdir/$handle.id") {
  786:         my $link = readlink("$lonidsdir/$handle.id");
  787:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  788:             $handle = $1;
  789:         }
  790:     }
  791:     if ((-e "$lonidsdir/$handle.id") &&
  792:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  793:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  794:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  795:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  796:                 flock($idf,LOCK_SH);
  797:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  798:                         &GDBM_READER(),0640)) {
  799:                     foreach my $item (@{$storearr}) {
  800:                         $returnhash{$item} = $disk_env{$item};
  801:                     }
  802:                     untie(%disk_env);
  803:                 }
  804:             }
  805:         }
  806:     }
  807:     return %returnhash;
  808: }
  809: 
  810: # ---------------------------------------------------------- Append Environment
  811: 
  812: sub appenv {
  813:     my ($newenv,$roles) = @_;
  814:     if (ref($newenv) eq 'HASH') {
  815:         foreach my $key (keys(%{$newenv})) {
  816:             my $refused = 0;
  817: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  818:                 $refused = 1;
  819:                 if (ref($roles) eq 'ARRAY') {
  820:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  821:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  822:                         $refused = 0;
  823:                     }
  824:                 }
  825:             }
  826:             if ($refused) {
  827:                 &logthis("<font color=\"blue\">WARNING: ".
  828:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  829:                          .'</font>');
  830: 	        delete($newenv->{$key});
  831:             } else {
  832:                 $env{$key}=$newenv->{$key};
  833:             }
  834:         }
  835:         my $lonids = $perlvar{'lonIDsDir'};
  836:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  837:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  838:             if ($opened
  839: 	        && &timed_flock($env_file,LOCK_EX)
  840: 	        &&
  841: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  842: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  843: 	        while (my ($key,$value) = each(%{$newenv})) {
  844: 	            $disk_env{$key} = $value;
  845: 	        }
  846: 	        untie(%disk_env);
  847:             }
  848:         }
  849:     }
  850:     return 'ok';
  851: }
  852: # ----------------------------------------------------- Delete from Environment
  853: 
  854: sub delenv {
  855:     my ($delthis,$regexp,$roles) = @_;
  856:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  857:         my $refused = 1;
  858:         if (ref($roles) eq 'ARRAY') {
  859:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  860:             if (grep(/^\Q$role\E$/,@{$roles})) {
  861:                 $refused = 0;
  862:             }
  863:         }
  864:         if ($refused) {
  865:             &logthis("<font color=\"blue\">WARNING: ".
  866:                      "Attempt to delete from environment ".$delthis);
  867:             return 'error';
  868:         }
  869:     }
  870:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  871:     if ($opened
  872: 	&& &timed_flock($env_file,LOCK_EX)
  873: 	&&
  874: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  875: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  876: 	foreach my $key (keys(%disk_env)) {
  877: 	    if ($regexp) {
  878:                 if ($key=~/^$delthis/) {
  879:                     delete($env{$key});
  880:                     delete($disk_env{$key});
  881:                 } 
  882:             } else {
  883:                 if ($key=~/^\Q$delthis\E/) {
  884: 		    delete($env{$key});
  885: 		    delete($disk_env{$key});
  886: 	        }
  887:             }
  888: 	}
  889: 	untie(%disk_env);
  890:     }
  891:     return 'ok';
  892: }
  893: 
  894: sub get_env_multiple {
  895:     my ($name) = @_;
  896:     my @values;
  897:     if (defined($env{$name})) {
  898:         # exists is it an array
  899:         if (ref($env{$name})) {
  900:             @values=@{ $env{$name} };
  901:         } else {
  902:             $values[0]=$env{$name};
  903:         }
  904:     }
  905:     return(@values);
  906: }
  907: 
  908: # ------------------------------------------------------------------- Locking
  909: 
  910: sub set_lock {
  911:     my ($text)=@_;
  912:     $locknum++;
  913:     my $id=$$.'-'.$locknum;
  914:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  915:              'session.lock.'.$id => $text});
  916:     return $id;
  917: }
  918: 
  919: sub get_locks {
  920:     my $num=0;
  921:     my %texts=();
  922:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  923:        if ($lock=~/\w/) {
  924:           $num++;
  925:           $texts{$lock}=$env{'session.lock.'.$lock};
  926:        }
  927:    }
  928:    return ($num,%texts);
  929: }
  930: 
  931: sub remove_lock {
  932:     my ($id)=@_;
  933:     my $newlocks='';
  934:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  935:        if (($lock=~/\w/) && ($lock ne $id)) {
  936:           $newlocks.=','.$lock;
  937:        }
  938:     }
  939:     &appenv({'session.locks' => $newlocks});
  940:     &delenv('session.lock.'.$id);
  941: }
  942: 
  943: sub remove_all_locks {
  944:     my $activelocks=$env{'session.locks'};
  945:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  946:        if ($lock=~/\w/) {
  947:           &remove_lock($lock);
  948:        }
  949:     }
  950: }
  951: 
  952: 
  953: # ------------------------------------------ Find out current server userload
  954: sub userload {
  955:     my $numusers=0;
  956:     {
  957: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  958: 	my $filename;
  959: 	my $curtime=time;
  960: 	while ($filename=readdir(LONIDS)) {
  961: 	    next if ($filename eq '.' || $filename eq '..');
  962: 	    next if ($filename =~ /publicuser_\d+\.id/);
  963:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  964: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  965: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  966: 	}
  967: 	closedir(LONIDS);
  968:     }
  969:     my $userloadpercent=0;
  970:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  971:     if ($maxuserload) {
  972: 	$userloadpercent=100*$numusers/$maxuserload;
  973:     }
  974:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  975:     return $userloadpercent;
  976: }
  977: 
  978: # ------------------------------ Find server with least workload from spare.tab
  979: 
  980: sub spareserver {
  981:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  982:     my $spare_server;
  983:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  984:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  985:                                                      :  $userloadpercent;
  986:     my ($uint_dom,$remotesessions);
  987:     if (($udom ne '') && (&domain($udom) ne '')) {
  988:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  989:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  990:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  991:         $remotesessions = $udomdefaults{'remotesessions'};
  992:     }
  993:     my $spareshash = &this_host_spares($udom);
  994:     if (ref($spareshash) eq 'HASH') {
  995:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  996:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  997:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  998:                                              $try_server));
  999: 	        ($spare_server, $lowest_load) =
 1000: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1001:             }
 1002:         }
 1003: 
 1004:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1005: 
 1006:         if (!$found_server) {
 1007:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1008: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1009:                     next unless (&spare_can_host($udom,$uint_dom,
 1010:                                                  $remotesessions,$try_server));
 1011: 	            ($spare_server, $lowest_load) =
 1012: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1013:                 }
 1014: 	    }
 1015:         }
 1016:     }
 1017: 
 1018:     if (!$want_server_name) {
 1019:         if (defined($spare_server)) {
 1020:             my $hostname = &hostname($spare_server);
 1021:             if (defined($hostname)) {
 1022:                 my $protocol = 'http';
 1023:                 if ($protocol{$spare_server} eq 'https') {
 1024:                     $protocol = $protocol{$spare_server};
 1025:                 }
 1026:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
 1027:                 $hostname = $alias if ($alias ne '');
 1028: 	        $spare_server = $protocol.'://'.$hostname;
 1029:             }
 1030:         }
 1031:     }
 1032:     return $spare_server;
 1033: }
 1034: 
 1035: sub compare_server_load {
 1036:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1037: 
 1038:     if ($required) {
 1039:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1040:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1041:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1042:         if (($major eq '' && $minor eq '') ||
 1043:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1044:             return ($spare_server,$lowest_load);
 1045:         }
 1046:     }
 1047: 
 1048:     my $loadans     = &reply('load',    $try_server);
 1049:     my $userloadans = &reply('userload',$try_server);
 1050: 
 1051:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1052: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1053:     }
 1054: 
 1055:     my $load;
 1056:     if ($loadans =~ /\d/) {
 1057: 	if ($userloadans =~ /\d/) {
 1058: 	    #both are numbers, pick the bigger one
 1059: 	    $load = ($loadans > $userloadans) ? $loadans 
 1060: 		                              : $userloadans;
 1061: 	} else {
 1062: 	    $load = $loadans;
 1063: 	}
 1064:     } else {
 1065: 	$load = $userloadans;
 1066:     }
 1067: 
 1068:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1069: 	$spare_server = $try_server;
 1070: 	$lowest_load  = $load;
 1071:     }
 1072:     return ($spare_server,$lowest_load);
 1073: }
 1074: 
 1075: # --------------------------- ask offload servers if user already has a session
 1076: sub find_existing_session {
 1077:     my ($udom,$uname) = @_;
 1078:     my $spareshash = &this_host_spares($udom);
 1079:     if (ref($spareshash) eq 'HASH') {
 1080:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1081:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1082:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1083:             }
 1084:         }
 1085:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1086:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1087:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1088:             }
 1089:         }
 1090:     }
 1091:     return;
 1092: }
 1093: 
 1094: sub delusersession {
 1095:     my ($lonid,$udom,$uname) = @_;
 1096:     my $uprimary_id = &domain($udom,'primary');
 1097:     my $uintdom = &internet_dom($uprimary_id);
 1098:     my $intdom = &internet_dom($lonid);
 1099:     my $serverhomedom = &host_domain($lonid);
 1100:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1101:         return &reply(join(':','delusersession',
 1102:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1103:     }
 1104:     return;
 1105: }
 1106: 
 1107: # check if user's browser sent load balancer cookie and server still has session
 1108: # and is not overloaded.
 1109: sub check_for_balancer_cookie {
 1110:     my ($r,$update_mtime) = @_;
 1111:     my ($otherserver,$cookie);
 1112:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1113:     if (exists($cookies{'balanceID'})) {
 1114:         my $balid = $cookies{'balanceID'};
 1115:         $cookie=&LONCAPA::clean_handle($balid->value);
 1116:         my $balancedir=$r->dir_config('lonBalanceDir');
 1117:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1118:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1119:                 my ($possudom,$possuname) = ($1,$2);
 1120:                 my $has_session = 0;
 1121:                 if ((&domain($possudom) ne '') &&
 1122:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1123:                     my $try_server;
 1124:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1125:                     if ($opened) {
 1126:                         flock($idf,LOCK_SH);
 1127:                         while (my $line = <$idf>) {
 1128:                             chomp($line);
 1129:                             if (&hostname($line) ne '') {
 1130:                                 $try_server = $line;
 1131:                                 last;
 1132:                             }
 1133:                         }
 1134:                         close($idf);
 1135:                         if (($try_server) &&
 1136:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1137:                             my $lowest_load = 30000;
 1138:                             ($otherserver,$lowest_load) =
 1139:                                 &compare_server_load($try_server,undef,$lowest_load);
 1140:                             if ($otherserver ne '' && $lowest_load < 100) {
 1141:                                 $has_session = 1;
 1142:                             } else {
 1143:                                 undef($otherserver);
 1144:                             }
 1145:                         }
 1146:                     }
 1147:                 }
 1148:                 if ($has_session) {
 1149:                     if ($update_mtime) {
 1150:                         my $atime = my $mtime = time;
 1151:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1152:                     }
 1153:                 } else {
 1154:                     unlink("$balancedir/$cookie.id");
 1155:                 }
 1156:             }
 1157:         }
 1158:     }
 1159:     return ($otherserver,$cookie);
 1160: }
 1161: 
 1162: sub updatebalcookie {
 1163:     my ($cookie,$balancer,$lastentry)=@_;
 1164:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1165:         my ($udom,$uname) = ($1,$2);
 1166:         my $uprimary_id = &domain($udom,'primary');
 1167:         my $uintdom = &internet_dom($uprimary_id);
 1168:         my $intdom = &internet_dom($balancer);
 1169:         my $serverhomedom = &host_domain($balancer);
 1170:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1171:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1172:         }
 1173:     }
 1174:     return;
 1175: }
 1176: 
 1177: sub delbalcookie {
 1178:     my ($cookie,$balancer) =@_;
 1179:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1180:         my ($udom,$uname) = ($1,$2);
 1181:         my $uprimary_id = &domain($udom,'primary');
 1182:         my $uintdom = &internet_dom($uprimary_id);
 1183:         my $intdom = &internet_dom($balancer);
 1184:         my $serverhomedom = &host_domain($balancer);
 1185:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1186:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1187:         }
 1188:     }
 1189: }
 1190: 
 1191: # -------------------------------- ask if server already has a session for user
 1192: sub has_user_session {
 1193:     my ($lonid,$udom,$uname) = @_;
 1194:     my $result = &reply(join(':','userhassession',
 1195: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1196:     return 1 if ($result eq 'ok');
 1197: 
 1198:     return 0;
 1199: }
 1200: 
 1201: # --------- determine least loaded server in a user's domain which allows login
 1202: 
 1203: sub choose_server {
 1204:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1205:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1206:     my %servers = &get_servers($udom);
 1207:     my $lowest_load = 30000;
 1208:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1209:     if ($skiploadbal) {
 1210:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1211:         unless (defined($cached)) {
 1212:             my $cachetime = 60*60*24;
 1213:             my %domconfig =
 1214:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1215:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1216:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1217:                                            $cachetime);
 1218:             }
 1219:         }
 1220:     }
 1221:     foreach my $lonhost (keys(%servers)) {
 1222:         if ($skiploadbal) {
 1223:             if (ref($balancers) eq 'HASH') {
 1224:                 next if (exists($balancers->{$lonhost}));
 1225:             }
 1226:         }
 1227:         my $loginvia;
 1228:         if ($checkloginvia) {
 1229:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1230:             if ($loginvia) {
 1231:                 my ($server,$path) = split(/:/,$loginvia);
 1232:                 ($login_host, $lowest_load) =
 1233:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1234:                 if ($login_host eq $server) {
 1235:                     $portal_path = $path;
 1236:                     $isredirect = 1;
 1237:                 }
 1238:             } else {
 1239:                 ($login_host, $lowest_load) =
 1240:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1241:                 if ($login_host eq $lonhost) {
 1242:                     $portal_path = '';
 1243:                     $isredirect = ''; 
 1244:                 }
 1245:             }
 1246:         } else {
 1247:             ($login_host, $lowest_load) =
 1248:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1249:         }
 1250:     }
 1251:     if ($login_host ne '') {
 1252:         $hostname = &hostname($login_host);
 1253:     }
 1254:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1255: }
 1256: 
 1257: sub get_course_sessions {
 1258:     my ($cnum,$cdom,$lastactivity) = @_;
 1259:     my %servers = &internet_dom_servers($cdom);
 1260:     my %returnhash;
 1261:     foreach my $server (sort(keys(%servers))) {
 1262:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1263:         my @pairs=split(/\&/,$rep);
 1264:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1265:             foreach my $item (@pairs) {
 1266:                 my ($key,$value)=split(/=/,$item,2);
 1267:                 $key = &unescape($key);
 1268:                 next if ($key =~ /^error: 2 /);
 1269:                 if (exists($returnhash{$key})) {
 1270:                     next if ($value < $returnhash{$key});
 1271:                 }
 1272:                 $returnhash{$key}=$value;
 1273:             }
 1274:         }
 1275:     }
 1276:     return %returnhash;
 1277: }
 1278: 
 1279: # --------------------------------------------- Try to change a user's password
 1280: 
 1281: sub changepass {
 1282:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1283:     $currentpass = &escape($currentpass);
 1284:     $newpass     = &escape($newpass);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1287: 		       $server);
 1288:     if (! $answer) {
 1289: 	&logthis("No reply on password change request to $server ".
 1290: 		 "by $uname in domain $udom.");
 1291:     } elsif ($answer =~ "^ok") {
 1292:         &logthis("$uname in $udom successfully changed their password ".
 1293: 		 "on $server.");
 1294:     } elsif ($answer =~ "^pwchange_failure") {
 1295: 	&logthis("$uname in $udom was unable to change their password ".
 1296: 		 "on $server.  The action was blocked by either lcpasswd ".
 1297: 		 "or pwchange");
 1298:     } elsif ($answer =~ "^non_authorized") {
 1299:         &logthis("$uname in $udom did not get their password correct when ".
 1300: 		 "attempting to change it on $server.");
 1301:     } elsif ($answer =~ "^auth_mode_error") {
 1302:         &logthis("$uname in $udom attempted to change their password despite ".
 1303: 		 "not being locally or internally authenticated on $server.");
 1304:     } elsif ($answer =~ "^unknown_user") {
 1305:         &logthis("$uname in $udom attempted to change their password ".
 1306: 		 "on $server but were unable to because $server is not ".
 1307: 		 "their home server.");
 1308:     } elsif ($answer =~ "^refused") {
 1309: 	&logthis("$server refused to change $uname in $udom password because ".
 1310: 		 "it was sent an unencrypted request to change the password.");
 1311:     } elsif ($answer =~ "invalid_client") {
 1312:         &logthis("$server refused to change $uname in $udom password because ".
 1313:                  "it was a reset by e-mail originating from an invalid server.");
 1314:     } elsif ($answer =~ "^prioruse") {
 1315:        &logthis("$server refused to change $uname in $udom password because ".
 1316:                 "the password had been used before");
 1317:     }
 1318:     return $answer;
 1319: }
 1320: 
 1321: # ----------------------- Try to determine user's current authentication scheme
 1322: 
 1323: sub queryauthenticate {
 1324:     my ($uname,$udom)=@_;
 1325:     my $uhome=&homeserver($uname,$udom);
 1326:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1327: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1328: 	return 'no_host';
 1329:     }
 1330:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1331:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1332: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1333:     }
 1334:     return $answer;
 1335: }
 1336: 
 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
 1338: 
 1339: sub authenticate {
 1340:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1341:     $upass=&escape($upass);
 1342:     $uname= &LONCAPA::clean_username($uname);
 1343:     my $uhome=&homeserver($uname,$udom,1);
 1344:     my $newhome;
 1345:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1346: # Maybe the machine was offline and only re-appeared again recently?
 1347:         &reconlonc();
 1348: # One more
 1349: 	$uhome=&homeserver($uname,$udom,1);
 1350:         if (($uhome eq 'no_host') && $checkdefauth) {
 1351:             if (defined(&domain($udom,'primary'))) {
 1352:                 $newhome=&domain($udom,'primary');
 1353:             }
 1354:             if ($newhome ne '') {
 1355:                 $uhome = $newhome;
 1356:             }
 1357:         }
 1358: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1359: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1360: 	    return 'no_host';
 1361:         }
 1362:     }
 1363:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1364:     if ($answer eq 'authorized') {
 1365:         if ($newhome) {
 1366:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1367:             return 'no_account_on_host'; 
 1368:         } else {
 1369:             &logthis("User $uname at $udom authorized by $uhome");
 1370:             return $uhome;
 1371:         }
 1372:     }
 1373:     if ($answer eq 'non_authorized') {
 1374: 	&logthis("User $uname at $udom rejected by $uhome");
 1375: 	return 'no_host';
 1376:     }
 1377:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1378:     return 'no_host';
 1379: }
 1380: 
 1381: sub can_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:                 } elsif ($item eq 'unamemap') {
 2597:                     $response=&unescape(&reply('instunamemapcheck:'.
 2598:                                                &escape($udom).':'.&escape($uname).
 2599:                                               ':'.$rulestr,$homeserver));
 2600:                 }
 2601:                 if ($response ne 'refused') {
 2602:                     my @pairs=split(/\&/,$response);
 2603:                     foreach my $item (@pairs) {
 2604:                         my ($key,$value)=split(/=/,$item,2);
 2605:                         $key = &unescape($key);
 2606:                         next if ($key =~ /^error: 2 /);
 2607:                         $returnhash{$key}=&thaw_unescape($value);
 2608:                     }
 2609:                 }
 2610:             }
 2611:         }
 2612:     }
 2613:     return %returnhash;
 2614: }
 2615: 
 2616: sub inst_userrules {
 2617:     my ($udom,$check) = @_;
 2618:     my (%ruleshash,@ruleorder);
 2619:     if ($udom ne '') {
 2620:         my $homeserver=&domain($udom,'primary');
 2621:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2622:             my $response;
 2623:             if ($check eq 'id') {
 2624:                 $response=&reply('instidrules:'.&escape($udom),
 2625:                                  $homeserver);
 2626:             } elsif ($check eq 'email') {
 2627:                 $response=&reply('instemailrules:'.&escape($udom),
 2628:                                  $homeserver);
 2629:             } elsif ($check eq 'unamemap') {
 2630:                 $response=&reply('unamemaprules:'.&escape($udom),
 2631:                                  $homeserver); 
 2632:             } else {
 2633:                 $response=&reply('instuserrules:'.&escape($udom),
 2634:                                  $homeserver);
 2635:             }
 2636:             if (($response ne 'refused') && ($response ne 'error') && 
 2637:                 ($response ne 'unknown_cmd') && 
 2638:                 ($response ne 'no_such_host')) {
 2639:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2640:                 my @pairs=split(/\&/,$hashitems);
 2641:                 foreach my $item (@pairs) {
 2642:                     my ($key,$value)=split(/=/,$item,2);
 2643:                     $key = &unescape($key);
 2644:                     next if ($key =~ /^error: 2 /);
 2645:                     $ruleshash{$key}=&thaw_unescape($value);
 2646:                 }
 2647:                 my @esc_order = split(/\&/,$orderitems);
 2648:                 foreach my $item (@esc_order) {
 2649:                     push(@ruleorder,&unescape($item));
 2650:                 }
 2651:             }
 2652:         }
 2653:     }
 2654:     return (\%ruleshash,\@ruleorder);
 2655: }
 2656: 
 2657: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2658: 
 2659: sub get_domain_defaults {
 2660:     my ($domain,$ignore_cache) = @_;
 2661:     return if (($domain eq '') || ($domain eq 'public'));
 2662:     my $cachetime = 60*60*24;
 2663:     unless ($ignore_cache) {
 2664:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2665:         if (defined($cached)) {
 2666:             if (ref($result) eq 'HASH') {
 2667:                 return %{$result};
 2668:             }
 2669:         }
 2670:     }
 2671:     my %domdefaults;
 2672:     my %domconfig =
 2673:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2674:                                   'requestcourses','inststatus',
 2675:                                   'coursedefaults','usersessions',
 2676:                                   'requestauthor','selfenrollment',
 2677:                                   'coursecategories','ssl','autoenroll',
 2678:                                   'trust','helpsettings','wafproxy','ltisec'],$domain);
 2679:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2680:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2681:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2682:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2683:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2684:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2685:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2686:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2687:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2688:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2689:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2690:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2691:     } else {
 2692:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2693:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2694:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2695:     }
 2696:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2697:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2698:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2699:         } else {
 2700:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2701:         }
 2702:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2703:         foreach my $item (@usertools) {
 2704:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2705:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2706:             }
 2707:         }
 2708:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2709:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2710:         }
 2711:     }
 2712:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2713:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2714:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2715:         }
 2716:     }
 2717:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2718:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2719:     }
 2720:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2721:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2722:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2723:         }
 2724:     }
 2725:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2726:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2727:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2728:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2729:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2730:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2731:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2732:         }
 2733:         foreach my $type (@coursetypes) {
 2734:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2735:                 unless ($type eq 'community') {
 2736:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2737:                 }
 2738:             }
 2739:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2740:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2741:             }
 2742:             if ($domdefaults{'postsubmit'} eq 'on') {
 2743:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2744:                     $domdefaults{$type.'postsubtimeout'} = 
 2745:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2746:                 }
 2747:             }
 2748:         }
 2749:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2750:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2751:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2752:                 if (@clonecodes) {
 2753:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2754:                 }
 2755:             }
 2756:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2757:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2758:         }
 2759:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2760:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2761:         }
 2762:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2763:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2764:         }
 2765:     }
 2766:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2767:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2768:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2769:         }
 2770:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2771:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2772:         }
 2773:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2774:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2775:         }
 2776:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2777:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2778:         }
 2779:     }
 2780:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2781:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2782:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2783:                             'approval','limit');
 2784:             foreach my $type (@coursetypes) {
 2785:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2786:                     my @mgrdc = ();
 2787:                     foreach my $item (@settings) {
 2788:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2789:                             push(@mgrdc,$item);
 2790:                         }
 2791:                     }
 2792:                     if (@mgrdc) {
 2793:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2794:                     }
 2795:                 }
 2796:             }
 2797:         }
 2798:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2799:             foreach my $type (@coursetypes) {
 2800:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2801:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2802:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2803:                     }
 2804:                 }
 2805:             }
 2806:         }
 2807:     }
 2808:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2809:         $domdefaults{'catauth'} = 'std';
 2810:         $domdefaults{'catunauth'} = 'std';
 2811:         if ($domconfig{'coursecategories'}{'auth'}) {
 2812:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2813:         }
 2814:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2815:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2816:         }
 2817:     }
 2818:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2819:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2820:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2821:         }
 2822:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2823:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2824:         }
 2825:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2826:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2827:         }
 2828:     }
 2829:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2830:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2831:         foreach my $prefix (@prefixes) {
 2832:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2833:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2834:             }
 2835:         }
 2836:     }
 2837:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2838:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2839:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2840:     }
 2841:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2842:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2843:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2844:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2845:         }
 2846:     }
 2847:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2848:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2849:             if ($domconfig{'wafproxy'}{$item}) {
 2850:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2851:             }
 2852:         }
 2853:     }
 2854:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2855:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2856:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2857:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2858:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2859:         }
 2860:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2861:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2862:                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2863:             }
 2864:         }
 2865:     }
 2866:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2867:     return %domdefaults;
 2868: }
 2869: 
 2870: sub get_dom_cats {
 2871:     my ($dom) = @_;
 2872:     return unless (&domain($dom));
 2873:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2874:     unless (defined($cached)) {
 2875:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2876:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2877:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2878:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2879:             } else {
 2880:                 $cats = {};
 2881:             }
 2882:         } else {
 2883:             $cats = {};
 2884:         }
 2885:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2886:     }
 2887:     return $cats;
 2888: }
 2889: 
 2890: sub get_dom_instcats {
 2891:     my ($dom) = @_;
 2892:     return unless (&domain($dom));
 2893:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2894:     unless (defined($cached)) {
 2895:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2896:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2897:         if ($totcodes > 0) {
 2898:             my $caller = 'global';
 2899:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2900:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2901:                 $instcats = {
 2902:                                 codes => \%codes,
 2903:                                 codetitles => \@codetitles,
 2904:                                 cat_titles => \%cat_titles,
 2905:                                 cat_order => \%cat_order,
 2906:                             };
 2907:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2908:             }
 2909:         }
 2910:     }
 2911:     return $instcats;
 2912: }
 2913: 
 2914: sub retrieve_instcodes {
 2915:     my ($coursecodes,$dom) = @_;
 2916:     my $totcodes;
 2917:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2918:     foreach my $course (keys(%courses)) {
 2919:         if (ref($courses{$course}) eq 'HASH') {
 2920:             if ($courses{$course}{'inst_code'} ne '') {
 2921:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2922:                 $totcodes ++;
 2923:             }
 2924:         }
 2925:     }
 2926:     return $totcodes;
 2927: }
 2928: 
 2929: sub course_portal_url {
 2930:     my ($cnum,$cdom,$r) = @_;
 2931:     my $chome = &homeserver($cnum,$cdom);
 2932:     my $hostname = &hostname($chome);
 2933:     my $protocol = $protocol{$chome};
 2934:     $protocol = 'http' if ($protocol ne 'https');
 2935:     my %domdefaults = &get_domain_defaults($cdom);
 2936:     my $firsturl;
 2937:     if ($domdefaults{'portal_def'}) {
 2938:         $firsturl = $domdefaults{'portal_def'};
 2939:     } else {
 2940:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
 2941:         $hostname = $alias if ($alias ne '');
 2942:         $firsturl = $protocol.'://'.$hostname;
 2943:     }
 2944:     return $firsturl;
 2945: }
 2946: 
 2947: # --------------------------------------------- Get domain config for passwords
 2948: 
 2949: sub get_passwdconf {
 2950:     my ($dom) = @_;
 2951:     my (%passwdconf,$gotconf,$lookup);
 2952:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2953:     if (defined($cached)) {
 2954:         if (ref($result) eq 'HASH') {
 2955:             %passwdconf = %{$result};
 2956:             $gotconf = 1;
 2957:         }
 2958:     }
 2959:     unless ($gotconf) {
 2960:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2961:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2962:             %passwdconf = %{$domconfig{'passwords'}};
 2963:         }
 2964:         my $cachetime = 24*60*60;
 2965:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2966:     }
 2967:     return %passwdconf;
 2968: }
 2969: 
 2970: # --------------------------------------------------- Assign a key to a student
 2971: 
 2972: sub assign_access_key {
 2973: #
 2974: # a valid key looks like uname:udom#comments
 2975: # comments are being appended
 2976: #
 2977:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2978:     $kdom=
 2979:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2980:     $knum=
 2981:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2982:     $cdom=
 2983:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2984:     $cnum=
 2985:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2986:     $udom=$env{'user.name'} unless (defined($udom));
 2987:     $uname=$env{'user.domain'} unless (defined($uname));
 2988:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2989:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2990:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2991:                                                   # assigned to this person
 2992:                                                   # - this should not happen,
 2993:                                                   # unless something went wrong
 2994:                                                   # the first time around
 2995: # ready to assign
 2996:         $logentry=$1.'; '.$logentry;
 2997:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2998:                                                  $kdom,$knum) eq 'ok') {
 2999: # key now belongs to user
 3000: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3001:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3002:                 &appenv({'environment.'.$envkey => $ckey});
 3003:                 return 'ok';
 3004:             } else {
 3005:                 return 
 3006:   'error: Count not permanently assign key, will need to be re-entered later.';
 3007: 	    }
 3008:         } else {
 3009:             return 'error: Could not assign key, try again later.';
 3010:         }
 3011:     } elsif (!$existing{$ckey}) {
 3012: # the key does not exist
 3013: 	return 'error: The key does not exist';
 3014:     } else {
 3015: # the key is somebody else's
 3016: 	return 'error: The key is already in use';
 3017:     }
 3018: }
 3019: 
 3020: # ------------------------------------------ put an additional comment on a key
 3021: 
 3022: sub comment_access_key {
 3023: #
 3024: # a valid key looks like uname:udom#comments
 3025: # comments are being appended
 3026: #
 3027:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3028:     $cdom=
 3029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3030:     $cnum=
 3031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3032:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3033:     if ($existing{$ckey}) {
 3034:         $existing{$ckey}.='; '.$logentry;
 3035: # ready to assign
 3036:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3037:                                                  $cdom,$cnum) eq 'ok') {
 3038: 	    return 'ok';
 3039:         } else {
 3040: 	    return 'error: Count not store comment.';
 3041:         }
 3042:     } else {
 3043: # the key does not exist
 3044: 	return 'error: The key does not exist';
 3045:     }
 3046: }
 3047: 
 3048: # ------------------------------------------------------ Generate a set of keys
 3049: 
 3050: sub generate_access_keys {
 3051:     my ($number,$cdom,$cnum,$logentry)=@_;
 3052:     $cdom=
 3053:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3054:     $cnum=
 3055:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3056:     unless (&allowed('mky',$cdom)) { return 0; }
 3057:     unless (($cdom) && ($cnum)) { return 0; }
 3058:     if ($number>10000) { return 0; }
 3059:     sleep(2); # make sure don't get same seed twice
 3060:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3061:     my $total=0;
 3062:     for (my $i=1;$i<=$number;$i++) {
 3063:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3064:                   sprintf("%lx",int(100000*rand)).'-'.
 3065:                   sprintf("%lx",int(100000*rand));
 3066:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3067:        $newkey=~s/0/h/g; # and also 0 and O
 3068:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3069:        if ($existing{$newkey}) {
 3070:            $i--;
 3071:        } else {
 3072: 	  if (&put('accesskeys',
 3073:               { $newkey => '# generated '.localtime().
 3074:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3075:                            '; '.$logentry },
 3076: 		   $cdom,$cnum) eq 'ok') {
 3077:               $total++;
 3078: 	  }
 3079:        }
 3080:     }
 3081:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3082:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3083:     return $total;
 3084: }
 3085: 
 3086: # ------------------------------------------------------- Validate an accesskey
 3087: 
 3088: sub validate_access_key {
 3089:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3090:     $cdom=
 3091:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3092:     $cnum=
 3093:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3094:     $udom=$env{'user.domain'} unless (defined($udom));
 3095:     $uname=$env{'user.name'} unless (defined($uname));
 3096:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3097:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3098: }
 3099: 
 3100: # ------------------------------------- Find the section of student in a course
 3101: sub devalidate_getsection_cache {
 3102:     my ($udom,$unam,$courseid)=@_;
 3103:     my $hashid="$udom:$unam:$courseid";
 3104:     &devalidate_cache_new('getsection',$hashid);
 3105: }
 3106: 
 3107: sub courseid_to_courseurl {
 3108:     my ($courseid) = @_;
 3109:     #already url style courseid
 3110:     return $courseid if ($courseid =~ m{^/});
 3111: 
 3112:     if (exists($env{'course.'.$courseid.'.num'})) {
 3113: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3114: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3115: 	return "/$cdom/$cnum";
 3116:     }
 3117: 
 3118:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3119:     if (exists($courseinfo{'num'})) {
 3120: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3121:     }
 3122: 
 3123:     return undef;
 3124: }
 3125: 
 3126: sub getsection {
 3127:     my ($udom,$unam,$courseid)=@_;
 3128:     my $cachetime=1800;
 3129: 
 3130:     my $hashid="$udom:$unam:$courseid";
 3131:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3132:     if (defined($cached)) { return $result; }
 3133: 
 3134:     my %Pending; 
 3135:     my %Expired;
 3136:     #
 3137:     # Each role can either have not started yet (pending), be active, 
 3138:     #    or have expired.
 3139:     #
 3140:     # If there is an active role, we are done.
 3141:     #
 3142:     # If there is more than one role which has not started yet, 
 3143:     #     choose the one which will start sooner
 3144:     # If there is one role which has not started yet, return it.
 3145:     #
 3146:     # If there is more than one expired role, choose the one which ended last.
 3147:     # If there is a role which has expired, return it.
 3148:     #
 3149:     $courseid = &courseid_to_courseurl($courseid);
 3150:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3151:     foreach my $key (keys(%roleshash)) {
 3152:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3153:         my $section=$1;
 3154:         if ($key eq $courseid.'_st') { $section=''; }
 3155:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3156:         my $now=time;
 3157:         if (defined($end) && $end && ($now > $end)) {
 3158:             $Expired{$end}=$section;
 3159:             next;
 3160:         }
 3161:         if (defined($start) && $start && ($now < $start)) {
 3162:             $Pending{$start}=$section;
 3163:             next;
 3164:         }
 3165:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3166:     }
 3167:     #
 3168:     # Presumedly there will be few matching roles from the above
 3169:     # loop and the sorting time will be negligible.
 3170:     if (scalar(keys(%Pending))) {
 3171:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3172:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3173:     } 
 3174:     if (scalar(keys(%Expired))) {
 3175:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3176:         my $time = pop(@sorted);
 3177:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3178:     }
 3179:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3180: }
 3181: 
 3182: sub save_cache {
 3183:     &purge_remembered();
 3184:     #&Apache::loncommon::validate_page();
 3185:     undef(%env);
 3186:     undef($env_loaded);
 3187: }
 3188: 
 3189: my $to_remember=-1;
 3190: my %remembered;
 3191: my %accessed;
 3192: my $kicks=0;
 3193: my $hits=0;
 3194: sub make_key {
 3195:     my ($name,$id) = @_;
 3196:     if (length($id) > 65 
 3197: 	&& length(&escape($id)) > 200) {
 3198: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3199:     }
 3200:     return &escape($name.':'.$id);
 3201: }
 3202: 
 3203: sub devalidate_cache_new {
 3204:     my ($name,$id,$debug) = @_;
 3205:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3206:     my $remembered_id=$name.':'.$id;
 3207:     $id=&make_key($name,$id);
 3208:     $memcache->delete($id);
 3209:     delete($remembered{$remembered_id});
 3210:     delete($accessed{$remembered_id});
 3211: }
 3212: 
 3213: sub is_cached_new {
 3214:     my ($name,$id,$debug) = @_;
 3215:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3216:     if (exists($remembered{$remembered_id})) {
 3217: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3218: 	$accessed{$remembered_id}=[&gettimeofday()];
 3219: 	$hits++;
 3220: 	return ($remembered{$remembered_id},1);
 3221:     }
 3222:     $id=&make_key($name,$id);
 3223:     my $value = $memcache->get($id);
 3224:     if (!(defined($value))) {
 3225: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3226: 	return (undef,undef);
 3227:     }
 3228:     if ($value eq '__undef__') {
 3229: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3230: 	$value=undef;
 3231:     }
 3232:     &make_room($remembered_id,$value,$debug);
 3233:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3234:     return ($value,1);
 3235: }
 3236: 
 3237: sub do_cache_new {
 3238:     my ($name,$id,$value,$time,$debug) = @_;
 3239:     my $remembered_id=$name.':'.$id;
 3240:     $id=&make_key($name,$id);
 3241:     my $setvalue=$value;
 3242:     if (!defined($setvalue)) {
 3243: 	$setvalue='__undef__';
 3244:     }
 3245:     if (!defined($time) ) {
 3246: 	$time=600;
 3247:     }
 3248:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3249:     my $result = $memcache->set($id,$setvalue,$time);
 3250:     if (! $result) {
 3251: 	&logthis("caching of id -> $id  failed");
 3252: 	$memcache->disconnect_all();
 3253:     }
 3254:     # need to make a copy of $value
 3255:     &make_room($remembered_id,$value,$debug);
 3256:     return $value;
 3257: }
 3258: 
 3259: sub make_room {
 3260:     my ($remembered_id,$value,$debug)=@_;
 3261: 
 3262:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3263:                                     : $value;
 3264:     if ($to_remember<0) { return; }
 3265:     $accessed{$remembered_id}=[&gettimeofday()];
 3266:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3267:     my $to_kick;
 3268:     my $max_time=0;
 3269:     foreach my $other (keys(%accessed)) {
 3270: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3271: 	    $to_kick=$other;
 3272: 	    $max_time=&tv_interval($accessed{$other});
 3273: 	}
 3274:     }
 3275:     delete($remembered{$to_kick});
 3276:     delete($accessed{$to_kick});
 3277:     $kicks++;
 3278:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3279:     return;
 3280: }
 3281: 
 3282: sub purge_remembered {
 3283:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3284:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3285:     undef(%remembered);
 3286:     undef(%accessed);
 3287: }
 3288: # ------------------------------------- Read an entry from a user's environment
 3289: 
 3290: sub userenvironment {
 3291:     my ($udom,$unam,@what)=@_;
 3292:     my $items;
 3293:     foreach my $item (@what) {
 3294:         $items.=&escape($item).'&';
 3295:     }
 3296:     $items=~s/\&$//;
 3297:     my %returnhash=();
 3298:     my $uhome = &homeserver($unam,$udom);
 3299:     unless ($uhome eq 'no_host') {
 3300:         my @answer=split(/\&/, 
 3301:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3302:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3303:             return %returnhash;
 3304:         }
 3305:         my $i;
 3306:         for ($i=0;$i<=$#what;$i++) {
 3307: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3308:         }
 3309:     }
 3310:     return %returnhash;
 3311: }
 3312: 
 3313: # ---------------------------------------------------------- Get a studentphoto
 3314: sub studentphoto {
 3315:     my ($udom,$unam,$ext) = @_;
 3316:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3317:     if (defined($env{'request.course.id'})) {
 3318:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3319:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3320:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3321:             } else {
 3322:                 my ($result,$perm_reqd)=
 3323: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3324:                 if ($result eq 'ok') {
 3325:                     if (!($perm_reqd eq 'yes')) {
 3326:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3327:                     }
 3328:                 }
 3329:             }
 3330:         }
 3331:     } else {
 3332:         my ($result,$perm_reqd) = 
 3333: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3334:         if ($result eq 'ok') {
 3335:             if (!($perm_reqd eq 'yes')) {
 3336:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3337:             }
 3338:         }
 3339:     }
 3340:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3341: }
 3342: 
 3343: sub retrievestudentphoto {
 3344:     my ($udom,$unam,$ext,$type) = @_;
 3345:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3346:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3347:     if ($ret eq 'ok') {
 3348:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3349:         if ($type eq 'thumbnail') {
 3350:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3351:         }
 3352:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3353:         return $tokenurl;
 3354:     } else {
 3355:         if ($type eq 'thumbnail') {
 3356:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3357:         } else { 
 3358:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3359:         }
 3360:     }
 3361: }
 3362: 
 3363: # -------------------------------------------------------------------- New chat
 3364: 
 3365: sub chatsend {
 3366:     my ($newentry,$anon,$group)=@_;
 3367:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3368:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3369:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3370:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3371: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3372: 		   &escape($newentry)).':'.$group,$chome);
 3373: }
 3374: 
 3375: # ------------------------------------------ Find current version of a resource
 3376: 
 3377: sub getversion {
 3378:     my $fname=&clutter(shift);
 3379:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3380:     return &currentversion(&filelocation('',$fname));
 3381: }
 3382: 
 3383: sub currentversion {
 3384:     my $fname=shift;
 3385:     my $author=$fname;
 3386:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3387:     my ($udom,$uname)=split(/\//,$author);
 3388:     my $home=&homeserver($uname,$udom);
 3389:     if ($home eq 'no_host') { 
 3390:         return -1; 
 3391:     }
 3392:     my $answer=&reply("currentversion:$fname",$home);
 3393:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3394: 	return -1;
 3395:     }
 3396:     return $answer;
 3397: }
 3398: 
 3399: #
 3400: # Return special version number of resource if set by override, empty otherwise
 3401: #
 3402: sub usedversion {
 3403:     my $fname=shift;
 3404:     unless ($fname) { $fname=$env{'request.uri'}; }
 3405:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3406:     if ($urlversion) { return $urlversion; }
 3407:     return '';
 3408: }
 3409: 
 3410: # ----------------------------- Subscribe to a resource, return URL if possible
 3411: 
 3412: sub subscribe {
 3413:     my $fname=shift;
 3414:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3415:     $fname=~s/[\n\r]//g;
 3416:     my $author=$fname;
 3417:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3418:     my ($udom,$uname)=split(/\//,$author);
 3419:     my $home=homeserver($uname,$udom);
 3420:     if ($home eq 'no_host') {
 3421:         return 'not_found';
 3422:     }
 3423:     my $answer=reply("sub:$fname",$home);
 3424:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3425: 	$answer.=' by '.$home;
 3426:     }
 3427:     return $answer;
 3428: }
 3429:     
 3430: # -------------------------------------------------------------- Replicate file
 3431: 
 3432: sub repcopy {
 3433:     my $filename=shift;
 3434:     $filename=~s/\/+/\//g;
 3435:     my $londocroot = $perlvar{'lonDocRoot'};
 3436:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3437:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3438:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3439: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3440: 	return &repcopy_userfile($filename);
 3441:     }
 3442:     $filename=~s/[\n\r]//g;
 3443:     my $transname="$filename.in.transfer";
 3444: # FIXME: this should flock
 3445:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3446:     my $remoteurl=subscribe($filename);
 3447:     if ($remoteurl =~ /^con_lost by/) {
 3448: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3449:            return 'unavailable';
 3450:     } elsif ($remoteurl eq 'not_found') {
 3451: 	   #&logthis("Subscribe returned not_found: $filename");
 3452: 	   return 'not_found';
 3453:     } elsif ($remoteurl =~ /^rejected by/) {
 3454: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3455:            return 'forbidden';
 3456:     } elsif ($remoteurl eq 'directory') {
 3457:            return 'ok';
 3458:     } else {
 3459:         my $author=$filename;
 3460:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3461:         my ($udom,$uname)=split(/\//,$author);
 3462:         my $home=homeserver($uname,$udom);
 3463:         unless ($home eq $perlvar{'lonHostID'}) {
 3464:            my @parts=split(/\//,$filename);
 3465:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3466:            if ($path ne "$londocroot/res") {
 3467:                &logthis("Malconfiguration for replication: $filename");
 3468: 	       return 'bad_request';
 3469:            }
 3470:            my $count;
 3471:            for ($count=5;$count<$#parts;$count++) {
 3472:                $path.="/$parts[$count]";
 3473:                if ((-e $path)!=1) {
 3474: 		   mkdir($path,0777);
 3475:                }
 3476:            }
 3477:            my $request=new HTTP::Request('GET',"$remoteurl");
 3478:            my $response;
 3479:            if ($remoteurl =~ m{/raw/}) {
 3480:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3481:            } else {
 3482:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3483:            }
 3484:            if ($response->is_error()) {
 3485: 	       unlink($transname);
 3486:                my $message=$response->status_line;
 3487:                &logthis("<font color=\"blue\">WARNING:"
 3488:                        ." LWP get: $message: $filename</font>");
 3489:                return 'unavailable';
 3490:            } else {
 3491: 	       if ($remoteurl!~/\.meta$/) {
 3492:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3493:                   my $mresponse;
 3494:                   if ($remoteurl =~ m{/raw/}) {
 3495:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3496:                   } else {
 3497:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3498:                   }
 3499:                   if ($mresponse->is_error()) {
 3500: 		      unlink($filename.'.meta');
 3501:                       &logthis(
 3502:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3503:                   }
 3504: 	       }
 3505:                rename($transname,$filename);
 3506:                return 'ok';
 3507:            }
 3508:        }
 3509:     }
 3510: }
 3511: 
 3512: # ------------------------------------------------- Unsubscribe from a resource
 3513: 
 3514: sub unsubscribe {
 3515:     my ($fname) = @_;
 3516:     my $answer;
 3517:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3518:     $fname=~s/[\n\r]//g;
 3519:     my $author=$fname;
 3520:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3521:     my ($udom,$uname)=split(/\//,$author);
 3522:     my $home=homeserver($uname,$udom);
 3523:     if ($home eq 'no_host') {
 3524:         $answer = 'no_host';
 3525:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3526:         $answer = 'home';
 3527:     } else {
 3528:         my $defdom = $perlvar{'lonDefDomain'};
 3529:         if (&will_trust('content',$defdom,$udom)) {
 3530:             $answer = reply("unsub:$fname",$home);
 3531:         } else {
 3532:             $answer = 'untrusted';
 3533:         }
 3534:     }
 3535:     return $answer;
 3536: }
 3537: 
 3538: # ------------------------------------------------ Get server side include body
 3539: sub ssi_body {
 3540:     my ($filelink,%form)=@_;
 3541:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3542:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3543:     }
 3544:     my $output='';
 3545:     my $response;
 3546:     if ($filelink=~/^https?\:/) {
 3547:        ($output,$response)=&externalssi($filelink);
 3548:     } else {
 3549:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3550:        $filelink .= 'inhibitmenu=yes';
 3551:        ($output,$response)=&ssi($filelink,%form);
 3552:     }
 3553:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3554:     $output=~s/^.*?\<body[^\>]*\>//si;
 3555:     $output=~s/\<\/body\s*\>.*?$//si;
 3556:     if (wantarray) {
 3557:         return ($output, $response);
 3558:     } else {
 3559:         return $output;
 3560:     }
 3561: }
 3562: 
 3563: # --------------------------------------------------------- Server Side Include
 3564: 
 3565: sub absolute_url {
 3566:     my ($host_name,$unalias,$keep_proto) = @_;
 3567:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3568:     if ($host_name eq '') {
 3569: 	$host_name = $ENV{'SERVER_NAME'};
 3570:     }
 3571:     if ($unalias) {
 3572:         my $alias = &get_proxy_alias();
 3573:         if ($alias eq $host_name) {
 3574:             my $lonhost = $perlvar{'lonHostID'};
 3575:             my $hostname = &hostname($lonhost);
 3576:             my $lcproto; 
 3577:             if (($keep_proto) || ($hostname eq '')) {
 3578:                 $lcproto = $protocol;
 3579:             } else {
 3580:                 $lcproto = $protocol{$lonhost};
 3581:                 $lcproto = 'http' if ($lcproto ne 'https');
 3582:                 $lcproto .= '://';
 3583:             }
 3584:             unless ($hostname eq '') {
 3585:                 return $lcproto.$hostname;
 3586:             }
 3587:         }
 3588:     }
 3589:     return $protocol.$host_name;
 3590: }
 3591: 
 3592: #
 3593: #   Server side include.
 3594: # Parameters:
 3595: #  fn     Possibly encrypted resource name/id.
 3596: #  form   Hash that describes how the rendering should be done
 3597: #         and other things.
 3598: # Returns:
 3599: #   Scalar context: The content of the response.
 3600: #   Array context:  2 element list of the content and the full response object.
 3601: #     
 3602: sub ssi {
 3603: 
 3604:     my ($fn,%form)=@_;
 3605:     my ($host,$request,$response);
 3606:     $host = &absolute_url('',1);
 3607: 
 3608:     $form{'no_update_last_known'}=1;
 3609:     &Apache::lonenc::check_encrypt(\$fn);
 3610:     if (%form) {
 3611:       $request=new HTTP::Request('POST',$host.$fn);
 3612:       $request->content(join('&',map { 
 3613:             my $name = escape($_);
 3614:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3615:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3616:             : &escape($form{$_}) );    
 3617:         } keys(%form)));
 3618:     } else {
 3619:       $request=new HTTP::Request('GET',$host.$fn);
 3620:     }
 3621: 
 3622:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3623:     my $lonhost = $perlvar{'lonHostID'};
 3624:     my $islocal;
 3625:     if (($env{'request.course.id'}) &&
 3626:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3627:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3628:         ($form{'grade_symb'} ne '') &&
 3629:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3630:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3631:         $islocal = 1;
 3632:     }
 3633:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3634:                                              '','','',$islocal);
 3635: 
 3636:     if (wantarray) {
 3637: 	return ($response->content, $response);
 3638:     } else {
 3639: 	return $response->content;
 3640:     }
 3641: }
 3642: 
 3643: sub externalssi {
 3644:     my ($url)=@_;
 3645:     my $request=new HTTP::Request('GET',$url);
 3646:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3647:     if (wantarray) {
 3648:         return ($response->content, $response);
 3649:     } else {
 3650:         return $response->content;
 3651:     }
 3652: }
 3653: 
 3654: 
 3655: # If the local copy of a replicated resource is outdated, trigger a  
 3656: # connection from the homeserver to flush the delayed queue. If no update 
 3657: # happens, remove local copies of outdated resource (and corresponding
 3658: # metadata file).
 3659: 
 3660: sub remove_stale_resfile {
 3661:     my ($url) = @_;
 3662:     my $removed;
 3663:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3664:         my $audom = $1;
 3665:         my $auname = $2;
 3666:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3667:             my $homeserver = &homeserver($auname,$audom);
 3668:             unless (($homeserver eq 'no_host') ||
 3669:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3670:                 my $fname = &filelocation('',$url);
 3671:                 if (-e $fname) {
 3672:                     my $hostname = &hostname($homeserver);
 3673:                     if ($hostname) {
 3674:                         my $protocol = $protocol{$homeserver};
 3675:                         $protocol = 'http' if ($protocol ne 'https');
 3676:                         my $uri = &declutter($url);
 3677:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3678:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3679:                         if ($response->is_success()) {
 3680:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3681:                             my $locmodtime = (stat($fname))[9];
 3682:                             if ($locmodtime < $remmodtime) {
 3683:                                 my $stale;
 3684:                                 my $answer = &reply('pong',$homeserver);
 3685:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3686:                                     sleep(0.2);
 3687:                                     $locmodtime = (stat($fname))[9];
 3688:                                     if ($locmodtime < $remmodtime) {
 3689:                                         my $posstransfer = $fname.'.in.transfer';
 3690:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3691:                                             $removed = 1;
 3692:                                         } else {
 3693:                                             $stale = 1;
 3694:                                         }
 3695:                                     } else {
 3696:                                         $removed = 1;
 3697:                                     }
 3698:                                 } else {
 3699:                                     $stale = 1;
 3700:                                 }
 3701:                                 if ($stale) {
 3702:                                     if (unlink($fname)) {
 3703:                                         if ($uri!~/\.meta$/) {
 3704:                                             if (-e $fname.'.meta') {
 3705:                                                 unlink($fname.'.meta');
 3706:                                             }
 3707:                                         }
 3708:                                         my $unsubresult = &unsubscribe($fname);
 3709:                                         unless ($unsubresult eq 'ok') {
 3710:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3711:                                         }
 3712:                                         $removed = 1;
 3713:                                     }
 3714:                                 }
 3715:                             }
 3716:                         }
 3717:                     }
 3718:                 }
 3719:             }
 3720:         }
 3721:     }
 3722:     return $removed;
 3723: }
 3724: 
 3725: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3726: 
 3727: sub allowuploaded {
 3728:     my ($srcurl,$url)=@_;
 3729:     $url=&clutter(&declutter($url));
 3730:     my $dir=$url;
 3731:     $dir=~s/\/[^\/]+$//;
 3732:     my %httpref=();
 3733:     my $httpurl=&hreflocation('',$url);
 3734:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3735:     &Apache::lonnet::appenv(\%httpref);
 3736: }
 3737: 
 3738: #
 3739: # Determine if the current user should be able to edit a particular resource,
 3740: # when viewing in course context.
 3741: # (a) When viewing resource used to determine if "Edit" item is included in 
 3742: #     Functions.
 3743: # (b) When displaying folder contents in course editor, used to determine if
 3744: #     "Edit" link will be displayed alongside resource.
 3745: #
 3746: #  input: six args -- filename (decluttered), course number, course domain,
 3747: #                   url, symb (if registered) and group (if this is a group
 3748: #                   item -- e.g., bulletin board, group page etc.).
 3749: #  output: array of five scalars -- 
 3750: #          $cfile -- url for file editing if editable on current server
 3751: #          $home -- homeserver of resource (i.e., for author if published,
 3752: #                                           or course if uploaded.).
 3753: #          $switchserver --  1 if server switch will be needed.
 3754: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3755: #          $forceview -- 1 if icon/link should be to go to view mode
 3756: #
 3757: 
 3758: sub can_edit_resource {
 3759:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3760:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3761: #
 3762: # For aboutme pages user can only edit his/her own.
 3763: #
 3764:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3765:         my ($sdom,$sname) = ($1,$2);
 3766:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3767:             $home = $env{'user.home'};
 3768:             $cfile = $resurl;
 3769:             if ($env{'form.forceedit'}) {
 3770:                 $forceview = 1;
 3771:             } else {
 3772:                 $forceedit = 1;
 3773:             }
 3774:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3775:         } else {
 3776:             return;
 3777:         }
 3778:     }
 3779: 
 3780:     if ($env{'request.course.id'}) {
 3781:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3782:         if ($group ne '') {
 3783: # if this is a group homepage or group bulletin board, check group privs
 3784:             my $allowed = 0;
 3785:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3786:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3787:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3788:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3789:                     $allowed = 1;
 3790:                 }
 3791:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3792:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3793:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3794:                     $allowed = 1;
 3795:                 }
 3796:             }
 3797:             if ($allowed) {
 3798:                 $home=&homeserver($cnum,$cdom);
 3799:                 if ($env{'form.forceedit'}) {
 3800:                     $forceview = 1;
 3801:                 } else {
 3802:                     $forceedit = 1;
 3803:                 }
 3804:                 $cfile = $resurl;
 3805:             } else {
 3806:                 return;
 3807:             }
 3808:         } else {
 3809:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3810:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3811:                     return;
 3812:                 }
 3813:             } elsif (!$crsedit) {
 3814: #
 3815: # No edit allowed where CC has switched to student role.
 3816: #
 3817:                 return;
 3818:             }
 3819:         }
 3820:     }
 3821: 
 3822:     if ($file ne '') {
 3823:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3824:             if (&is_course_upload($file,$cnum,$cdom)) {
 3825:                 $uploaded = 1;
 3826:                 $incourse = 1;
 3827:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3828:                     $cfile = &hreflocation('',$file);
 3829:                     if ($env{'form.forceedit'}) {
 3830:                         $forceview = 1;
 3831:                     } else {
 3832:                         $forceedit = 1;
 3833:                     }
 3834:                 }
 3835:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3836:                 $incourse = 1;
 3837:                 if ($env{'form.forceedit'}) {
 3838:                     $forceview = 1;
 3839:                 } else {
 3840:                     $forceedit = 1;
 3841:                 }
 3842:                 $cfile = $resurl;
 3843:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3844:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3845:                     $incourse = 1;
 3846:                     if ($env{'form.forceedit'}) {
 3847:                         $forceview = 1;
 3848:                     } else {
 3849:                         $forceedit = 1;
 3850:                     }
 3851:                     $cfile = $resurl;
 3852:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3853:                     $incourse = 1;
 3854:                     $cfile = $resurl.'/smpedit';
 3855:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3856:                     $incourse = 1;
 3857:                     if ($env{'form.forceedit'}) {
 3858:                         $forceview = 1;
 3859:                     } else {
 3860:                         $forceedit = 1;
 3861:                     }
 3862:                     $cfile = $resurl;
 3863:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3864:                     my ($map,$id,$res) = &decode_symb($symb);
 3865:                     if ($map =~ /\.page$/) {
 3866:                         $incourse = 1;
 3867:                         if ($env{'form.forceedit'}) {
 3868:                             $forceview = 1;
 3869:                             $cfile = $map;
 3870:                         } else {
 3871:                             $forceedit = 1;
 3872:                             $cfile =  '/adm/wrapper'.$resurl;
 3873:                         }
 3874:                     }
 3875:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3876:                     $incourse = 1;
 3877:                     if ($env{'form.forceedit'}) {
 3878:                         $forceview = 1;
 3879:                     } else {
 3880:                         $forceedit = 1;
 3881:                     }
 3882:                     $cfile = $resurl;
 3883:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3884:                     $incourse = 1;
 3885:                     if ($env{'form.forceedit'}) {
 3886:                         $forceview = 1;
 3887:                     } else {
 3888:                         $forceedit = 1;
 3889:                     }
 3890:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3891:                 }
 3892:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3893:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3894:                 if (&is_on_map($template)) { 
 3895:                     $incourse = 1;
 3896:                     $forceview = 1;
 3897:                     $cfile = $template;
 3898:                 }
 3899:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($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 =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3908:                 $incourse = 1;
 3909:                 if ($env{'form.forceedit'}) {
 3910:                     $forceview = 1;
 3911:                 } else {
 3912:                     $forceedit = 1;
 3913:                 }
 3914:                 $cfile = $resurl;
 3915:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3916:                 $incourse = 1;
 3917:                 $forceview = 1;
 3918:                 if ($symb) {
 3919:                     my ($map,$id,$res)=&decode_symb($symb);
 3920:                     $env{'request.symb'} = $symb;
 3921:                     $cfile = &clutter($res);
 3922:                 } else {
 3923:                     $cfile = $env{'form.suppurl'};
 3924:                     my $escfile = &unescape($cfile);
 3925:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3926:                         $cfile = '/adm/wrapper'.$escfile;
 3927:                     } else {
 3928:                         $escfile =~ s{^http://}{};
 3929:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3930:                     }
 3931:                 }
 3932:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3933:                 if ($env{'form.forceedit'}) {
 3934:                     $forceview = 1;
 3935:                 } else {
 3936:                     $forceedit = 1;
 3937:                 }
 3938:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3939:             }
 3940:         }
 3941:         if ($uploaded || $incourse) {
 3942:             $home=&homeserver($cnum,$cdom);
 3943:         } elsif ($file !~ m{/$}) {
 3944:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3945:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3946:             # Check that the user has permission to edit this resource
 3947:             my $setpriv = 1;
 3948:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3949:             if (defined($cfudom)) {
 3950:                 $home=&homeserver($cfuname,$cfudom);
 3951:                 $cfile=$file;
 3952:             }
 3953:         }
 3954:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3955:             (($home ne '') && ($home ne 'no_host'))) {
 3956:             my @ids=&current_machine_ids();
 3957:             unless (grep(/^\Q$home\E$/,@ids)) {
 3958:                 $switchserver=1;
 3959:             }
 3960:         }
 3961:     }
 3962:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3963: }
 3964: 
 3965: sub is_course_upload {
 3966:     my ($file,$cnum,$cdom) = @_;
 3967:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3968:     $uploadpath =~ s{^\/}{};
 3969:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3970:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3971:         return 1;
 3972:     }
 3973:     return;
 3974: }
 3975: 
 3976: sub in_course {
 3977:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3978:     if ($hideprivileged) {
 3979:         my $skipuser;
 3980:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3981:         my @possdoms = ($cdom);  
 3982:         if ($coursehash{'checkforpriv'}) { 
 3983:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3984:         }
 3985:         if (&privileged($uname,$udom,\@possdoms)) {
 3986:             $skipuser = 1;
 3987:             if ($coursehash{'nothideprivileged'}) {
 3988:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3989:                     my $user;
 3990:                     if ($item =~ /:/) {
 3991:                         $user = $item;
 3992:                     } else {
 3993:                         $user = join(':',split(/[\@]/,$item));
 3994:                     }
 3995:                     if ($user eq $uname.':'.$udom) {
 3996:                         undef($skipuser);
 3997:                         last;
 3998:                     }
 3999:                 }
 4000:             }
 4001:             if ($skipuser) {
 4002:                 return 0;
 4003:             }
 4004:         }
 4005:     }
 4006:     $type ||= 'any';
 4007:     if (!defined($cdom) || !defined($cnum)) {
 4008:         my $cid  = $env{'request.course.id'};
 4009:         $cdom = $env{'course.'.$cid.'.domain'};
 4010:         $cnum = $env{'course.'.$cid.'.num'};
 4011:     }
 4012:     my $typesref;
 4013:     if (($type eq 'any') || ($type eq 'all')) {
 4014:         $typesref = ['active','previous','future'];
 4015:     } elsif ($type eq 'previous' || $type eq 'future') {
 4016:         $typesref = [$type];
 4017:     }
 4018:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4019:                               $typesref,undef,[$cdom]);
 4020:     my ($tmp) = keys(%roles);
 4021:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4022:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4023:     if (@course_roles > 0) {
 4024:         return 1;
 4025:     }
 4026:     return 0;
 4027: }
 4028: 
 4029: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4030: # input: action, courseID, current domain, intended
 4031: #        path to file, source of file, instruction to parse file for objects,
 4032: #        ref to hash for embedded objects,
 4033: #        ref to hash for codebase of java objects.
 4034: #        reference to scalar to accommodate mime type determined
 4035: #          from File::MMagic if $parser = parse.
 4036: #
 4037: # output: url to file (if action was uploaddoc), 
 4038: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4039: #
 4040: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4041: # course.
 4042: #
 4043: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4044: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4045: #          course's home server.
 4046: #
 4047: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4048: #          be copied from $source (current location) to 
 4049: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4050: #         and will then be copied to
 4051: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4052: #         course's home server.
 4053: #
 4054: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4055: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4056: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4057: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4058: #         in course's home server.
 4059: #
 4060: 
 4061: sub process_coursefile {
 4062:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4063:         $mimetype)=@_;
 4064:     my $fetchresult;
 4065:     my $home=&homeserver($docuname,$docudom);
 4066:     if ($action eq 'propagate') {
 4067:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4068: 			     $home);
 4069:     } else {
 4070:         my $fpath = '';
 4071:         my $fname = $file;
 4072:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4073:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4074:         my $filepath = &build_filepath($fpath);
 4075:         if ($action eq 'copy') {
 4076:             if ($source eq '') {
 4077:                 $fetchresult = 'no source file';
 4078:                 return $fetchresult;
 4079:             } else {
 4080:                 my $destination = $filepath.'/'.$fname;
 4081:                 rename($source,$destination);
 4082:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4083:                                  $home);
 4084:             }
 4085:         } elsif ($action eq 'uploaddoc') {
 4086:             open(my $fh,'>',$filepath.'/'.$fname);
 4087:             print $fh $env{'form.'.$source};
 4088:             close($fh);
 4089:             if ($parser eq 'parse') {
 4090:                 my $mm = new File::MMagic;
 4091:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4092:                 if ($type eq 'text/html') {
 4093:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4094:                     unless ($parse_result eq 'ok') {
 4095:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4096:                     }
 4097:                 }
 4098:                 if (ref($mimetype)) {
 4099:                     $$mimetype = $type;
 4100:                 } 
 4101:             }
 4102:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4103:                                  $home);
 4104:             if ($fetchresult eq 'ok') {
 4105:                 return '/uploaded/'.$fpath.'/'.$fname;
 4106:             } else {
 4107:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4108:                         ' to host '.$home.': '.$fetchresult);
 4109:                 return '/adm/notfound.html';
 4110:             }
 4111:         }
 4112:     }
 4113:     unless ( $fetchresult eq 'ok') {
 4114:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4115:              ' to host '.$home.': '.$fetchresult);
 4116:     }
 4117:     return $fetchresult;
 4118: }
 4119: 
 4120: sub build_filepath {
 4121:     my ($fpath) = @_;
 4122:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4123:     unless ($fpath eq '') {
 4124:         my @parts=split('/',$fpath);
 4125:         foreach my $part (@parts) {
 4126:             $filepath.= '/'.$part;
 4127:             if ((-e $filepath)!=1) {
 4128:                 mkdir($filepath,0777);
 4129:             }
 4130:         }
 4131:     }
 4132:     return $filepath;
 4133: }
 4134: 
 4135: sub store_edited_file {
 4136:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4137:     my $file = $primary_url;
 4138:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4139:     my $fpath = '';
 4140:     my $fname = $file;
 4141:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4142:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4143:     my $filepath = &build_filepath($fpath);
 4144:     open(my $fh,'>',$filepath.'/'.$fname);
 4145:     print $fh $content;
 4146:     close($fh);
 4147:     my $home=&homeserver($docuname,$docudom);
 4148:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4149: 			  $home);
 4150:     if ($$fetchresult eq 'ok') {
 4151:         return '/uploaded/'.$fpath.'/'.$fname;
 4152:     } else {
 4153:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4154: 		 ' to host '.$home.': '.$$fetchresult);
 4155:         return '/adm/notfound.html';
 4156:     }
 4157: }
 4158: 
 4159: sub clean_filename {
 4160:     my ($fname,$args)=@_;
 4161: # Replace Windows backslashes by forward slashes
 4162:     $fname=~s/\\/\//g;
 4163:     if (!$args->{'keep_path'}) {
 4164:         # Get rid of everything but the actual filename
 4165: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4166:     }
 4167: # Replace spaces by underscores
 4168:     $fname=~s/\s+/\_/g;
 4169: # Transliterate non-ascii text to ascii
 4170:     my $lang = &Apache::lonlocal::current_language();
 4171:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4172: # Replace all other weird characters by nothing
 4173:     $fname=~s{[^/\w\.\-]}{}g;
 4174: # Replace all .\d. sequences with _\d. so they no longer look like version
 4175: # numbers
 4176:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4177: # Replace three or more adjacent underscores with one for consistency 
 4178: # with loncfile::filename_check() so complete url can be extracted by
 4179: # lonnet::decode_symb()
 4180:     $fname=~s/_{3,}/_/g;
 4181:     return $fname;
 4182: }
 4183: 
 4184: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4185: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4186: # image with the same aspect ratio as the original, but with dimensions which do 
 4187: # not exceed $resizewidth and $resizeheight.
 4188:  
 4189: sub resizeImage {
 4190:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4191:     my $ima = Image::Magick->new;
 4192:     my $resized;
 4193:     if (-e $img_path) {
 4194:         $ima->Read($img_path);
 4195:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4196:             my $width = $ima->Get('width');
 4197:             my $height = $ima->Get('height');
 4198:             if ($width > $resizewidth) {
 4199: 	        my $factor = $width/$resizewidth;
 4200:                 my $newheight = $height/$factor;
 4201:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4202:                 $resized = 1;
 4203:             }
 4204:         }
 4205:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4206:             my $width = $ima->Get('width');
 4207:             my $height = $ima->Get('height');
 4208:             if ($height > $resizeheight) {
 4209:                 my $factor = $height/$resizeheight;
 4210:                 my $newwidth = $width/$factor;
 4211:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4212:                 $resized = 1;
 4213:             }
 4214:         }
 4215:         if ($resized) {
 4216:             $ima->Write($img_path);
 4217:         }
 4218:     }
 4219:     return;
 4220: }
 4221: 
 4222: # --------------- Take an uploaded file and put it into the userfiles directory
 4223: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4224: #                    the desired filename is in $env{"form.$formname.filename"}
 4225: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4226: #                                    canceloverwrite, scantron or ''.
 4227: #                   if 'coursedoc': upload to the current course
 4228: #                   if 'existingfile': write file to tmp/overwrites directory 
 4229: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4230: #                   $context is passed as argument to &finishuserfileupload
 4231: #        $subdir - directory in userfile to store the file into
 4232: #        $parser - instruction to parse file for objects ($parser = parse) or
 4233: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4234: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4235: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4236: #        $allfiles - reference to hash for embedded objects
 4237: #        $codebase - reference to hash for codebase of java objects
 4238: #        $desuname - username for permanent storage of uploaded file
 4239: #        $dsetudom - domain for permanaent storage of uploaded file
 4240: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4241: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4242: #        $resizewidth - width (pixels) to which to resize uploaded image
 4243: #        $resizeheight - height (pixels) to which to resize uploaded image
 4244: #        $mimetype - reference to scalar to accommodate mime type determined
 4245: #                    from File::MMagic.
 4246: # 
 4247: # output: url of file in userspace, or error: <message> 
 4248: #             or /adm/notfound.html if failure to upload occurse
 4249: 
 4250: sub userfileupload {
 4251:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4252:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4253:     if (!defined($subdir)) { $subdir='unknown'; }
 4254:     my $fname=$env{'form.'.$formname.'.filename'};
 4255:     $fname=&clean_filename($fname);
 4256:     # See if there is anything left
 4257:     unless ($fname) { return 'error: no uploaded file'; }
 4258:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4259:     if ($fname =~ /^\./) {
 4260:         my ($s,$usec) = &gettimeofday();
 4261:         while (length($usec) < 6) {
 4262:             $usec = '0'.$usec;
 4263:         }
 4264:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4265:     }
 4266:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4267:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4268:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4269:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4270:         my $now = time;
 4271:         my $filepath;
 4272:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4273:              $filepath = 'tmp/helprequests/'.$now;
 4274:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4275:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4276:                          '_'.$env{'user.domain'}.'/pending';
 4277:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4278:             my ($docuname,$docudom);
 4279:             if ($destudom =~ /^$match_domain$/) {
 4280:                 $docudom = $destudom;
 4281:             } else {
 4282:                 $docudom = $env{'user.domain'};
 4283:             }
 4284:             if ($destuname =~ /^$match_username$/) {
 4285:                 $docuname = $destuname;
 4286:             } else {
 4287:                 $docuname = $env{'user.name'};
 4288:             }
 4289:             if (exists($env{'form.group'})) {
 4290:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4291:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4292:             }
 4293:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4294:             if ($context eq 'canceloverwrite') {
 4295:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4296:                 if (-e  $tempfile) {
 4297:                     my @info = stat($tempfile);
 4298:                     if ($info[9] eq $env{'form.timestamp'}) {
 4299:                         unlink($tempfile);
 4300:                     }
 4301:                 }
 4302:                 return;
 4303:             }
 4304:         }
 4305:         # Create the directory if not present
 4306:         my @parts=split(/\//,$filepath);
 4307:         my $fullpath = $perlvar{'lonDaemons'};
 4308:         for (my $i=0;$i<@parts;$i++) {
 4309:             $fullpath .= '/'.$parts[$i];
 4310:             if ((-e $fullpath)!=1) {
 4311:                 mkdir($fullpath,0777);
 4312:             }
 4313:         }
 4314:         open(my $fh,'>',$fullpath.'/'.$fname);
 4315:         print $fh $env{'form.'.$formname};
 4316:         close($fh);
 4317:         if ($context eq 'existingfile') {
 4318:             my @info = stat($fullpath.'/'.$fname);
 4319:             return ($fullpath.'/'.$fname,$info[9]);
 4320:         } else {
 4321:             return $fullpath.'/'.$fname;
 4322:         }
 4323:     }
 4324:     if ($subdir eq 'scantron') {
 4325:         $fname = 'scantron_orig_'.$fname;
 4326:     } else {
 4327:         $fname="$subdir/$fname";
 4328:     }
 4329:     if ($context eq 'coursedoc') {
 4330: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4331: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4332:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4333:             return &finishuserfileupload($docuname,$docudom,
 4334: 					 $formname,$fname,$parser,$allfiles,
 4335: 					 $codebase,$thumbwidth,$thumbheight,
 4336:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4337:         } else {
 4338:             if ($env{'form.folder'}) {
 4339:                 $fname=$env{'form.folder'}.'/'.$fname;
 4340:             }
 4341:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4342: 				       $fname,$formname,$parser,
 4343: 				       $allfiles,$codebase,$mimetype);
 4344:         }
 4345:     } elsif (defined($destuname)) {
 4346:         my $docuname=$destuname;
 4347:         my $docudom=$destudom;
 4348: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4349: 				     $parser,$allfiles,$codebase,
 4350:                                      $thumbwidth,$thumbheight,
 4351:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4352:     } else {
 4353:         my $docuname=$env{'user.name'};
 4354:         my $docudom=$env{'user.domain'};
 4355:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4356:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4357:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4358:         }
 4359: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4360: 				     $parser,$allfiles,$codebase,
 4361:                                      $thumbwidth,$thumbheight,
 4362:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4363:     }
 4364: }
 4365: 
 4366: sub finishuserfileupload {
 4367:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4368:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4369:     my $path=$docudom.'/'.$docuname.'/';
 4370:     my $filepath=$perlvar{'lonDocRoot'};
 4371:   
 4372:     my ($fnamepath,$file,$fetchthumb);
 4373:     $file=$fname;
 4374:     if ($fname=~m|/|) {
 4375:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4376: 	$path.=$fnamepath.'/';
 4377:     }
 4378:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4379:     my $count;
 4380:     for ($count=4;$count<=$#parts;$count++) {
 4381:         $filepath.="/$parts[$count]";
 4382:         if ((-e $filepath)!=1) {
 4383: 	    mkdir($filepath,0777);
 4384:         }
 4385:     }
 4386: 
 4387: # Save the file
 4388:     {
 4389: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4390: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4391: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4392: 	    return '/adm/notfound.html';
 4393: 	}
 4394:         if ($context eq 'overwrite') {
 4395:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4396:             my $target = $filepath.'/'.$file;
 4397:             if (-e $source) {
 4398:                 my @info = stat($source);
 4399:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4400:                     unless (&File::Copy::move($source,$target)) {
 4401:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4402:                         return "Moving from $source failed";
 4403:                     }
 4404:                 } else {
 4405:                     return "Temporary file: $source had unexpected date/time for last modification";
 4406:                 }
 4407:             } else {
 4408:                 return "Temporary file: $source missing";
 4409:             }
 4410:         } elsif (!print FH ($env{'form.'.$formname})) {
 4411: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4412: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4413: 	    return '/adm/notfound.html';
 4414: 	}
 4415: 	close(FH);
 4416:         if ($resizewidth && $resizeheight) {
 4417:             my $mm = new File::MMagic;
 4418:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4419:             if ($mime_type =~ m{^image/}) {
 4420: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4421:             }  
 4422: 	}
 4423:     }
 4424:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4425:         if (ref($mimetype)) {
 4426:             if ($$mimetype eq '') {
 4427:                 my $mm = new File::MMagic;
 4428:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4429:                 $$mimetype = $type;
 4430:             }
 4431:         }
 4432:     }
 4433:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4434:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4435:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4436:                                                        $allfiles,$codebase);
 4437:             unless ($parse_result eq 'ok') {
 4438:                 &logthis('Failed to parse '.$filepath.$file.
 4439: 	   	         ' for embedded media: '.$parse_result); 
 4440:             }
 4441:         }
 4442:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4443:         my $format = $env{'form.scantron_format'};
 4444:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4445:     }
 4446:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4447:         my $input = $filepath.'/'.$file;
 4448:         my $output = $filepath.'/'.'tn-'.$file;
 4449:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4450:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4451:         system({$args[0]} @args);
 4452:         if (-e $filepath.'/'.'tn-'.$file) {
 4453:             $fetchthumb  = 1; 
 4454:         }
 4455:     }
 4456:  
 4457: # Notify homeserver to grep it
 4458: #
 4459:     my $docuhome=&homeserver($docuname,$docudom);	
 4460:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4461:     if ($fetchresult eq 'ok') {
 4462:         if ($fetchthumb) {
 4463:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4464:             if ($thumbresult ne 'ok') {
 4465:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4466:                          $docuhome.': '.$thumbresult);
 4467:             }
 4468:         }
 4469: #
 4470: # Return the URL to it
 4471:         return '/uploaded/'.$path.$file;
 4472:     } else {
 4473:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4474: 		 ': '.$fetchresult);
 4475:         return '/adm/notfound.html';
 4476:     }
 4477: }
 4478: 
 4479: sub extract_embedded_items {
 4480:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4481:     my @state = ();
 4482:     my (%lastids,%related,%shockwave,%flashvars);
 4483:     my %javafiles = (
 4484:                       codebase => '',
 4485:                       code => '',
 4486:                       archive => ''
 4487:                     );
 4488:     my %mediafiles = (
 4489:                       src => '',
 4490:                       movie => '',
 4491:                      );
 4492:     my $p;
 4493:     if ($content) {
 4494:         $p = HTML::LCParser->new($content);
 4495:     } else {
 4496:         $p = HTML::LCParser->new($fullpath);
 4497:     }
 4498:     while (my $t=$p->get_token()) {
 4499: 	if ($t->[0] eq 'S') {
 4500: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4501: 	    push(@state, $tagname);
 4502:             if (lc($tagname) eq 'allow') {
 4503:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4504:             }
 4505: 	    if (lc($tagname) eq 'img') {
 4506: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4507: 	    }
 4508: 	    if (lc($tagname) eq 'a') {
 4509:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4510:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4511:                 }
 4512: 	    }
 4513:             if (lc($tagname) eq 'script') {
 4514:                 my $src;
 4515:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4516:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4517:                 } else {
 4518:                     if ($attr->{'src'} ne '') {
 4519:                         $src = $attr->{'src'};
 4520:                         &add_filetype($allfiles,$src,'src');
 4521:                     }
 4522:                 }
 4523:                 my $text = $p->get_trimmed_text();
 4524:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4525:                     my @swfargs = split(/,/,$1);
 4526:                     foreach my $item (@swfargs) {
 4527:                         $item =~ s/["']//g;
 4528:                         $item =~ s/^\s+//;
 4529:                         $item =~ s/\s+$//;
 4530:                     }
 4531:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4532:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4533:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4534:                         } else {
 4535:                             $related{$swfargs[0]} = [$swfargs[2]];
 4536:                         }
 4537:                     }
 4538:                 }
 4539:             }
 4540:             if (lc($tagname) eq 'link') {
 4541:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4542:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4543:                 }
 4544:             }
 4545: 	    if (lc($tagname) eq 'object' ||
 4546: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4547: 		foreach my $item (keys(%javafiles)) {
 4548: 		    $javafiles{$item} = '';
 4549: 		}
 4550:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4551:                     $lastids{lc($tagname)} = $attr->{'id'};
 4552:                 }
 4553: 	    }
 4554: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4555: 		my $name = lc($attr->{'name'});
 4556: 		foreach my $item (keys(%javafiles)) {
 4557: 		    if ($name eq $item) {
 4558: 			$javafiles{$item} = $attr->{'value'};
 4559: 			last;
 4560: 		    }
 4561: 		}
 4562:                 my $pathfrom;
 4563: 		foreach my $item (keys(%mediafiles)) {
 4564: 		    if ($name eq $item) {
 4565:                         $pathfrom = $attr->{'value'};
 4566:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4567: 			&add_filetype($allfiles,$pathfrom,$name);
 4568: 			last;
 4569: 		    }
 4570: 		}
 4571:                 if ($name eq 'flashvars') {
 4572:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4573:                 }
 4574:                 if ($pathfrom ne '') {
 4575:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4576:                                          $pathfrom);
 4577:                 }
 4578: 	    }
 4579: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4580: 		foreach my $item (keys(%javafiles)) {
 4581: 		    if ($attr->{$item}) {
 4582: 			$javafiles{$item} = $attr->{$item};
 4583: 			last;
 4584: 		    }
 4585: 		}
 4586: 		foreach my $item (keys(%mediafiles)) {
 4587: 		    if ($attr->{$item}) {
 4588: 			&add_filetype($allfiles,$attr->{$item},$item);
 4589: 			last;
 4590: 		    }
 4591: 		}
 4592:                 if (lc($tagname) eq 'embed') {
 4593:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4594:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4595:                                              $attr->{'src'});
 4596:                     }
 4597:                 }
 4598: 	    }
 4599:             if (lc($tagname) eq 'iframe') {
 4600:                 my $src = $attr->{'src'} ;
 4601:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4602:                     &add_filetype($allfiles,$src,'src');
 4603:                 } elsif ($src =~ m{^/}) {
 4604:                     if ($env{'request.course.id'}) {
 4605:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4606:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4607:                         my $url = &hreflocation('',$fullpath);
 4608:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4609:                             my $relpath = $1;
 4610:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4611:                                 &add_filetype($allfiles,$1,'src');
 4612:                             }
 4613:                         }
 4614:                     }
 4615:                 }
 4616:             }
 4617:             if ($t->[4] =~ m{/>$}) {
 4618:                 pop(@state);
 4619:             }
 4620: 	} elsif ($t->[0] eq 'E') {
 4621: 	    my ($tagname) = ($t->[1]);
 4622: 	    if ($javafiles{'codebase'} ne '') {
 4623: 		$javafiles{'codebase'} .= '/';
 4624: 	    }  
 4625: 	    if (lc($tagname) eq 'applet' ||
 4626: 		lc($tagname) eq 'object' ||
 4627: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4628: 		) {
 4629: 		foreach my $item (keys(%javafiles)) {
 4630: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4631: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4632: 			&add_filetype($allfiles,$file,$item);
 4633: 		    }
 4634: 		}
 4635: 	    } 
 4636: 	    pop @state;
 4637: 	}
 4638:     }
 4639:     foreach my $id (sort(keys(%flashvars))) {
 4640:         if ($shockwave{$id} ne '') {
 4641:             my @pairs = split(/\&/,$flashvars{$id});
 4642:             foreach my $pair (@pairs) {
 4643:                 my ($key,$value) = split(/\=/,$pair);
 4644:                 if ($key eq 'thumb') {
 4645:                     &add_filetype($allfiles,$value,$key);
 4646:                 } elsif ($key eq 'content') {
 4647:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4648:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4649:                     if ($ext ne '') {
 4650:                         &add_filetype($allfiles,$path.$value,$ext);
 4651:                     }
 4652:                 }
 4653:             }
 4654:         }
 4655:     }
 4656:     return 'ok';
 4657: }
 4658: 
 4659: sub add_filetype {
 4660:     my ($allfiles,$file,$type)=@_;
 4661:     if (exists($allfiles->{$file})) {
 4662: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4663: 	    push(@{$allfiles->{$file}}, &escape($type));
 4664: 	}
 4665:     } else {
 4666: 	@{$allfiles->{$file}} = (&escape($type));
 4667:     }
 4668: }
 4669: 
 4670: sub embedded_dependency {
 4671:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4672:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4673:         if (($identifier ne '') &&
 4674:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4675:             ($pathfrom ne '')) {
 4676:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4677:             foreach my $dep (@{$related->{$identifier}}) {
 4678:                 &add_filetype($allfiles,$path.$dep,'object');
 4679:             }
 4680:         }
 4681:     }
 4682:     return;
 4683: }
 4684: 
 4685: sub bubblesheet_converter {
 4686:     my ($cdom,$fullpath,$config,$format) = @_;
 4687:     if ((&domain($cdom) ne '') &&
 4688:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4689:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4690:         my (%csvcols,%csvoptions);
 4691:         if (ref($config->{'fields'}) eq 'HASH') {  
 4692:             %csvcols = %{$config->{'fields'}};
 4693:         }
 4694:         if (ref($config->{'options'}) eq 'HASH') {
 4695:             %csvoptions = %{$config->{'options'}};
 4696:         }
 4697:         my %csvbynum = reverse(%csvcols);
 4698:         my %scantronconf = &get_scantron_config($format,$cdom);
 4699:         if (keys(%scantronconf)) {
 4700:             my %bynum = (
 4701:                           $scantronconf{CODEstart} => 'CODEstart',
 4702:                           $scantronconf{IDstart}   => 'IDstart',
 4703:                           $scantronconf{PaperID}   => 'PaperID',
 4704:                           $scantronconf{FirstName} => 'FirstName',
 4705:                           $scantronconf{LastName}  => 'LastName',
 4706:                           $scantronconf{Qstart}    => 'Qstart',
 4707:                         );
 4708:             my @ordered;
 4709:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4710:                 push(@ordered,$bynum{$item});
 4711:             }
 4712:             my %mapstart = (
 4713:                               CODEstart => 'CODE',
 4714:                               IDstart   => 'ID',
 4715:                               PaperID   => 'PaperID',
 4716:                               FirstName => 'FirstName',
 4717:                               LastName  => 'LastName',
 4718:                               Qstart    => 'FirstQuestion',
 4719:                            );
 4720:             my %maplength = (
 4721:                               CODEstart => 'CODElength',
 4722:                               IDstart   => 'IDlength',
 4723:                               PaperID   => 'PaperIDlength',
 4724:                               FirstName => 'FirstNamelength',
 4725:                               LastName  => 'LastNamelength',
 4726:             );
 4727:             if (open(my $fh,'<',$fullpath)) {
 4728:                 my $output;
 4729:                 my %lettdig = &letter_to_digits();
 4730:                 my %diglett = reverse(%lettdig);
 4731:                 my $numletts = scalar(keys(%lettdig));
 4732:                 my $num = 0;
 4733:                 while (my $line=<$fh>) {
 4734:                     $num ++;
 4735:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4736:                     $line =~ s{[\r\n]+$}{};
 4737:                     my %found;
 4738:                     my @values = split(/,/,$line,-1);
 4739:                     my ($qstart,$record);
 4740:                     for (my $i=0; $i<@values; $i++) {
 4741:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4742:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4743:                             if ($values[$i] eq '') {
 4744:                                 $values[$i] = $scantronconf{'Qoff'};
 4745:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4746:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4747:                                     $values[$i] = $lettdig{uc($values[$i])};
 4748:                                 }
 4749:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4750:                                 if ($values[$i] =~ /^[0-9]$/) {
 4751:                                     $values[$i] = $diglett{$values[$i]};
 4752:                                 }
 4753:                             } else {
 4754:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4755:                                     my $digit;
 4756:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4757:                                         $digit = $lettdig{uc($values[$i])}-1;
 4758:                                         if ($values[$i] eq 'J') {
 4759:                                             $digit += $numletts;
 4760:                                         }
 4761:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4762:                                         $digit = $values[$i]-1;
 4763:                                         if ($values[$i] eq '0') {
 4764:                                             $digit += $numletts;
 4765:                                         }
 4766:                                     }
 4767:                                     my $qval='';
 4768:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4769:                                         if ($j == $digit) {
 4770:                                             $qval .= $scantronconf{'Qon'};
 4771:                                         } else {
 4772:                                             $qval .= $scantronconf{'Qoff'};
 4773:                                         }
 4774:                                     }
 4775:                                     $values[$i] = $qval;
 4776:                                 }
 4777:                             }
 4778:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4779:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4780:                             }
 4781:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4782:                             if ($numblank > 0) {
 4783:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4784:                             }
 4785:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4786:                                 $qstart = $i;
 4787:                                 $found{$csvbynum{$i}} = $values[$i];
 4788:                             } else {
 4789:                                 $found{'FirstQuestion'} .= $values[$i];
 4790:                             }
 4791:                         } elsif (exists($csvbynum{$i})) {
 4792:                             if ($csvoptions{'rem'}) {
 4793:                                 $values[$i] =~ s/^\s+//;
 4794:                             }
 4795:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4796:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4797:                                     $values[$i] = '0'.$values[$i];
 4798:                                 }
 4799:                             }
 4800:                             $found{$csvbynum{$i}} = $values[$i];
 4801:                         }
 4802:                     }
 4803:                     foreach my $item (@ordered) {
 4804:                         my $currlength = 1+length($record);
 4805:                         my $numspaces = $scantronconf{$item} - $currlength;
 4806:                         if ($numspaces > 0) {
 4807:                             $record .= (' ' x $numspaces);
 4808:                         }
 4809:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4810:                             unless ($item eq 'Qstart') {
 4811:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4812:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4813:                                 }
 4814:                             }
 4815:                             $record .= $found{$mapstart{$item}};
 4816:                         }
 4817:                     }
 4818:                     $output .= "$record\n";
 4819:                 }
 4820:                 close($fh);
 4821:                 if ($output) {
 4822:                     if (open(my $fh,'>',$fullpath)) {
 4823:                         print $fh $output;
 4824:                         close($fh);
 4825:                     }
 4826:                 }
 4827:             }
 4828:         }
 4829:         return;
 4830:     }
 4831: }
 4832: 
 4833: sub letter_to_digits {
 4834:     my %lettdig = (
 4835:                     A => 1,
 4836:                     B => 2,
 4837:                     C => 3,
 4838:                     D => 4,
 4839:                     E => 5,
 4840:                     F => 6,
 4841:                     G => 7,
 4842:                     H => 8,
 4843:                     I => 9,
 4844:                     J => 0,
 4845:                   );
 4846:     return %lettdig;
 4847: }
 4848: 
 4849: sub get_scantron_config {
 4850:     my ($which,$cdom) = @_;
 4851:     my @lines = &get_scantronformat_file($cdom);
 4852:     my %config;
 4853:     #FIXME probably should move to XML it has already gotten a bit much now
 4854:     foreach my $line (@lines) {
 4855:         my ($name,$descrip)=split(/:/,$line);
 4856:         if ($name ne $which ) { next; }
 4857:         chomp($line);
 4858:         my @config=split(/:/,$line);
 4859:         $config{'name'}=$config[0];
 4860:         $config{'description'}=$config[1];
 4861:         $config{'CODElocation'}=$config[2];
 4862:         $config{'CODEstart'}=$config[3];
 4863:         $config{'CODElength'}=$config[4];
 4864:         $config{'IDstart'}=$config[5];
 4865:         $config{'IDlength'}=$config[6];
 4866:         $config{'Qstart'}=$config[7];
 4867:         $config{'Qlength'}=$config[8];
 4868:         $config{'Qoff'}=$config[9];
 4869:         $config{'Qon'}=$config[10];
 4870:         $config{'PaperID'}=$config[11];
 4871:         $config{'PaperIDlength'}=$config[12];
 4872:         $config{'FirstName'}=$config[13];
 4873:         $config{'FirstNamelength'}=$config[14];
 4874:         $config{'LastName'}=$config[15];
 4875:         $config{'LastNamelength'}=$config[16];
 4876:         $config{'BubblesPerRow'}=$config[17];
 4877:         last;
 4878:     }
 4879:     return %config;
 4880: }
 4881: 
 4882: sub get_scantronformat_file {
 4883:     my ($cdom) = @_;
 4884:     if ($cdom eq '') {
 4885:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4886:     }
 4887:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4888:     my $gottab = 0;
 4889:     my @lines;
 4890:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4891:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4892:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4893:             if ($formatfile ne '-1') {
 4894:                 @lines = split("\n",$formatfile,-1);
 4895:                 $gottab = 1;
 4896:             }
 4897:         }
 4898:     }
 4899:     if (!$gottab) {
 4900:         my $confname = $cdom.'-domainconfig';
 4901:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4902:         my $formatfile = &getfile($default);
 4903:         if ($formatfile ne '-1') {
 4904:             @lines = split("\n",$formatfile,-1);
 4905:             $gottab = 1;
 4906:         }
 4907:     }
 4908:     if (!$gottab) {
 4909:         my @domains = &current_machine_domains();
 4910:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4911:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4912:                 @lines = <$fh>;
 4913:                 close($fh);
 4914:             }
 4915:         } else {
 4916:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4917:                 @lines = <$fh>;
 4918:                 close($fh);
 4919:             }
 4920:         }
 4921:         chomp(@lines);
 4922:     }
 4923:     return @lines;
 4924: }
 4925: 
 4926: sub removeuploadedurl {
 4927:     my ($url)=@_;	
 4928:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4929:     return &removeuserfile($uname,$udom,$fname);
 4930: }
 4931: 
 4932: sub removeuserfile {
 4933:     my ($docuname,$docudom,$fname)=@_;
 4934:     my $home=&homeserver($docuname,$docudom);    
 4935:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4936:     if ($result eq 'ok') {	
 4937:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4938:             my $metafile = $fname.'.meta';
 4939:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4940: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4941:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4942:             my $sqlresult = 
 4943:                 &update_portfolio_table($docuname,$docudom,$file,
 4944:                                         'portfolio_metadata',$group,
 4945:                                         'delete');
 4946:         }
 4947:     }
 4948:     return $result;
 4949: }
 4950: 
 4951: sub mkdiruserfile {
 4952:     my ($docuname,$docudom,$dir)=@_;
 4953:     my $home=&homeserver($docuname,$docudom);
 4954:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4955: }
 4956: 
 4957: sub renameuserfile {
 4958:     my ($docuname,$docudom,$old,$new)=@_;
 4959:     my $home=&homeserver($docuname,$docudom);
 4960:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4961:                         &escape("$old").':'.&escape("$new"),$home);
 4962:     if ($result eq 'ok') {
 4963:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4964:             my $oldmeta = $old.'.meta';
 4965:             my $newmeta = $new.'.meta';
 4966:             my $metaresult = 
 4967:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4968: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4969:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4970:             my $sqlresult = 
 4971:                 &update_portfolio_table($docuname,$docudom,$file,
 4972:                                         'portfolio_metadata',$group,
 4973:                                         'delete');
 4974:         }
 4975:     }
 4976:     return $result;
 4977: }
 4978: 
 4979: # ------------------------------------------------------------------------- Log
 4980: 
 4981: sub log {
 4982:     my ($dom,$nam,$hom,$what)=@_;
 4983:     return critical("log:$dom:$nam:$what",$hom);
 4984: }
 4985: 
 4986: # ------------------------------------------------------------------ Course Log
 4987: #
 4988: # This routine flushes several buffers of non-mission-critical nature
 4989: #
 4990: 
 4991: sub flushcourselogs {
 4992:     &logthis('Flushing log buffers');
 4993: #
 4994: # course logs
 4995: # This is a log of all transactions in a course, which can be used
 4996: # for data mining purposes
 4997: #
 4998: # It also collects the courseid database, which lists last transaction
 4999: # times and course titles for all courseids
 5000: #
 5001:     my %courseidbuffer=();
 5002:     foreach my $crsid (keys(%courselogs)) {
 5003:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5004: 		          &escape($courselogs{$crsid}),
 5005: 		          $coursehombuf{$crsid}) eq 'ok') {
 5006: 	    delete $courselogs{$crsid};
 5007:         } else {
 5008:             &logthis('Failed to flush log buffer for '.$crsid);
 5009:             if (length($courselogs{$crsid})>40000) {
 5010:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5011:                         " exceeded maximum size, deleting.</font>");
 5012:                delete $courselogs{$crsid};
 5013:             }
 5014:         }
 5015:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5016:             'description' => $coursedescrbuf{$crsid},
 5017:             'inst_code'    => $courseinstcodebuf{$crsid},
 5018:             'type'        => $coursetypebuf{$crsid},
 5019:             'owner'       => $courseownerbuf{$crsid},
 5020:         };
 5021:     }
 5022: #
 5023: # Write course id database (reverse lookup) to homeserver of courses 
 5024: # Is used in pickcourse
 5025: #
 5026:     foreach my $crs_home (keys(%courseidbuffer)) {
 5027:         my $response = &courseidput(&host_domain($crs_home),
 5028:                                     $courseidbuffer{$crs_home},
 5029:                                     $crs_home,'timeonly');
 5030:     }
 5031: #
 5032: # File accesses
 5033: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5034: #
 5035:     foreach my $entry (keys(%accesshash)) {
 5036:         if ($entry =~ /___count$/) {
 5037:             my ($dom,$name);
 5038:             ($dom,$name,undef)=
 5039: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5040:             if (! defined($dom) || $dom eq '' || 
 5041:                 ! defined($name) || $name eq '') {
 5042:                 my $cid = $env{'request.course.id'};
 5043: #
 5044: # FIXME 11/29/2021
 5045: # Typo in rev. 1.458 (2003/12/09)??
 5046: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5047: #
 5048: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5049: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5050: # in a nohist_accesscount.db file for the user rather than the course.
 5051: #
 5052: # That said there is a lot of noise in the data being stored.
 5053: # So counts for prtspool/  and adm/ etc. are recorded.
 5054: #
 5055: # A review of which items ending '___count' are written to %accesshash should likely be 
 5056: # made before deciding whether to set these to 'course.' instead of 'request.'
 5057: #
 5058: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5059: # accesses for things which are not published resources, regardless of course, and
 5060: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5061: # anyone in the course for things which are not published resources.
 5062: #
 5063: # For an author, nohist_accesscount.db ends up having records for other items
 5064: # mixed up with the legitimate access counts for the author's published resources.
 5065: #
 5066:                 $dom  = $env{'request.'.$cid.'.domain'};
 5067:                 $name = $env{'request.'.$cid.'.num'};
 5068:             }
 5069:             my $value = $accesshash{$entry};
 5070:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5071:             my %temphash=($url => $value);
 5072:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5073:             if ($result eq 'ok') {
 5074:                 delete $accesshash{$entry};
 5075:             }
 5076:         } else {
 5077:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5078:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5079:             my %temphash=($entry => $accesshash{$entry});
 5080:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5081:                 delete $accesshash{$entry};
 5082:             }
 5083:         }
 5084:     }
 5085: #
 5086: # Roles
 5087: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5088: #
 5089:     foreach my $entry (keys(%userrolehash)) {
 5090:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5091: 	    split(/\:/,$entry);
 5092:         if (&Apache::lonnet::put('nohist_userroles',
 5093:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5094:                 $rudom,$runame) eq 'ok') {
 5095: 	    delete $userrolehash{$entry};
 5096:         }
 5097:     }
 5098: #
 5099: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5100: #
 5101:     my %domrolebuffer = ();
 5102:     foreach my $entry (keys(%domainrolehash)) {
 5103:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5104:         if ($domrolebuffer{$rudom}) {
 5105:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5106:                       '='.&escape($domainrolehash{$entry});
 5107:         } else {
 5108:             $domrolebuffer{$rudom}.=&escape($entry).
 5109:                       '='.&escape($domainrolehash{$entry});
 5110:         }
 5111:         delete $domainrolehash{$entry};
 5112:     }
 5113:     foreach my $dom (keys(%domrolebuffer)) {
 5114: 	my %servers;
 5115: 	if (defined(&domain($dom,'primary'))) {
 5116: 	    my $primary=&domain($dom,'primary');
 5117: 	    my $hostname=&hostname($primary);
 5118: 	    $servers{$primary} = $hostname;
 5119: 	} else { 
 5120: 	    %servers = &get_servers($dom,'library');
 5121: 	}
 5122: 	foreach my $tryserver (keys(%servers)) {
 5123: 	    if (&reply('domroleput:'.$dom.':'.
 5124: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5125: 		last;
 5126: 	    } else {  
 5127: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5128: 	    }
 5129:         }
 5130:     }
 5131:     $dumpcount++;
 5132: }
 5133: 
 5134: sub courselog {
 5135:     my $what=shift;
 5136:     $what=time.':'.$what;
 5137:     unless ($env{'request.course.id'}) { return ''; }
 5138:     $coursedombuf{$env{'request.course.id'}}=
 5139:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5140:     $coursenumbuf{$env{'request.course.id'}}=
 5141:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5142:     $coursehombuf{$env{'request.course.id'}}=
 5143:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5144:     $coursedescrbuf{$env{'request.course.id'}}=
 5145:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5146:     $courseinstcodebuf{$env{'request.course.id'}}=
 5147:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5148:     $courseownerbuf{$env{'request.course.id'}}=
 5149:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5150:     $coursetypebuf{$env{'request.course.id'}}=
 5151:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5152:     if (defined $courselogs{$env{'request.course.id'}}) {
 5153: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5154:     } else {
 5155: 	$courselogs{$env{'request.course.id'}}.=$what;
 5156:     }
 5157:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5158: 	&flushcourselogs();
 5159:     }
 5160: }
 5161: 
 5162: sub courseacclog {
 5163:     my $fnsymb=shift;
 5164:     unless ($env{'request.course.id'}) { return ''; }
 5165:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5166:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5167:         $what.=':POST';
 5168:         # FIXME: Probably ought to escape things....
 5169: 	foreach my $key (keys(%env)) {
 5170:             if ($key=~/^form\.(.*)/) {
 5171:                 my $formitem = $1;
 5172:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5173:                     $what.=':'.$formitem.'='.$env{$key};
 5174:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5175:                     if ($formitem eq 'proctorpassword') {
 5176:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5177:                     } else {
 5178:                         $what.=':'.$formitem.'='.$env{$key};
 5179:                     }
 5180:                 }
 5181:             }
 5182:         }
 5183:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5184:         # FIXME: We should not be depending on a form parameter that someone
 5185:         # editing lonsearchcat.pm might change in the future.
 5186:         if ($env{'form.phase'} eq 'course_search') {
 5187:             $what.= ':POST';
 5188:             # FIXME: Probably ought to escape things....
 5189:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5190:                                  'crsdiscuss') {
 5191:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5192:             }
 5193:         }
 5194:     }
 5195:     &courselog($what);
 5196: }
 5197: 
 5198: sub countacc {
 5199:     my $url=&declutter(shift);
 5200:     return if (! defined($url) || $url eq '');
 5201:     unless ($env{'request.course.id'}) { return ''; }
 5202: #
 5203: # Mark that this url was used in this course
 5204: #
 5205:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5206: #
 5207: # Increase the access count for this resource in this child process
 5208: #
 5209:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5210:     $accesshash{$key}++;
 5211: }
 5212: 
 5213: sub linklog {
 5214:     my ($from,$to)=@_;
 5215:     $from=&declutter($from);
 5216:     $to=&declutter($to);
 5217:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5218:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5219: }
 5220: 
 5221: sub statslog {
 5222:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5223:     if ($users<2) { return; }
 5224:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5225:             'course'       => $env{'request.course.id'},
 5226:             'sections'     => '"all"',
 5227:             'num_students' => $users,
 5228:             'part'         => $part,
 5229:             'symb'         => $symb,
 5230:             'mean_tries'   => $av_attempts,
 5231:             'deg_of_diff'  => $degdiff});
 5232:     foreach my $key (keys(%dynstore)) {
 5233:         $accesshash{$key}=$dynstore{$key};
 5234:     }
 5235: }
 5236:   
 5237: sub userrolelog {
 5238:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5239:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5240:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5241:        $userrolehash
 5242:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5243:                     =$tend.':'.$tstart;
 5244:     }
 5245:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5246:        $userrolehash
 5247:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5248:                     =$tend.':'.$tstart;
 5249:     }
 5250:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5251:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5252:        $domainrolehash
 5253:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5254:                     = $tend.':'.$tstart;
 5255:     }
 5256: }
 5257: 
 5258: sub courserolelog {
 5259:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5260:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5261:         my $cdom = $1;
 5262:         my $cnum = $2;
 5263:         my $sec = $3;
 5264:         my $namespace = 'rolelog';
 5265:         my %storehash = (
 5266:                            role    => $trole,
 5267:                            start   => $tstart,
 5268:                            end     => $tend,
 5269:                            selfenroll => $selfenroll,
 5270:                            context    => $context,
 5271:                         );
 5272:         if ($trole eq 'gr') {
 5273:             $namespace = 'groupslog';
 5274:             $storehash{'group'} = $sec;
 5275:         } else {
 5276:             $storehash{'section'} = $sec;
 5277:         }
 5278:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5279:                    $domain,$cnum,$cdom);
 5280:         if (($trole ne 'st') || ($sec ne '')) {
 5281:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5282:         }
 5283:     }
 5284:     return;
 5285: }
 5286: 
 5287: sub domainrolelog {
 5288:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5289:     if ($area =~ m{^/($match_domain)/$}) {
 5290:         my $cdom = $1;
 5291:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5292:         my $namespace = 'rolelog';
 5293:         my %storehash = (
 5294:                            role    => $trole,
 5295:                            start   => $tstart,
 5296:                            end     => $tend,
 5297:                            context => $context,
 5298:                         );
 5299:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5300:                    $domain,$domconfiguser,$cdom);
 5301:     }
 5302:     return;
 5303: 
 5304: }
 5305: 
 5306: sub coauthorrolelog {
 5307:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5308:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5309:         my $audom = $1;
 5310:         my $auname = $2;
 5311:         my $namespace = 'rolelog';
 5312:         my %storehash = (
 5313:                            role    => $trole,
 5314:                            start   => $tstart,
 5315:                            end     => $tend,
 5316:                            context => $context,
 5317:                         );
 5318:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5319:                    $domain,$auname,$audom);
 5320:     }
 5321:     return;
 5322: }
 5323: 
 5324: sub get_course_adv_roles {
 5325:     my ($cid,$codes) = @_;
 5326:     $cid=$env{'request.course.id'} unless (defined($cid));
 5327:     my %coursehash=&coursedescription($cid);
 5328:     my $crstype = &Apache::loncommon::course_type($cid);
 5329:     my %nothide=();
 5330:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5331:         if ($user !~ /:/) {
 5332: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5333:         } else {
 5334:             $nothide{$user}=1;
 5335:         }
 5336:     }
 5337:     my @possdoms = ($coursehash{'domain'});
 5338:     if ($coursehash{'checkforpriv'}) {
 5339:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5340:     }
 5341:     my %returnhash=();
 5342:     my %dumphash=
 5343:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5344:     my $now=time;
 5345:     my %privileged;
 5346:     foreach my $entry (keys(%dumphash)) {
 5347: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5348:         if (($tstart) && ($tstart<0)) { next; }
 5349:         if (($tend) && ($tend<$now)) { next; }
 5350:         if (($tstart) && ($now<$tstart)) { next; }
 5351:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5352: 	if ($username eq '' || $domain eq '') { next; }
 5353:         if ((&privileged($username,$domain,\@possdoms)) &&
 5354:             (!$nothide{$username.':'.$domain})) { next; }
 5355: 	if ($role eq 'cr') { next; }
 5356:         if ($codes) {
 5357:             if ($section) { $role .= ':'.$section; }
 5358:             if ($returnhash{$role}) {
 5359:                 $returnhash{$role}.=','.$username.':'.$domain;
 5360:             } else {
 5361:                 $returnhash{$role}=$username.':'.$domain;
 5362:             }
 5363:         } else {
 5364:             my $key=&plaintext($role,$crstype);
 5365:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5366:             if ($returnhash{$key}) {
 5367: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5368:             } else {
 5369:                 $returnhash{$key}=$username.':'.$domain;
 5370:             }
 5371:         }
 5372:     }
 5373:     return %returnhash;
 5374: }
 5375: 
 5376: sub get_my_roles {
 5377:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5378:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5379:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5380:     my (%dumphash,%nothide);
 5381:     if ($context eq 'userroles') {
 5382:         %dumphash = &dump('roles',$udom,$uname);
 5383:     } else {
 5384:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5385:         if ($hidepriv) {
 5386:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5387:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5388:                 if ($user !~ /:/) {
 5389:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5390:                 } else {
 5391:                     $nothide{$user} = 1;
 5392:                 }
 5393:             }
 5394:         }
 5395:     }
 5396:     my %returnhash=();
 5397:     my $now=time;
 5398:     my %privileged;
 5399:     foreach my $entry (keys(%dumphash)) {
 5400:         my ($role,$tend,$tstart);
 5401:         if ($context eq 'userroles') {
 5402:             next if ($entry =~ /^rolesdef/);
 5403: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5404:         } else {
 5405:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5406:         }
 5407:         if (($tstart) && ($tstart<0)) { next; }
 5408:         my $status = 'active';
 5409:         if (($tend) && ($tend<=$now)) {
 5410:             $status = 'previous';
 5411:         } 
 5412:         if (($tstart) && ($now<$tstart)) {
 5413:             $status = 'future';
 5414:         }
 5415:         if (ref($types) eq 'ARRAY') {
 5416:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5417:                 next;
 5418:             } 
 5419:         } else {
 5420:             if ($status ne 'active') {
 5421:                 next;
 5422:             }
 5423:         }
 5424:         my ($rolecode,$username,$domain,$section,$area);
 5425:         if ($context eq 'userroles') {
 5426:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5427:             (undef,$domain,$username,$section) = split(/\//,$area);
 5428:         } else {
 5429:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5430:         }
 5431:         if (ref($roledoms) eq 'ARRAY') {
 5432:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5433:                 next;
 5434:             }
 5435:         }
 5436:         if (ref($roles) eq 'ARRAY') {
 5437:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5438:                 if ($role =~ /^cr\//) {
 5439:                     if (!grep(/^cr$/,@{$roles})) {
 5440:                         next;
 5441:                     }
 5442:                 } elsif ($role =~ /^gr\//) {
 5443:                     if (!grep(/^gr$/,@{$roles})) {
 5444:                         next;
 5445:                     }
 5446:                 } else {
 5447:                     next;
 5448:                 }
 5449:             }
 5450:         }
 5451:         if ($hidepriv) {
 5452:             my @privroles = ('dc','su');
 5453:             if ($context eq 'userroles') {
 5454:                 next if (grep(/^\Q$role\E$/,@privroles));
 5455:             } else {
 5456:                 my $possdoms = [$domain];
 5457:                 if (ref($roledoms) eq 'ARRAY') {
 5458:                    push(@{$possdoms},@{$roledoms}); 
 5459:                 }
 5460:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5461:                     if (!$nothide{$username.':'.$domain}) {
 5462:                         next;
 5463:                     }
 5464:                 }
 5465:             }
 5466:         }
 5467:         if ($withsec) {
 5468:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5469:                 $tstart.':'.$tend;
 5470:         } else {
 5471:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5472:         }
 5473:     }
 5474:     return %returnhash;
 5475: }
 5476: 
 5477: sub get_all_adhocroles {
 5478:     my ($dom) = @_;
 5479:     my @roles_by_num = ();
 5480:     my %domdefaults = &get_domain_defaults($dom);
 5481:     my (%description,%access_in_dom,%access_info);
 5482:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5483:         my $count = 0;
 5484:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5485:         my %ordered;
 5486:         foreach my $role (sort(keys(%domcurrent))) {
 5487:             my ($order,$desc,$access_in_dom);
 5488:             if (ref($domcurrent{$role}) eq 'HASH') {
 5489:                 $order = $domcurrent{$role}{'order'};
 5490:                 $desc = $domcurrent{$role}{'desc'};
 5491:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5492:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5493:             }
 5494:             if ($order eq '') {
 5495:                 $order = $count;
 5496:             }
 5497:             $ordered{$order} = $role;
 5498:             if ($desc ne '') {
 5499:                 $description{$role} = $desc;
 5500:             } else {
 5501:                 $description{$role}= $role;
 5502:             }
 5503:             $count++;
 5504:         }
 5505:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5506:             push(@roles_by_num,$ordered{$item});
 5507:         }
 5508:     }
 5509:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5510: }
 5511: 
 5512: sub get_my_adhocroles {
 5513:     my ($cid,$checkreg) = @_;
 5514:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5515:     if ($env{'request.course.id'} eq $cid) {
 5516:         $cdom = $env{'course.'.$cid.'.domain'};
 5517:         $cnum = $env{'course.'.$cid.'.num'};
 5518:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5519:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5520:         $cdom = $1;
 5521:         $cnum = $2;
 5522:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5523:                                      $cdom,$cnum);
 5524:     }
 5525:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5526:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5527:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5528:         if ($rosterhash{$user} ne '') {
 5529:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5530:             return ([],{}) if ($type eq 'auto');
 5531:         }
 5532:     }
 5533:     if (($cdom ne '') && ($cnum ne ''))  {
 5534:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5535:             my $then=$env{'user.login.time'};
 5536:             my $update=$env{'user.update.time'};
 5537:             if (!$update) {
 5538:                 $update = $then;
 5539:             }
 5540:             my @liveroles;
 5541:             foreach my $role ('dh','da') {
 5542:                 if ($env{"user.role.$role./$cdom/"}) {
 5543:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5544:                     my $limit = $update;
 5545:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5546:                         $limit = $then;
 5547:                     }
 5548:                     my $activerole = 1;
 5549:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5550:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5551:                     if ($activerole) {
 5552:                         push(@liveroles,$role);
 5553:                     }
 5554:                 }
 5555:             }
 5556:             if (@liveroles) {
 5557:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5558:                     my ($accessref,$accessinfo,%access_in_dom);
 5559:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5560:                     if (ref($roles_by_num) eq 'ARRAY') {
 5561:                         if (@{$roles_by_num}) {
 5562:                             my %settings;
 5563:                             if ($env{'request.course.id'} eq $cid) {
 5564:                                 foreach my $envkey (keys(%env)) {
 5565:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5566:                                         $settings{$1} = $env{$envkey};
 5567:                                     }
 5568:                                 }
 5569:                             } else {
 5570:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5571:                             }
 5572:                             my %setincrs;
 5573:                             if ($settings{'internal.adhocaccess'}) {
 5574:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5575:                             }
 5576:                             my @statuses;
 5577:                             if ($env{'environment.inststatus'}) {
 5578:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5579:                             }
 5580:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5581:                             if (ref($accessref) eq 'HASH') {
 5582:                                 %access_in_dom = %{$accessref};
 5583:                             }
 5584:                             foreach my $role (@{$roles_by_num}) {
 5585:                                 my ($curraccess,@okstatus,@personnel);
 5586:                                 if ($setincrs{$role}) {
 5587:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5588:                                     if ($curraccess eq 'status') {
 5589:                                         @okstatus = split(/\&/,$rest);
 5590:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5591:                                         @personnel = split(/\&/,$rest);
 5592:                                     }
 5593:                                 } else {
 5594:                                     $curraccess = $access_in_dom{$role};
 5595:                                     if (ref($accessinfo) eq 'HASH') {
 5596:                                         if ($curraccess eq 'status') {
 5597:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5598:                                                 @okstatus = @{$accessinfo->{$role}};
 5599:                                             }
 5600:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5601:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5602:                                                 @personnel = @{$accessinfo->{$role}};
 5603:                                             }
 5604:                                         }
 5605:                                     }
 5606:                                 }
 5607:                                 if ($curraccess eq 'none') {
 5608:                                     next;
 5609:                                 } elsif ($curraccess eq 'all') {
 5610:                                     push(@possroles,$role);
 5611:                                 } elsif ($curraccess eq 'dh') {
 5612:                                     if (grep(/^dh$/,@liveroles)) {
 5613:                                         push(@possroles,$role);
 5614:                                     } else {
 5615:                                         next;
 5616:                                     }
 5617:                                 } elsif ($curraccess eq 'da') {
 5618:                                     if (grep(/^da$/,@liveroles)) {
 5619:                                         push(@possroles,$role);
 5620:                                     } else {
 5621:                                         next;
 5622:                                     }
 5623:                                 } elsif ($curraccess eq 'status') {
 5624:                                     if (@okstatus) {
 5625:                                         if (!@statuses) {
 5626:                                             if (grep(/^default$/,@okstatus)) {
 5627:                                                 push(@possroles,$role);
 5628:                                             }
 5629:                                         } else {
 5630:                                             foreach my $status (@okstatus) {
 5631:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5632:                                                     push(@possroles,$role);
 5633:                                                     last;
 5634:                                                 }
 5635:                                             }
 5636:                                         }
 5637:                                     }
 5638:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5639:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5640:                                         if ($curraccess eq 'exc') {
 5641:                                             push(@possroles,$role);
 5642:                                         }
 5643:                                     } elsif ($curraccess eq 'inc') {
 5644:                                         push(@possroles,$role);
 5645:                                     }
 5646:                                 }
 5647:                             }
 5648:                         }
 5649:                     }
 5650:                 }
 5651:             }
 5652:         }
 5653:     }
 5654:     unless (ref($description) eq 'HASH') {
 5655:         if (ref($roles_by_num) eq 'ARRAY') {
 5656:             my %desc;
 5657:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5658:             $description = \%desc;
 5659:         } else {
 5660:             $description = {};
 5661:         }
 5662:     }
 5663:     return (\@possroles,$description);
 5664: }
 5665: 
 5666: # ----------------------------------------------------- Frontpage Announcements
 5667: #
 5668: #
 5669: 
 5670: sub postannounce {
 5671:     my ($server,$text)=@_;
 5672:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5673:     unless ($text=~/\w/) { $text=''; }
 5674:     return &reply('setannounce:'.&escape($text),$server);
 5675: }
 5676: 
 5677: sub getannounce {
 5678: 
 5679:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5680: 	my $announcement='';
 5681: 	while (my $line = <$fh>) { $announcement .= $line; }
 5682: 	close($fh);
 5683: 	if ($announcement=~/\w/) { 
 5684: 	    return 
 5685:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5686:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5687: 	} else {
 5688: 	    return '';
 5689: 	}
 5690:     } else {
 5691: 	return '';
 5692:     }
 5693: }
 5694: 
 5695: # ---------------------------------------------------------- Course ID routines
 5696: # Deal with domain's nohist_courseid.db files
 5697: #
 5698: 
 5699: sub courseidput {
 5700:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5701:     return unless (ref($storehash) eq 'HASH');
 5702:     my $outcome;
 5703:     if ($caller eq 'timeonly') {
 5704:         my $cids = '';
 5705:         foreach my $item (keys(%$storehash)) {
 5706:             $cids.=&escape($item).'&';
 5707:         }
 5708:         $cids=~s/\&$//;
 5709:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5710:                           $coursehome);       
 5711:     } else {
 5712:         my $items = '';
 5713:         foreach my $item (keys(%$storehash)) {
 5714:             $items.= &escape($item).'='.
 5715:                      &freeze_escape($$storehash{$item}).'&';
 5716:         }
 5717:         $items=~s/\&$//;
 5718:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5719:                           $coursehome);
 5720:     }
 5721:     if ($outcome eq 'unknown_cmd') {
 5722:         my $what;
 5723:         foreach my $cid (keys(%$storehash)) {
 5724:             $what .= &escape($cid).'=';
 5725:             foreach my $item ('description','inst_code','owner','type') {
 5726:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5727:             }
 5728:             $what =~ s/\:$/&/;
 5729:         }
 5730:         $what =~ s/\&$//;  
 5731:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5732:     } else {
 5733:         return $outcome;
 5734:     }
 5735: }
 5736: 
 5737: sub courseiddump {
 5738:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5739:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5740:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5741:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5742:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5743:     my $as_hash = 1;
 5744:     my %returnhash;
 5745:     if (!$domfilter) { $domfilter=''; }
 5746:     my %libserv = &all_library();
 5747:     foreach my $tryserver (keys(%libserv)) {
 5748:         if ( (  $hostidflag == 1 
 5749: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5750: 	     || (!defined($hostidflag)) ) {
 5751: 
 5752: 	    if (($domfilter eq '') ||
 5753: 		(&host_domain($tryserver) eq $domfilter)) {
 5754:                 my $rep;
 5755:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5756:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5757:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5758:                                 &escape($descfilter), &escape($instcodefilter), 
 5759:                                 &escape($ownerfilter), &escape($coursefilter),
 5760:                                 &escape($typefilter), &escape($regexp_ok), 
 5761:                                 $as_hash, &escape($selfenrollonly), 
 5762:                                 &escape($catfilter), $showhidden, $caller, 
 5763:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5764:                                 &escape($createdbefore), &escape($createdafter), 
 5765:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5766:                                 $reqcrsdom,&escape($reqinstcode))));
 5767:                 } else {
 5768:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5769:                              $sincefilter.':'.&escape($descfilter).':'.
 5770:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5771:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5772:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5773:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5774:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5775:                              &escape($cc_clone).':'.$cloneonly.':'.
 5776:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5777:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5778:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5779:                 }
 5780:                      
 5781:                 my @pairs=split(/\&/,$rep);
 5782:                 foreach my $item (@pairs) {
 5783:                     my ($key,$value)=split(/\=/,$item,2);
 5784:                     $key = &unescape($key);
 5785:                     next if ($key =~ /^error: 2 /);
 5786:                     my $result = &thaw_unescape($value);
 5787:                     if (ref($result) eq 'HASH') {
 5788:                         $returnhash{$key}=$result;
 5789:                     } else {
 5790:                         my @responses = split(/:/,$value);
 5791:                         my @items = ('description','inst_code','owner','type');
 5792:                         for (my $i=0; $i<@responses; $i++) {
 5793:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5794:                         }
 5795:                     }
 5796:                 }
 5797:             }
 5798:         }
 5799:     }
 5800:     return %returnhash;
 5801: }
 5802: 
 5803: sub courselastaccess {
 5804:     my ($cdom,$cnum,$hostidref) = @_;
 5805:     my %returnhash;
 5806:     if ($cdom && $cnum) {
 5807:         my $chome = &homeserver($cnum,$cdom);
 5808:         if ($chome ne 'no_host') {
 5809:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5810:             &extract_lastaccess(\%returnhash,$rep);
 5811:         }
 5812:     } else {
 5813:         if (!$cdom) { $cdom=''; }
 5814:         my %libserv = &all_library();
 5815:         foreach my $tryserver (keys(%libserv)) {
 5816:             if (ref($hostidref) eq 'ARRAY') {
 5817:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5818:             } 
 5819:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5820:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5821:                 &extract_lastaccess(\%returnhash,$rep);
 5822:             }
 5823:         }
 5824:     }
 5825:     return %returnhash;
 5826: }
 5827: 
 5828: sub extract_lastaccess {
 5829:     my ($returnhash,$rep) = @_;
 5830:     if (ref($returnhash) eq 'HASH') {
 5831:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5832:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5833:                  $rep eq '') {
 5834:             my @pairs=split(/\&/,$rep);
 5835:             foreach my $item (@pairs) {
 5836:                 my ($key,$value)=split(/\=/,$item,2);
 5837:                 $key = &unescape($key);
 5838:                 next if ($key =~ /^error: 2 /);
 5839:                 $returnhash->{$key} = &thaw_unescape($value);
 5840:             }
 5841:         }
 5842:     }
 5843:     return;
 5844: }
 5845: 
 5846: # ---------------------------------------------------------- DC e-mail
 5847: 
 5848: sub dcmailput {
 5849:     my ($domain,$msgid,$message,$server)=@_;
 5850:     my $status = &Apache::lonnet::critical(
 5851:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5852:        &escape($message),$server);
 5853:     return $status;
 5854: }
 5855: 
 5856: sub dcmaildump {
 5857:     my ($dom,$startdate,$enddate,$senders) = @_;
 5858:     my %returnhash=();
 5859: 
 5860:     if (defined(&domain($dom,'primary'))) {
 5861:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5862:                                                          &escape($enddate).':';
 5863: 	my @esc_senders=map { &escape($_)} @$senders;
 5864: 	$cmd.=&escape(join('&',@esc_senders));
 5865: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5866:             my ($key,$value) = split(/\=/,$line,2);
 5867:             if (($key) && ($value)) {
 5868:                 $returnhash{&unescape($key)} = &unescape($value);
 5869:             }
 5870:         }
 5871:     }
 5872:     return %returnhash;
 5873: }
 5874: # ---------------------------------------------------------- Domain roles
 5875: 
 5876: sub get_domain_roles {
 5877:     my ($dom,$roles,$startdate,$enddate)=@_;
 5878:     if ((!defined($startdate)) || ($startdate eq '')) {
 5879:         $startdate = '.';
 5880:     }
 5881:     if ((!defined($enddate)) || ($enddate eq '')) {
 5882:         $enddate = '.';
 5883:     }
 5884:     my $rolelist;
 5885:     if (ref($roles) eq 'ARRAY') {
 5886:         $rolelist = join('&',@{$roles});
 5887:     }
 5888:     my %personnel = ();
 5889: 
 5890:     my %servers = &get_servers($dom,'library');
 5891:     foreach my $tryserver (keys(%servers)) {
 5892: 	%{$personnel{$tryserver}}=();
 5893: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5894: 					    &escape($startdate).':'.
 5895: 					    &escape($enddate).':'.
 5896: 					    &escape($rolelist), $tryserver))) {
 5897: 	    my ($key,$value) = split(/\=/,$line,2);
 5898: 	    if (($key) && ($value)) {
 5899: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5900: 	    }
 5901: 	}
 5902:     }
 5903:     return %personnel;
 5904: }
 5905: 
 5906: sub get_active_domroles {
 5907:     my ($dom,$roles) = @_;
 5908:     return () unless (ref($roles) eq 'ARRAY');
 5909:     my $now = time;
 5910:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5911:     my %domroles;
 5912:     foreach my $server (keys(%dompersonnel)) {
 5913:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5914:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5915:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5916:         }
 5917:     }
 5918:     return %domroles;
 5919: }
 5920: 
 5921: # ----------------------------------------------------------- Interval timing 
 5922: 
 5923: {
 5924: # Caches needed for speedup of navmaps
 5925: # We don't want to cache this for very long at all (5 seconds at most)
 5926: # 
 5927: # The user for whom we cache
 5928: my $cachedkey='';
 5929: # The cached times for this user
 5930: my %cachedtimes=();
 5931: # When this was last done
 5932: my $cachedtime='';
 5933: 
 5934: sub load_all_first_access {
 5935:     my ($uname,$udom,$ignorecache)=@_;
 5936:     if (($cachedkey eq $uname.':'.$udom) &&
 5937:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5938:         (!$ignorecache)) {
 5939:         return;
 5940:     }
 5941:     $cachedtime=time;
 5942:     $cachedkey=$uname.':'.$udom;
 5943:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5944: }
 5945: 
 5946: sub get_first_access {
 5947:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5948:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5949:     if ($argsymb) { $symb=$argsymb; }
 5950:     my ($map,$id,$res)=&decode_symb($symb);
 5951:     if ($argmap) { $map = $argmap; }
 5952:     if ($type eq 'course') {
 5953: 	$res='course';
 5954:     } elsif ($type eq 'map') {
 5955: 	$res=&symbread($map);
 5956:     } else {
 5957: 	$res=$symb;
 5958:     }
 5959:     &load_all_first_access($uname,$udom,$ignorecache);
 5960:     return $cachedtimes{"$courseid\0$res"};
 5961: }
 5962: 
 5963: sub set_first_access {
 5964:     my ($type,$interval)=@_;
 5965:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5966:     my ($map,$id,$res)=&decode_symb($symb);
 5967:     if ($type eq 'course') {
 5968: 	$res='course';
 5969:     } elsif ($type eq 'map') {
 5970: 	$res=&symbread($map);
 5971:     } else {
 5972: 	$res=$symb;
 5973:     }
 5974:     $cachedkey='';
 5975:     my $firstaccess=&get_first_access($type,$symb,$map);
 5976:     if ($firstaccess) {
 5977:         &logthis("First access time already set ($firstaccess) when attempting ".
 5978:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5979:                  "in $courseid");
 5980:         return 'already_set';
 5981:     } else {
 5982:         my $start = time;
 5983: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5984:                           $udom,$uname);
 5985:         if ($putres eq 'ok') {
 5986:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5987:                  $udom,$uname); 
 5988:             &appenv(
 5989:                      {
 5990:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5991:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5992:                      }
 5993:                   );
 5994:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5995:                 $cachedtimes{"$courseid\0$res"} = $start;
 5996:             }
 5997:         } elsif ($putres ne 'refused') {
 5998:             &logthis("Result: $putres when attempting to set first access time ".
 5999:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6000:         }
 6001:         return $putres;
 6002:     }
 6003:     return 'already_set';
 6004: }
 6005: }
 6006: 
 6007: # --------------------------------------------- Set Expire Date for Spreadsheet
 6008: 
 6009: sub expirespread {
 6010:     my ($uname,$udom,$stype,$usymb)=@_;
 6011:     my $cid=$env{'request.course.id'}; 
 6012:     if ($cid) {
 6013:        my $now=time;
 6014:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6015:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6016:                             $env{'course.'.$cid.'.num'}.
 6017: 	        	    ':nohist_expirationdates:'.
 6018:                             &escape($key).'='.$now,
 6019:                             $env{'course.'.$cid.'.home'})
 6020:     }
 6021:     return 'ok';
 6022: }
 6023: 
 6024: # ----------------------------------------------------- Devalidate Spreadsheets
 6025: 
 6026: sub devalidate {
 6027:     my ($symb,$uname,$udom)=@_;
 6028:     my $cid=$env{'request.course.id'}; 
 6029:     if ($cid) {
 6030:         # delete the stored spreadsheets for
 6031:         # - the student level sheet of this user in course's homespace
 6032:         # - the assessment level sheet for this resource 
 6033:         #   for this user in user's homespace
 6034: 	# - current conditional state info
 6035: 	my $key=$uname.':'.$udom.':';
 6036:         my $status=
 6037: 	    &del('nohist_calculatedsheets',
 6038: 		 [$key.'studentcalc:'],
 6039: 		 $env{'course.'.$cid.'.domain'},
 6040: 		 $env{'course.'.$cid.'.num'})
 6041: 		.' '.
 6042: 	    &del('nohist_calculatedsheets_'.$cid,
 6043: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6044:         unless ($status eq 'ok ok') {
 6045:            &logthis('Could not devalidate spreadsheet '.
 6046:                     $uname.' at '.$udom.' for '.
 6047: 		    $symb.': '.$status);
 6048:         }
 6049: 	&delenv('user.state.'.$cid);
 6050:     }
 6051: }
 6052: 
 6053: sub get_scalar {
 6054:     my ($string,$end) = @_;
 6055:     my $value;
 6056:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6057: 	$value = $1;
 6058:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6059: 	$value = $1;
 6060:     }
 6061:     return &unescape($value);
 6062: }
 6063: 
 6064: sub array2str {
 6065:   my (@array) = @_;
 6066:   my $result=&arrayref2str(\@array);
 6067:   $result=~s/^__ARRAY_REF__//;
 6068:   $result=~s/__END_ARRAY_REF__$//;
 6069:   return $result;
 6070: }
 6071: 
 6072: sub arrayref2str {
 6073:   my ($arrayref) = @_;
 6074:   my $result='__ARRAY_REF__';
 6075:   foreach my $elem (@$arrayref) {
 6076:     if(ref($elem) eq 'ARRAY') {
 6077:       $result.=&arrayref2str($elem).'&';
 6078:     } elsif(ref($elem) eq 'HASH') {
 6079:       $result.=&hashref2str($elem).'&';
 6080:     } elsif(ref($elem)) {
 6081:       #print("Got a ref of ".(ref($elem))." skipping.");
 6082:     } else {
 6083:       $result.=&escape($elem).'&';
 6084:     }
 6085:   }
 6086:   $result=~s/\&$//;
 6087:   $result .= '__END_ARRAY_REF__';
 6088:   return $result;
 6089: }
 6090: 
 6091: sub hash2str {
 6092:   my (%hash) = @_;
 6093:   my $result=&hashref2str(\%hash);
 6094:   $result=~s/^__HASH_REF__//;
 6095:   $result=~s/__END_HASH_REF__$//;
 6096:   return $result;
 6097: }
 6098: 
 6099: sub hashref2str {
 6100:   my ($hashref)=@_;
 6101:   my $result='__HASH_REF__';
 6102:   foreach my $key (sort(keys(%$hashref))) {
 6103:     if (ref($key) eq 'ARRAY') {
 6104:       $result.=&arrayref2str($key).'=';
 6105:     } elsif (ref($key) eq 'HASH') {
 6106:       $result.=&hashref2str($key).'=';
 6107:     } elsif (ref($key)) {
 6108:       $result.='=';
 6109:       #print("Got a ref of ".(ref($key))." skipping.");
 6110:     } else {
 6111: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6112:     }
 6113: 
 6114:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6115:       $result.=&arrayref2str($hashref->{$key}).'&';
 6116:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6117:       $result.=&hashref2str($hashref->{$key}).'&';
 6118:     } elsif(ref($hashref->{$key})) {
 6119:        $result.='&';
 6120:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6121:     } else {
 6122:       $result.=&escape($hashref->{$key}).'&';
 6123:     }
 6124:   }
 6125:   $result=~s/\&$//;
 6126:   $result .= '__END_HASH_REF__';
 6127:   return $result;
 6128: }
 6129: 
 6130: sub str2hash {
 6131:     my ($string)=@_;
 6132:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6133:     return %$hash;
 6134: }
 6135: 
 6136: sub str2hashref {
 6137:   my ($string) = @_;
 6138: 
 6139:   my %hash;
 6140: 
 6141:   if($string !~ /^__HASH_REF__/) {
 6142:       if (! ($string eq '' || !defined($string))) {
 6143: 	  $hash{'error'}='Not hash reference';
 6144:       }
 6145:       return (\%hash, $string);
 6146:   }
 6147: 
 6148:   $string =~ s/^__HASH_REF__//;
 6149: 
 6150:   while($string !~ /^__END_HASH_REF__/) {
 6151:       #key
 6152:       my $key='';
 6153:       if($string =~ /^__HASH_REF__/) {
 6154:           ($key, $string)=&str2hashref($string);
 6155:           if(defined($key->{'error'})) {
 6156:               $hash{'error'}='Bad data';
 6157:               return (\%hash, $string);
 6158:           }
 6159:       } elsif($string =~ /^__ARRAY_REF__/) {
 6160:           ($key, $string)=&str2arrayref($string);
 6161:           if($key->[0] eq 'Array reference error') {
 6162:               $hash{'error'}='Bad data';
 6163:               return (\%hash, $string);
 6164:           }
 6165:       } else {
 6166:           $string =~ s/^(.*?)=//;
 6167: 	  $key=&unescape($1);
 6168:       }
 6169:       $string =~ s/^=//;
 6170: 
 6171:       #value
 6172:       my $value='';
 6173:       if($string =~ /^__HASH_REF__/) {
 6174:           ($value, $string)=&str2hashref($string);
 6175:           if(defined($value->{'error'})) {
 6176:               $hash{'error'}='Bad data';
 6177:               return (\%hash, $string);
 6178:           }
 6179:       } elsif($string =~ /^__ARRAY_REF__/) {
 6180:           ($value, $string)=&str2arrayref($string);
 6181:           if($value->[0] eq 'Array reference error') {
 6182:               $hash{'error'}='Bad data';
 6183:               return (\%hash, $string);
 6184:           }
 6185:       } else {
 6186: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6187:       }
 6188:       $string =~ s/^&//;
 6189: 
 6190:       $hash{$key}=$value;
 6191:   }
 6192: 
 6193:   $string =~ s/^__END_HASH_REF__//;
 6194: 
 6195:   return (\%hash, $string);
 6196: }
 6197: 
 6198: sub str2array {
 6199:     my ($string)=@_;
 6200:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6201:     return @$array;
 6202: }
 6203: 
 6204: sub str2arrayref {
 6205:   my ($string) = @_;
 6206:   my @array;
 6207: 
 6208:   if($string !~ /^__ARRAY_REF__/) {
 6209:       if (! ($string eq '' || !defined($string))) {
 6210: 	  $array[0]='Array reference error';
 6211:       }
 6212:       return (\@array, $string);
 6213:   }
 6214: 
 6215:   $string =~ s/^__ARRAY_REF__//;
 6216: 
 6217:   while($string !~ /^__END_ARRAY_REF__/) {
 6218:       my $value='';
 6219:       if($string =~ /^__HASH_REF__/) {
 6220:           ($value, $string)=&str2hashref($string);
 6221:           if(defined($value->{'error'})) {
 6222:               $array[0] ='Array reference error';
 6223:               return (\@array, $string);
 6224:           }
 6225:       } elsif($string =~ /^__ARRAY_REF__/) {
 6226:           ($value, $string)=&str2arrayref($string);
 6227:           if($value->[0] eq 'Array reference error') {
 6228:               $array[0] ='Array reference error';
 6229:               return (\@array, $string);
 6230:           }
 6231:       } else {
 6232: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6233:       }
 6234:       $string =~ s/^&//;
 6235: 
 6236:       push(@array, $value);
 6237:   }
 6238: 
 6239:   $string =~ s/^__END_ARRAY_REF__//;
 6240: 
 6241:   return (\@array, $string);
 6242: }
 6243: 
 6244: # -------------------------------------------------------------------Temp Store
 6245: 
 6246: sub tmpreset {
 6247:   my ($symb,$namespace,$domain,$stuname) = @_;
 6248:   if (!$symb) {
 6249:     $symb=&symbread();
 6250:     if (!$symb) { $symb= $env{'request.url'}; }
 6251:   }
 6252:   $symb=escape($symb);
 6253: 
 6254:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6255:   $namespace=~s/\//\_/g;
 6256:   $namespace=~s/\W//g;
 6257: 
 6258:   if (!$domain) { $domain=$env{'user.domain'}; }
 6259:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6260:   if ($domain eq 'public' && $stuname eq 'public') {
 6261:       $stuname=&get_requestor_ip();
 6262:   }
 6263:   my $path=LONCAPA::tempdir();
 6264:   my %hash;
 6265:   if (tie(%hash,'GDBM_File',
 6266: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6267: 	  &GDBM_WRCREAT(),0640)) {
 6268:     foreach my $key (keys(%hash)) {
 6269:       if ($key=~ /:$symb/) {
 6270: 	delete($hash{$key});
 6271:       }
 6272:     }
 6273:   }
 6274: }
 6275: 
 6276: sub tmpstore {
 6277:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6278: 
 6279:   if (!$symb) {
 6280:     $symb=&symbread();
 6281:     if (!$symb) { $symb= $env{'request.url'}; }
 6282:   }
 6283:   $symb=escape($symb);
 6284: 
 6285:   if (!$namespace) {
 6286:     # I don't think we would ever want to store this for a course.
 6287:     # it seems this will only be used if we don't have a course.
 6288:     #$namespace=$env{'request.course.id'};
 6289:     #if (!$namespace) {
 6290:       $namespace=$env{'request.state'};
 6291:     #}
 6292:   }
 6293:   $namespace=~s/\//\_/g;
 6294:   $namespace=~s/\W//g;
 6295:   if (!$domain) { $domain=$env{'user.domain'}; }
 6296:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6297:   if ($domain eq 'public' && $stuname eq 'public') {
 6298:       $stuname=&get_requestor_ip();
 6299:   }
 6300:   my $now=time;
 6301:   my %hash;
 6302:   my $path=LONCAPA::tempdir();
 6303:   if (tie(%hash,'GDBM_File',
 6304: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6305: 	  &GDBM_WRCREAT(),0640)) {
 6306:     $hash{"version:$symb"}++;
 6307:     my $version=$hash{"version:$symb"};
 6308:     my $allkeys=''; 
 6309:     foreach my $key (keys(%$storehash)) {
 6310:       $allkeys.=$key.':';
 6311:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6312:     }
 6313:     $hash{"$version:$symb:timestamp"}=$now;
 6314:     $allkeys.='timestamp';
 6315:     $hash{"$version:keys:$symb"}=$allkeys;
 6316:     if (untie(%hash)) {
 6317:       return 'ok';
 6318:     } else {
 6319:       return "error:$!";
 6320:     }
 6321:   } else {
 6322:     return "error:$!";
 6323:   }
 6324: }
 6325: 
 6326: # -----------------------------------------------------------------Temp Restore
 6327: 
 6328: sub tmprestore {
 6329:   my ($symb,$namespace,$domain,$stuname) = @_;
 6330: 
 6331:   if (!$symb) {
 6332:     $symb=&symbread();
 6333:     if (!$symb) { $symb= $env{'request.url'}; }
 6334:   }
 6335:   $symb=escape($symb);
 6336: 
 6337:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6338: 
 6339:   if (!$domain) { $domain=$env{'user.domain'}; }
 6340:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6341:   if ($domain eq 'public' && $stuname eq 'public') {
 6342:       $stuname=&get_requestor_ip();
 6343:   }
 6344:   my %returnhash;
 6345:   $namespace=~s/\//\_/g;
 6346:   $namespace=~s/\W//g;
 6347:   my %hash;
 6348:   my $path=LONCAPA::tempdir();
 6349:   if (tie(%hash,'GDBM_File',
 6350: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6351: 	  &GDBM_READER(),0640)) {
 6352:     my $version=$hash{"version:$symb"};
 6353:     $returnhash{'version'}=$version;
 6354:     my $scope;
 6355:     for ($scope=1;$scope<=$version;$scope++) {
 6356:       my $vkeys=$hash{"$scope:keys:$symb"};
 6357:       my @keys=split(/:/,$vkeys);
 6358:       my $key;
 6359:       $returnhash{"$scope:keys"}=$vkeys;
 6360:       foreach $key (@keys) {
 6361: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6362: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6363:       }
 6364:     }
 6365:     if (!(untie(%hash))) {
 6366:       return "error:$!";
 6367:     }
 6368:   } else {
 6369:     return "error:$!";
 6370:   }
 6371:   return %returnhash;
 6372: }
 6373: 
 6374: # ----------------------------------------------------------------------- Store
 6375: 
 6376: sub store {
 6377:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6378:     my $home='';
 6379: 
 6380:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6381: 
 6382:     $symb=&symbclean($symb);
 6383:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6384: 
 6385:     if (!$domain) { $domain=$env{'user.domain'}; }
 6386:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6387: 
 6388:     &devalidate($symb,$stuname,$domain);
 6389: 
 6390:     $symb=escape($symb);
 6391:     if (!$namespace) { 
 6392:        unless ($namespace=$env{'request.course.id'}) { 
 6393:           return ''; 
 6394:        } 
 6395:     }
 6396:     if (!$home) { $home=$env{'user.home'}; }
 6397: 
 6398:     $$storehash{'ip'}=&get_requestor_ip();
 6399:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6400: 
 6401:     my $namevalue='';
 6402:     foreach my $key (keys(%$storehash)) {
 6403:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6404:     }
 6405:     $namevalue=~s/\&$//;
 6406:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6407:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6408: }
 6409: 
 6410: # -------------------------------------------------------------- Critical Store
 6411: 
 6412: sub cstore {
 6413:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6414:     my $home='';
 6415: 
 6416:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6417: 
 6418:     $symb=&symbclean($symb);
 6419:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6420: 
 6421:     if (!$domain) { $domain=$env{'user.domain'}; }
 6422:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6423: 
 6424:     &devalidate($symb,$stuname,$domain);
 6425: 
 6426:     $symb=escape($symb);
 6427:     if (!$namespace) { 
 6428:        unless ($namespace=$env{'request.course.id'}) { 
 6429:           return ''; 
 6430:        } 
 6431:     }
 6432:     if (!$home) { $home=$env{'user.home'}; }
 6433: 
 6434:     $$storehash{'ip'}=&get_requestor_ip();
 6435:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6436: 
 6437:     my $namevalue='';
 6438:     foreach my $key (keys(%$storehash)) {
 6439:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6440:     }
 6441:     $namevalue=~s/\&$//;
 6442:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6443:     return critical
 6444:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6445: }
 6446: 
 6447: # --------------------------------------------------------------------- Restore
 6448: 
 6449: sub restore {
 6450:     my ($symb,$namespace,$domain,$stuname) = @_;
 6451:     my $home='';
 6452: 
 6453:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6454: 
 6455:     if (!$symb) {
 6456:         return if ($namespace eq 'courserequests');
 6457:         unless ($symb=escape(&symbread())) { return ''; }
 6458:     } else {
 6459:         unless ($namespace eq 'courserequests') {
 6460:             $symb=&escape(&symbclean($symb));
 6461:         }
 6462:     }
 6463:     if (!$namespace) { 
 6464:        unless ($namespace=$env{'request.course.id'}) { 
 6465:           return ''; 
 6466:        } 
 6467:     }
 6468:     if (!$domain) { $domain=$env{'user.domain'}; }
 6469:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6470:     if (!$home) { $home=$env{'user.home'}; }
 6471:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6472: 
 6473:     my %returnhash=();
 6474:     foreach my $line (split(/\&/,$answer)) {
 6475: 	my ($name,$value)=split(/\=/,$line);
 6476:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6477:     }
 6478:     my $version;
 6479:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6480:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6481:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6482:        }
 6483:     }
 6484:     return %returnhash;
 6485: }
 6486: 
 6487: # ---------------------------------------------------------- Course Description
 6488: #
 6489: #  
 6490: 
 6491: sub coursedescription {
 6492:     my ($courseid,$args)=@_;
 6493:     $courseid=~s/^\///;
 6494:     $courseid=~s/\_/\//g;
 6495:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6496:     my $chome=&homeserver($cnum,$cdomain);
 6497:     my $normalid=$cdomain.'_'.$cnum;
 6498:     # need to always cache even if we get errors otherwise we keep 
 6499:     # trying and trying and trying to get the course description.
 6500:     my %envhash=();
 6501:     my %returnhash=();
 6502:     
 6503:     my $expiretime=600;
 6504:     if ($env{'request.course.id'} eq $normalid) {
 6505: 	$expiretime=120;
 6506:     }
 6507: 
 6508:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6509:     if (!$args->{'freshen_cache'}
 6510: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6511: 	foreach my $key (keys(%env)) {
 6512: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6513: 	    my ($setting) = $1;
 6514: 	    $returnhash{$setting} = $env{$key};
 6515: 	}
 6516: 	return %returnhash;
 6517:     }
 6518: 
 6519:     # get the data again
 6520: 
 6521:     if (!$args->{'one_time'}) {
 6522: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6523:     }
 6524: 
 6525:     if ($chome ne 'no_host') {
 6526:        %returnhash=&dump('environment',$cdomain,$cnum);
 6527:        if (!exists($returnhash{'con_lost'})) {
 6528: 	   my $username = $env{'user.name'}; # Defult username
 6529: 	   if(defined $args->{'user'}) {
 6530: 	       $username = $args->{'user'};
 6531: 	   }
 6532:            $returnhash{'home'}= $chome;
 6533: 	   $returnhash{'domain'} = $cdomain;
 6534: 	   $returnhash{'num'} = $cnum;
 6535:            if (!defined($returnhash{'type'})) {
 6536:                $returnhash{'type'} = 'Course';
 6537:            }
 6538:            while (my ($name,$value) = each %returnhash) {
 6539:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6540:            }
 6541:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6542:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6543: 	       $username.'_'.$cdomain.'_'.$cnum;
 6544:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6545:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6546:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6547:        }
 6548:     }
 6549:     if (!$args->{'one_time'}) {
 6550: 	&appenv(\%envhash);
 6551:     }
 6552:     return %returnhash;
 6553: }
 6554: 
 6555: sub update_released_required {
 6556:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6557:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6558:         $cid = $env{'request.course.id'};
 6559:         $cdom = $env{'course.'.$cid.'.domain'};
 6560:         $cnum = $env{'course.'.$cid.'.num'};
 6561:         $chome = $env{'course.'.$cid.'.home'};
 6562:     }
 6563:     if ($needsrelease) {
 6564:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6565:         my $needsupdate;
 6566:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6567:             $needsupdate = 1;
 6568:         } else {
 6569:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6570:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6571:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6572:                 $needsupdate = 1;
 6573:             }
 6574:         }
 6575:         if ($needsupdate) {
 6576:             my %needshash = (
 6577:                              'internal.releaserequired' => $needsrelease,
 6578:                             );
 6579:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6580:             if ($putresult eq 'ok') {
 6581:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6582:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6583:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6584:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6585:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6586:                 }
 6587:             }
 6588:         }
 6589:     }
 6590:     return;
 6591: }
 6592: 
 6593: # -------------------------------------------------See if a user is privileged
 6594: 
 6595: sub privileged {
 6596:     my ($username,$domain,$possdomains,$possroles)=@_;
 6597:     my $now = time;
 6598:     my $roles;
 6599:     if (ref($possroles) eq 'ARRAY') {
 6600:         $roles = $possroles; 
 6601:     } else {
 6602:         $roles = ['dc','su'];
 6603:     }
 6604:     if (ref($possdomains) eq 'ARRAY') {
 6605:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6606:         foreach my $dom (@{$possdomains}) {
 6607:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6608:                 (ref($privileged{$dom}) eq 'HASH')) {
 6609:                 foreach my $role (@{$roles}) {
 6610:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6611:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6612:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6613:                             return 1 unless (($end && $end < $now) ||
 6614:                                              ($start && $start > $now));
 6615:                         }
 6616:                     }
 6617:                 }
 6618:             }
 6619:         }
 6620:     } else {
 6621:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6622:         my $now = time;
 6623: 
 6624:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6625:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6626:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6627:                 return 1 unless ($tend && $tend < $now) 
 6628:                         or ($tstart && $tstart > $now);
 6629:             }
 6630:         }
 6631:     }
 6632:     return 0;
 6633: }
 6634: 
 6635: sub privileged_by_domain {
 6636:     my ($domains,$roles) = @_;
 6637:     my %privileged = ();
 6638:     my $cachetime = 60*60*24;
 6639:     my $now = time;
 6640:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6641:         return %privileged;
 6642:     }
 6643:     foreach my $dom (@{$domains}) {
 6644:         next if (ref($privileged{$dom}) eq 'HASH');
 6645:         my $needroles;
 6646:         foreach my $role (@{$roles}) {
 6647:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6648:             if (defined($cached)) {
 6649:                 if (ref($result) eq 'HASH') {
 6650:                     $privileged{$dom}{$role} = $result;
 6651:                 }
 6652:             } else {
 6653:                 $needroles = 1;
 6654:             }
 6655:         }
 6656:         if ($needroles) {
 6657:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6658:             $privileged{$dom} = {};
 6659:             foreach my $server (keys(%dompersonnel)) {
 6660:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6661:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6662:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6663:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6664:                         next if ($end && $end < $now);
 6665:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6666:                             $dompersonnel{$server}{$item};
 6667:                     }
 6668:                 }
 6669:             }
 6670:             if (ref($privileged{$dom}) eq 'HASH') {
 6671:                 foreach my $role (@{$roles}) {
 6672:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6673:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6674:                     } else {
 6675:                         my %hash = ();
 6676:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6677:                     }
 6678:                 }
 6679:             }
 6680:         }
 6681:     }
 6682:     return %privileged;
 6683: }
 6684: 
 6685: # -------------------------------------------------------- Get user privileges
 6686: 
 6687: sub rolesinit {
 6688:     my ($domain, $username) = @_;
 6689:     my %userroles = ('user.login.time' => time);
 6690:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6691: 
 6692:     # firstaccess and timerinterval are related to timed maps/resources. 
 6693:     # also, blocking can be triggered by an activating timer
 6694:     # it's saved in the user's %env.
 6695:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6696:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6697:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6698:         %timerintchk, %timerintenv);
 6699: 
 6700:     foreach my $key (keys(%firstaccess)) {
 6701:         my ($cid, $rest) = split(/\0/, $key);
 6702:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6703:     }
 6704: 
 6705:     foreach my $key (keys(%timerinterval)) {
 6706:         my ($cid,$rest) = split(/\0/,$key);
 6707:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6708:     }
 6709: 
 6710:     my %allroles=();
 6711:     my %allgroups=();
 6712: 
 6713:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6714:         my $role = $rolesdump{$area};
 6715:         $area =~ s/\_\w\w$//;
 6716: 
 6717:         my ($trole, $tend, $tstart, $group_privs);
 6718: 
 6719:         if ($role =~ /^cr/) {
 6720:         # Custom role, defined by a user 
 6721:         # e.g., user.role.cr/msu/smith/mynewrole
 6722:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6723:                 $trole = $1;
 6724:                 ($tend, $tstart) = split('_', $2);
 6725:             } else {
 6726:                 $trole = $role;
 6727:             }
 6728:         } elsif ($role =~ m|^gr/|) {
 6729:         # Role of member in a group, defined within a course/community
 6730:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6731:             ($trole, $tend, $tstart) = split(/_/, $role);
 6732:             next if $tstart eq '-1';
 6733:             ($trole, $group_privs) = split(/\//, $trole);
 6734:             $group_privs = &unescape($group_privs);
 6735:         } else {
 6736:         # Just a normal role, defined in roles.tab
 6737:             ($trole, $tend, $tstart) = split(/_/,$role);
 6738:         }
 6739: 
 6740:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6741:                  $username);
 6742:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6743: 
 6744:         # role expired or not available yet?
 6745:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6746:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6747: 
 6748:         next if $area eq '' or $trole eq '';
 6749: 
 6750:         my $spec = "$trole.$area";
 6751:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6752: 
 6753:         if ($trole =~ /^cr\//) {
 6754:         # Custom role, defined by a user
 6755:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6756:         } elsif ($trole eq 'gr') {
 6757:         # Role of a member in a group, defined within a course/community
 6758:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6759:             next;
 6760:         } else {
 6761:         # Normal role, defined in roles.tab
 6762:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6763:         }
 6764: 
 6765:         my $cid = $tdomain.'_'.$trest;
 6766:         unless ($firstaccchk{$cid}) {
 6767:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6768:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6769:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6770:                         $coursetimerstarts{$cid}{$item}; 
 6771:                 }
 6772:             }
 6773:             $firstaccchk{$cid} = 1;
 6774:         }
 6775:         unless ($timerintchk{$cid}) {
 6776:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6777:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6778:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6779:                        $coursetimerintervals{$cid}{$item};
 6780:                 }
 6781:             }
 6782:             $timerintchk{$cid} = 1;
 6783:         }
 6784:     }
 6785: 
 6786:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6787:                                                           \%allroles, \%allgroups);
 6788:     $env{'user.adv'} = $userroles{'user.adv'};
 6789:     $env{'user.rar'} = $userroles{'user.rar'};
 6790: 
 6791:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6792: }
 6793: 
 6794: sub set_arearole {
 6795:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6796:     unless ($nolog) {
 6797: # log the associated role with the area
 6798:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6799:     }
 6800:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6801: }
 6802: 
 6803: sub custom_roleprivs {
 6804:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6805:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6806:     my $homsvr = &homeserver($rauthor,$rdomain);
 6807:     if (&hostname($homsvr) ne '') {
 6808:         my ($rdummy,$roledef)=
 6809:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6810:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6811:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6812:             if (defined($syspriv)) {
 6813:                 if ($trest =~ /^$match_community$/) {
 6814:                     $syspriv =~ s/bre\&S//; 
 6815:                 }
 6816:                 $$allroles{'cm./'}.=':'.$syspriv;
 6817:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6818:             }
 6819:             if ($tdomain ne '') {
 6820:                 if (defined($dompriv)) {
 6821:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6822:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6823:                 }
 6824:                 if (($trest ne '') && (defined($coursepriv))) {
 6825:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6826:                         my $rolename = $1;
 6827:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6828:                     }
 6829:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6830:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6831:                 }
 6832:             }
 6833:         }
 6834:     }
 6835: }
 6836: 
 6837: sub course_adhocrole_privs {
 6838:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6839:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6840:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6841:         my (%currprivs,%storeprivs);
 6842:         foreach my $item (split(/:/,$coursepriv)) {
 6843:             my ($priv,$restrict) = split(/\&/,$item);
 6844:             $currprivs{$priv} = $restrict;
 6845:         }
 6846:         my (%possadd,%possremove,%full);
 6847:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6848:             my ($priv,$restrict)=split(/\&/,$item);
 6849:             $full{$priv} = $restrict;
 6850:         }
 6851:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6852:              next if ($item eq '');
 6853:              my ($rule,$rest) = split(/=/,$item);
 6854:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6855:              foreach my $priv (split(/:/,$rest)) {
 6856:                  if ($priv ne '') {
 6857:                      if ($rule eq 'off') {
 6858:                          $possremove{$priv} = 1;
 6859:                      } else {
 6860:                          $possadd{$priv} = 1;
 6861:                      }
 6862:                  }
 6863:              }
 6864:          }
 6865:          foreach my $priv (sort(keys(%full))) {
 6866:              if (exists($currprivs{$priv})) {
 6867:                  unless (exists($possremove{$priv})) {
 6868:                      $storeprivs{$priv} = $currprivs{$priv};
 6869:                  }
 6870:              } elsif (exists($possadd{$priv})) {
 6871:                  $storeprivs{$priv} = $full{$priv};
 6872:              }
 6873:          }
 6874:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6875:      }
 6876:      return $coursepriv;
 6877: }
 6878: 
 6879: sub group_roleprivs {
 6880:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6881:     my $access = 1;
 6882:     my $now = time;
 6883:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6884:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6885:     if ($access) {
 6886:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6887:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6888:     }
 6889: }
 6890: 
 6891: sub standard_roleprivs {
 6892:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6893:     if (defined($pr{$trole.':s'})) {
 6894:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6895:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6896:     }
 6897:     if ($tdomain ne '') {
 6898:         if (defined($pr{$trole.':d'})) {
 6899:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6900:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6901:         }
 6902:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6903:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6904:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6905:         }
 6906:     }
 6907: }
 6908: 
 6909: sub set_userprivs {
 6910:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6911:     my $author=0;
 6912:     my $adv=0;
 6913:     my $rar=0;
 6914:     my %grouproles = ();
 6915:     if (keys(%{$allgroups}) > 0) {
 6916:         my @groupkeys; 
 6917:         foreach my $role (keys(%{$allroles})) {
 6918:             push(@groupkeys,$role);
 6919:         }
 6920:         if (ref($groups_roles) eq 'HASH') {
 6921:             foreach my $key (keys(%{$groups_roles})) {
 6922:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6923:                     push(@groupkeys,$key);
 6924:                 }
 6925:             }
 6926:         }
 6927:         if (@groupkeys > 0) {
 6928:             foreach my $role (@groupkeys) {
 6929:                 my ($trole,$area,$sec,$extendedarea);
 6930:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6931:                     $trole = $1;
 6932:                     $area = $2;
 6933:                     $sec = $3;
 6934:                     $extendedarea = $area.$sec;
 6935:                     if (exists($$allgroups{$area})) {
 6936:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6937:                             my $spec = $trole.'.'.$extendedarea;
 6938:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6939:                                                 $$allgroups{$area}{$group};
 6940:                         }
 6941:                     }
 6942:                 }
 6943:             }
 6944:         }
 6945:     }
 6946:     foreach my $group (keys(%grouproles)) {
 6947:         $$allroles{$group} = $grouproles{$group};
 6948:     }
 6949:     foreach my $role (keys(%{$allroles})) {
 6950:         my %thesepriv;
 6951:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6952:         foreach my $item (split(/:/,$$allroles{$role})) {
 6953:             if ($item ne '') {
 6954:                 my ($privilege,$restrictions)=split(/&/,$item);
 6955:                 if ($restrictions eq '') {
 6956:                     $thesepriv{$privilege}='F';
 6957:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6958:                     $thesepriv{$privilege}.=$restrictions;
 6959:                 }
 6960:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6961:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6962:             }
 6963:         }
 6964:         my $thesestr='';
 6965:         foreach my $priv (sort(keys(%thesepriv))) {
 6966: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6967: 	}
 6968:         $userroles->{'user.priv.'.$role} = $thesestr;
 6969:     }
 6970:     return ($author,$adv,$rar);
 6971: }
 6972: 
 6973: sub role_status {
 6974:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6975:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6976:         my ($one,$two) = split(m{\./},$rolekey,2);
 6977:         (undef,undef,$$role) = split(/\./,$one,3);
 6978:         unless (!defined($$role) || $$role eq '') {
 6979:             $$where = '/'.$two;
 6980:             $$trolecode=$$role.'.'.$$where;
 6981:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6982:             $$tstatus='is';
 6983:             if ($$tstart && $$tstart>$update) {
 6984:                 $$tstatus='future';
 6985:                 if ($$tstart<$now) {
 6986:                     if ($$tstart && $$tstart>$refresh) {
 6987:                         if (($$where ne '') && ($$role ne '')) {
 6988:                             my (%allroles,%allgroups,$group_privs,
 6989:                                 %groups_roles,@rolecodes);
 6990:                             my %userroles = (
 6991:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6992:                             );
 6993:                             @rolecodes = ('cm'); 
 6994:                             my $spec=$$role.'.'.$$where;
 6995:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6996:                             if ($$role =~ /^cr\//) {
 6997:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6998:                                 push(@rolecodes,'cr');
 6999:                             } elsif ($$role eq 'gr') {
 7000:                                 push(@rolecodes,$$role);
 7001:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7002:                                                     $env{'user.name'});
 7003:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7004:                                 (undef,my $group_privs) = split(/\//,$trole);
 7005:                                 $group_privs = &unescape($group_privs);
 7006:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7007:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7008:                                 &get_groups_roles($tdomain,$trest,
 7009:                                                   \%course_roles,\@rolecodes,
 7010:                                                   \%groups_roles);
 7011:                             } else {
 7012:                                 push(@rolecodes,$$role);
 7013:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7014:                             }
 7015:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7016:                                                                    \%groups_roles);
 7017:                             &appenv(\%userroles,\@rolecodes);
 7018:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7019:                         }
 7020:                     }
 7021:                     $$tstatus = 'is';
 7022:                 }
 7023:             }
 7024:             if ($$tend) {
 7025:                 if ($$tend<$update) {
 7026:                     $$tstatus='expired';
 7027:                 } elsif ($$tend<$now) {
 7028:                     $$tstatus='will_not';
 7029:                 }
 7030:             }
 7031:         }
 7032:     }
 7033: }
 7034: 
 7035: sub get_groups_roles {
 7036:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7037:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7038:                   (ref($rolecodes) eq 'ARRAY') && 
 7039:                   (ref($groups_roles) eq 'HASH')); 
 7040:     if (keys(%{$cdom_courseroles}) > 0) {
 7041:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7042:         if ($cdom ne '' && $cnum ne '') {
 7043:             foreach my $key (keys(%{$cdom_courseroles})) {
 7044:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7045:                     my $crsrole = $1;
 7046:                     my $crssec = $2;
 7047:                     if ($crsrole =~ /^cr/) {
 7048:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7049:                             push(@{$rolecodes},'cr');
 7050:                         }
 7051:                     } else {
 7052:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7053:                             push(@{$rolecodes},$crsrole);
 7054:                         }
 7055:                     }
 7056:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7057:                     if ($crssec ne '') {
 7058:                         $rolekey .= "/$crssec";
 7059:                     }
 7060:                     $rolekey .= './';
 7061:                     $groups_roles->{$rolekey} = $rolecodes;
 7062:                 }
 7063:             }
 7064:         }
 7065:     }
 7066:     return;
 7067: }
 7068: 
 7069: sub delete_env_groupprivs {
 7070:     my ($where,$courseroles,$possroles) = @_;
 7071:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7072:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7073:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7074:         %{$courseroles->{$udom}} =
 7075:             &get_my_roles('','','userroles',['active'],
 7076:                           $possroles,[$udom],1);
 7077:     }
 7078:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7079:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7080:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7081:             my $area = '/'.$cdom.'/'.$cnum;
 7082:             my $privkey = "user.priv.$crsrole.$area";
 7083:             if ($crssec ne '') {
 7084:                 $privkey .= '/'.$crssec;
 7085:             }
 7086:             $privkey .= ".$area/$group";
 7087:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7088:         }
 7089:     }
 7090:     return;
 7091: }
 7092: 
 7093: sub check_adhoc_privs {
 7094:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7095:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7096:     if ($sec) {
 7097:         $cckey .= '/'.$sec;
 7098:     } 
 7099:     my $setprivs;
 7100:     if ($env{$cckey}) {
 7101:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7102:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7103:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7104:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7105:             $setprivs = 1;
 7106:         }
 7107:     } else {
 7108:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7109:         $setprivs = 1;
 7110:     }
 7111:     return $setprivs;
 7112: }
 7113: 
 7114: sub set_adhoc_privileges {
 7115: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7116:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7117:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7118:     if ($sec ne '') {
 7119:         $area .= '/'.$sec;
 7120:     }
 7121:     my $spec = $role.'.'.$area;
 7122:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7123:                                   $env{'user.name'},1);
 7124:     my %rolehash = ();
 7125:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7126:         my $rolename = $1;
 7127:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7128:         my %domdef = &get_domain_defaults($dcdom);
 7129:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7130:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7131:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7132:             }
 7133:         }
 7134:     } else {
 7135:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7136:     }
 7137:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7138:     &appenv(\%userroles,[$role,'cm']);
 7139:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7140:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7141:             ($caller eq 'tiny')) {
 7142:         &appenv( {'request.role'        => $spec,
 7143:                   'request.role.domain' => $dcdom,
 7144:                   'request.course.sec'  => $sec,
 7145:                  }
 7146:                );
 7147:         my $tadv=0;
 7148:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7149:         &appenv({'request.role.adv'    => $tadv});
 7150:     }
 7151: }
 7152: 
 7153: # --------------------------------------------------------------- get interface
 7154: 
 7155: sub get {
 7156:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7157:    my $items='';
 7158:    foreach my $item (@$storearr) {
 7159:        $items.=&escape($item).'&';
 7160:    }
 7161:    $items=~s/\&$//;
 7162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7163:    if (!$uname) { $uname=$env{'user.name'}; }
 7164:    my $uhome=&homeserver($uname,$udomain);
 7165: 
 7166:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7167:    my @pairs=split(/\&/,$rep);
 7168:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7169:      return @pairs;
 7170:    }
 7171:    my %returnhash=();
 7172:    my $i=0;
 7173:    foreach my $item (@$storearr) {
 7174:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7175:       $i++;
 7176:    }
 7177:    return %returnhash;
 7178: }
 7179: 
 7180: # --------------------------------------------------------------- del interface
 7181: 
 7182: sub del {
 7183:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7184:    my $items='';
 7185:    foreach my $item (@$storearr) {
 7186:        $items.=&escape($item).'&';
 7187:    }
 7188: 
 7189:    $items=~s/\&$//;
 7190:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7191:    if (!$uname) { $uname=$env{'user.name'}; }
 7192:    my $uhome=&homeserver($uname,$udomain);
 7193:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7194: }
 7195: 
 7196: # -------------------------------------------------------------- dump interface
 7197: 
 7198: sub unserialize {
 7199:     my ($rep, $escapedkeys) = @_;
 7200: 
 7201:     return {} if $rep =~ /^error/;
 7202: 
 7203:     my %returnhash=();
 7204: 	foreach my $item (split(/\&/,$rep)) {
 7205: 	    my ($key, $value) = split(/=/, $item, 2);
 7206: 	    $key = unescape($key) unless $escapedkeys;
 7207: 	    next if $key =~ /^error: 2 /;
 7208: 	    $returnhash{$key} = &thaw_unescape($value);
 7209: 	}
 7210:     #return %returnhash;
 7211:     return \%returnhash;
 7212: }        
 7213: 
 7214: # see Lond::dump_with_regexp
 7215: # if $escapedkeys hash keys won't get unescaped.
 7216: sub dump {
 7217:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7218:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7219:     if (!$uname) { $uname=$env{'user.name'}; }
 7220:     my $uhome=&homeserver($uname,$udomain);
 7221: 
 7222:     if ($regexp) {
 7223:         $regexp=&escape($regexp);
 7224:     } else {
 7225:         $regexp='.';
 7226:     }
 7227:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7228:         # user is hosted on this machine
 7229:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7230:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7231:         return %{unserialize($reply, $escapedkeys)};
 7232:     }
 7233:     my $rep;
 7234:     if ($encrypt) {
 7235:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7236:     } else {
 7237:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7238:     }
 7239:     my @pairs=split(/\&/,$rep);
 7240:     my %returnhash=();
 7241:     if (!($rep =~ /^error/ )) {
 7242: 	foreach my $item (@pairs) {
 7243: 	    my ($key,$value)=split(/=/,$item,2);
 7244:         $key = unescape($key) unless $escapedkeys;
 7245:         #$key = &unescape($key);
 7246: 	    next if ($key =~ /^error: 2 /);
 7247: 	    $returnhash{$key}=&thaw_unescape($value);
 7248: 	}
 7249:     }
 7250:     return %returnhash;
 7251: }
 7252: 
 7253: 
 7254: # --------------------------------------------------------- dumpstore interface
 7255: 
 7256: sub dumpstore {
 7257:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7258:    # same as dump but keys must be escaped. They may contain colon separated
 7259:    # lists of values that may themself contain colons (e.g. symbs).
 7260:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7261: }
 7262: 
 7263: # -------------------------------------------------------------- keys interface
 7264: 
 7265: sub getkeys {
 7266:    my ($namespace,$udomain,$uname)=@_;
 7267:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7268:    if (!$uname) { $uname=$env{'user.name'}; }
 7269:    my $uhome=&homeserver($uname,$udomain);
 7270:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7271:    my @keyarray=();
 7272:    foreach my $key (split(/\&/,$rep)) {
 7273:       next if ($key =~ /^error: 2 /);
 7274:       push(@keyarray,&unescape($key));
 7275:    }
 7276:    return @keyarray;
 7277: }
 7278: 
 7279: # --------------------------------------------------------------- currentdump
 7280: sub currentdump {
 7281:    my ($courseid,$sdom,$sname)=@_;
 7282:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7283:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7284:    $sname    = $env{'user.name'}         if (! defined($sname));
 7285:    my $uhome = &homeserver($sname,$sdom);
 7286:    my $rep;
 7287: 
 7288:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7289:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7290:                    $courseid)));
 7291:    } else {
 7292:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7293:    }
 7294: 
 7295:    return if ($rep =~ /^(error:|no_such_host)/);
 7296:    #
 7297:    my %returnhash=();
 7298:    #
 7299:    if ($rep eq 'unknown_cmd') {
 7300:        # an old lond will not know currentdump
 7301:        # Do a dump and make it look like a currentdump
 7302:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7303:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7304:        my %hash = @tmp;
 7305:        @tmp=();
 7306:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7307:    } else {
 7308:        my @pairs=split(/\&/,$rep);
 7309:        foreach my $pair (@pairs) {
 7310:            my ($key,$value)=split(/=/,$pair,2);
 7311:            my ($symb,$param) = split(/:/,$key);
 7312:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7313:                                                         &thaw_unescape($value);
 7314:        }
 7315:    }
 7316:    return %returnhash;
 7317: }
 7318: 
 7319: sub convert_dump_to_currentdump{
 7320:     my %hash = %{shift()};
 7321:     my %returnhash;
 7322:     # Code ripped from lond, essentially.  The only difference
 7323:     # here is the unescaping done by lonnet::dump().  Conceivably
 7324:     # we might run in to problems with parameter names =~ /^v\./
 7325:     while (my ($key,$value) = each(%hash)) {
 7326:         my ($v,$symb,$param) = split(/:/,$key);
 7327: 	$symb  = &unescape($symb);
 7328: 	$param = &unescape($param);
 7329:         next if ($v eq 'version' || $symb eq 'keys');
 7330:         next if (exists($returnhash{$symb}) &&
 7331:                  exists($returnhash{$symb}->{$param}) &&
 7332:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7333:         $returnhash{$symb}->{$param}=$value;
 7334:         $returnhash{$symb}->{'v.'.$param}=$v;
 7335:     }
 7336:     #
 7337:     # Remove all of the keys in the hashes which keep track of
 7338:     # the version of the parameter.
 7339:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7340:         # use a foreach because we are going to delete from the hash.
 7341:         foreach my $key (keys(%$param_hash)) {
 7342:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7343:         }
 7344:     }
 7345:     return \%returnhash;
 7346: }
 7347: 
 7348: # ------------------------------------------------------ critical inc interface
 7349: 
 7350: sub cinc {
 7351:     return &inc(@_,'critical');
 7352: }
 7353: 
 7354: # --------------------------------------------------------------- inc interface
 7355: 
 7356: sub inc {
 7357:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7358:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7359:     if (!$uname) { $uname=$env{'user.name'}; }
 7360:     my $uhome=&homeserver($uname,$udomain);
 7361:     my $items='';
 7362:     if (! ref($store)) {
 7363:         # got a single value, so use that instead
 7364:         $items = &escape($store).'=&';
 7365:     } elsif (ref($store) eq 'SCALAR') {
 7366:         $items = &escape($$store).'=&';        
 7367:     } elsif (ref($store) eq 'ARRAY') {
 7368:         $items = join('=&',map {&escape($_);} @{$store});
 7369:     } elsif (ref($store) eq 'HASH') {
 7370:         while (my($key,$value) = each(%{$store})) {
 7371:             $items.= &escape($key).'='.&escape($value).'&';
 7372:         }
 7373:     }
 7374:     $items=~s/\&$//;
 7375:     if ($critical) {
 7376: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7377:     } else {
 7378: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7379:     }
 7380: }
 7381: 
 7382: # --------------------------------------------------------------- put interface
 7383: 
 7384: sub put {
 7385:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7386:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7387:    if (!$uname) { $uname=$env{'user.name'}; }
 7388:    my $uhome=&homeserver($uname,$udomain);
 7389:    my $items='';
 7390:    foreach my $item (keys(%$storehash)) {
 7391:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7392:    }
 7393:    $items=~s/\&$//;
 7394:    if ($encrypt) {
 7395:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7396:    } else {
 7397:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7398:    }
 7399: }
 7400: 
 7401: # ------------------------------------------------------------ newput interface
 7402: 
 7403: sub newput {
 7404:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7405:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7406:    if (!$uname) { $uname=$env{'user.name'}; }
 7407:    my $uhome=&homeserver($uname,$udomain);
 7408:    my $items='';
 7409:    foreach my $key (keys(%$storehash)) {
 7410:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7411:    }
 7412:    $items=~s/\&$//;
 7413:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7414: }
 7415: 
 7416: # ---------------------------------------------------------  putstore interface
 7417: 
 7418: sub putstore {
 7419:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7420:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7421:    if (!$uname) { $uname=$env{'user.name'}; }
 7422:    my $uhome=&homeserver($uname,$udomain);
 7423:    my $items='';
 7424:    foreach my $key (keys(%$storehash)) {
 7425:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7426:    }
 7427:    $items=~s/\&$//;
 7428:    my $esc_symb=&escape($symb);
 7429:    my $esc_v=&escape($version);
 7430:    my $reply =
 7431:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7432: 	      $uhome);
 7433:    if (($tolog) && ($reply eq 'ok')) {
 7434:        my $namevalue='';
 7435:        foreach my $key (keys(%{$storehash})) {
 7436:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7437:        }
 7438:        my $ip = &get_requestor_ip();
 7439:        $namevalue .= 'ip='.&escape($ip).
 7440:                      '&host='.&escape($perlvar{'lonHostID'}).
 7441:                      '&version='.$esc_v.
 7442:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7443:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7444:    }
 7445:    if ($reply eq 'unknown_cmd') {
 7446:        # gfall back to way things use to be done
 7447:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7448: 			    $uname);
 7449:    }
 7450:    return $reply;
 7451: }
 7452: 
 7453: sub old_putstore {
 7454:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7455:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7456:     if (!$uname) { $uname=$env{'user.name'}; }
 7457:     my $uhome=&homeserver($uname,$udomain);
 7458:     my %newstorehash;
 7459:     foreach my $item (keys(%$storehash)) {
 7460: 	my $key = $version.':'.&escape($symb).':'.$item;
 7461: 	$newstorehash{$key} = $storehash->{$item};
 7462:     }
 7463:     my $items='';
 7464:     my %allitems = ();
 7465:     foreach my $item (keys(%newstorehash)) {
 7466: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7467: 	    my $key = $1.':keys:'.$2;
 7468: 	    $allitems{$key} .= $3.':';
 7469: 	}
 7470: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7471:     }
 7472:     foreach my $item (keys(%allitems)) {
 7473: 	$allitems{$item} =~ s/\:$//;
 7474: 	$items.= $item.'='.$allitems{$item}.'&';
 7475:     }
 7476:     $items=~s/\&$//;
 7477:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7478: }
 7479: 
 7480: # ------------------------------------------------------ critical put interface
 7481: 
 7482: sub cput {
 7483:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7484:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7485:    if (!$uname) { $uname=$env{'user.name'}; }
 7486:    my $uhome=&homeserver($uname,$udomain);
 7487:    my $items='';
 7488:    foreach my $item (keys(%$storehash)) {
 7489:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7490:    }
 7491:    $items=~s/\&$//;
 7492:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7493: }
 7494: 
 7495: # -------------------------------------------------------------- eget interface
 7496: 
 7497: sub eget {
 7498:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7499:    my $items='';
 7500:    foreach my $item (@$storearr) {
 7501:        $items.=&escape($item).'&';
 7502:    }
 7503:    $items=~s/\&$//;
 7504:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7505:    if (!$uname) { $uname=$env{'user.name'}; }
 7506:    my $uhome=&homeserver($uname,$udomain);
 7507:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7508:    my @pairs=split(/\&/,$rep);
 7509:    my %returnhash=();
 7510:    my $i=0;
 7511:    foreach my $item (@$storearr) {
 7512:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7513:       $i++;
 7514:    }
 7515:    return %returnhash;
 7516: }
 7517: 
 7518: # ------------------------------------------------------------ tmpput interface
 7519: sub tmpput {
 7520:     my ($storehash,$server,$context)=@_;
 7521:     my $items='';
 7522:     foreach my $item (keys(%$storehash)) {
 7523: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7524:     }
 7525:     $items=~s/\&$//;
 7526:     if (defined($context)) {
 7527:         $items .= ':'.&escape($context);
 7528:     }
 7529:     return &reply("tmpput:$items",$server);
 7530: }
 7531: 
 7532: # ------------------------------------------------------------ tmpget interface
 7533: sub tmpget {
 7534:     my ($token,$server)=@_;
 7535:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7536:     my $rep=&reply("tmpget:$token",$server);
 7537:     my %returnhash;
 7538:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7539:         return %returnhash;
 7540:     }
 7541:     foreach my $item (split(/\&/,$rep)) {
 7542: 	my ($key,$value)=split(/=/,$item);
 7543: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7544:     }
 7545:     return %returnhash;
 7546: }
 7547: 
 7548: # ------------------------------------------------------------ tmpdel interface
 7549: sub tmpdel {
 7550:     my ($token,$server)=@_;
 7551:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7552:     return &reply("tmpdel:$token",$server);
 7553: }
 7554: 
 7555: # ------------------------------------------------------------ get_timebased_id 
 7556: 
 7557: sub get_timebased_id {
 7558:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7559:         $maxtries) = @_;
 7560:     my ($newid,$error,$dellock);
 7561:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7562:         return ('','ok','invalid call to get suffix');
 7563:     }
 7564: 
 7565: # set defaults for any optional args for which values were not supplied
 7566:     if ($who eq '') {
 7567:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7568:     }
 7569:     if (!$locktries) {
 7570:         $locktries = 3;
 7571:     }
 7572:     if (!$maxtries) {
 7573:         $maxtries = 10;
 7574:     }
 7575:     
 7576:     if (($cdom eq '') || ($cnum eq '')) {
 7577:         if ($env{'request.course.id'}) {
 7578:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7579:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7580:         }
 7581:         if (($cdom eq '') || ($cnum eq '')) {
 7582:             return ('','ok','call to get suffix not in course context');
 7583:         }
 7584:     }
 7585: 
 7586: # construct locking item
 7587:     my $lockhash = {
 7588:                       $prefix."\0".'locked_'.$keyid => $who,
 7589:                    };
 7590:     my $tries = 0;
 7591: 
 7592: # attempt to get lock on nohist_$namespace file
 7593:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7594:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7595:         $tries ++;
 7596:         sleep 1;
 7597:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7598:     }
 7599: 
 7600: # attempt to get unique identifier, based on current timestamp
 7601:     if ($gotlock eq 'ok') {
 7602:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7603:         my $id = time;
 7604:         $newid = $id;
 7605:         if ($idtype eq 'addcode') {
 7606:             $newid .= &sixnum_code();
 7607:         }
 7608:         my $idtries = 0;
 7609:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7610:             if ($idtype eq 'concat') {
 7611:                 $newid = $id.$idtries;
 7612:             } elsif ($idtype eq 'addcode') {
 7613:                 $newid = $newid.&sixnum_code();
 7614:             } else {
 7615:                 $newid ++;
 7616:             }
 7617:             $idtries ++;
 7618:         }
 7619:         if (!exists($inuse{$prefix."\0".$newid})) {
 7620:             my %new_item =  (
 7621:                               $prefix."\0".$newid => $who,
 7622:                             );
 7623:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7624:                                                  $cdom,$cnum);
 7625:             if ($putresult ne 'ok') {
 7626:                 undef($newid);
 7627:                 $error = 'error saving new item: '.$putresult;
 7628:             }
 7629:         } else {
 7630:              undef($newid);
 7631:              $error = ('error: no unique suffix available for the new item ');
 7632:         }
 7633: #  remove lock
 7634:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7635:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7636:     } else {
 7637:         $error = "error: could not obtain lockfile\n";
 7638:         $dellock = 'ok';
 7639:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7640:             $dellock = 'nolock';
 7641:         }
 7642:     }
 7643:     return ($newid,$dellock,$error);
 7644: }
 7645: 
 7646: sub sixnum_code {
 7647:     my $code;
 7648:     for (0..6) {
 7649:         $code .= int( rand(9) );
 7650:     }
 7651:     return $code;
 7652: }
 7653: 
 7654: # -------------------------------------------------- portfolio access checking
 7655: 
 7656: sub portfolio_access {
 7657:     my ($requrl,$clientip) = @_;
 7658:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7659:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7660:     if ($result) {
 7661:         my %setters;
 7662:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7663:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7664:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7665:             if (($startblock && $endblock) || ($by_ip)) {
 7666:                 return 'B';
 7667:             }
 7668:         } else {
 7669:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7670:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7671:             if (($startblock && $endblock) || ($by_ip)) {
 7672:                 return 'B';
 7673:             }
 7674:         }
 7675:     }
 7676:     if ($result eq 'ok') {
 7677:        return 'F';
 7678:     } elsif ($result =~ /^[^:]+:guest_/) {
 7679:        return 'A';
 7680:     }
 7681:     return '';
 7682: }
 7683: 
 7684: sub get_portfolio_access {
 7685:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7686: 
 7687:     if (!ref($access_hash)) {
 7688: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7689: 	my %access_controls = &get_access_controls($current_perms,$group,
 7690: 						   $file_name);
 7691: 	$access_hash = $access_controls{$file_name};
 7692:     }
 7693: 
 7694:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7695:     my $now = time;
 7696:     if (ref($access_hash) eq 'HASH') {
 7697:         foreach my $key (keys(%{$access_hash})) {
 7698:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7699:             if ($start > $now) {
 7700:                 next;
 7701:             }
 7702:             if ($end && $end<$now) {
 7703:                 next;
 7704:             }
 7705:             if ($scope eq 'public') {
 7706:                 $public = $key;
 7707:                 last;
 7708:             } elsif ($scope eq 'guest') {
 7709:                 $guest = $key;
 7710:             } elsif ($scope eq 'domains') {
 7711:                 push(@domains,$key);
 7712:             } elsif ($scope eq 'users') {
 7713:                 push(@users,$key);
 7714:             } elsif ($scope eq 'course') {
 7715:                 push(@courses,$key);
 7716:             } elsif ($scope eq 'group') {
 7717:                 push(@groups,$key);
 7718:             } elsif ($scope eq 'ip') {
 7719:                 push(@ips,$key);
 7720:             }
 7721:         }
 7722:         if ($public) {
 7723:             return 'ok';
 7724:         } elsif (@ips > 0) {
 7725:             my $allowed;
 7726:             foreach my $ipkey (@ips) {
 7727:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7728:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7729:                         $allowed = 1;
 7730:                         last; 
 7731:                     }
 7732:                 }
 7733:             }
 7734:             if ($allowed) {
 7735:                 return 'ok';
 7736:             }
 7737:         }
 7738:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7739:             if ($guest) {
 7740:                 return $guest;
 7741:             }
 7742:         } else {
 7743:             if (@domains > 0) {
 7744:                 foreach my $domkey (@domains) {
 7745:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7746:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7747:                             return 'ok';
 7748:                         }
 7749:                     }
 7750:                 }
 7751:             }
 7752:             if (@users > 0) {
 7753:                 foreach my $userkey (@users) {
 7754:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7755:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7756:                             if (ref($item) eq 'HASH') {
 7757:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7758:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7759:                                     return 'ok';
 7760:                                 }
 7761:                             }
 7762:                         }
 7763:                     } 
 7764:                 }
 7765:             }
 7766:             my %roleshash;
 7767:             my @courses_and_groups = @courses;
 7768:             push(@courses_and_groups,@groups); 
 7769:             if (@courses_and_groups > 0) {
 7770:                 my (%allgroups,%allroles); 
 7771:                 my ($start,$end,$role,$sec,$group);
 7772:                 foreach my $envkey (%env) {
 7773:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7774:                         my $cid = $2.'_'.$3; 
 7775:                         if ($1 eq 'gr') {
 7776:                             $group = $4;
 7777:                             $allgroups{$cid}{$group} = $env{$envkey};
 7778:                         } else {
 7779:                             if ($4 eq '') {
 7780:                                 $sec = 'none';
 7781:                             } else {
 7782:                                 $sec = $4;
 7783:                             }
 7784:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7785:                         }
 7786:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7787:                         my $cid = $2.'_'.$3;
 7788:                         if ($4 eq '') {
 7789:                             $sec = 'none';
 7790:                         } else {
 7791:                             $sec = $4;
 7792:                         }
 7793:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7794:                     }
 7795:                 }
 7796:                 if (keys(%allroles) == 0) {
 7797:                     return;
 7798:                 }
 7799:                 foreach my $key (@courses_and_groups) {
 7800:                     my %content = %{$$access_hash{$key}};
 7801:                     my $cnum = $content{'number'};
 7802:                     my $cdom = $content{'domain'};
 7803:                     my $cid = $cdom.'_'.$cnum;
 7804:                     if (!exists($allroles{$cid})) {
 7805:                         next;
 7806:                     }    
 7807:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7808:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7809:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7810:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7811:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7812:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7813:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7814:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7815:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7816:                                         if (grep/^all$/,@sections) {
 7817:                                             return 'ok';
 7818:                                         } else {
 7819:                                             if (grep/^$sec$/,@sections) {
 7820:                                                 return 'ok';
 7821:                                             }
 7822:                                         }
 7823:                                     }
 7824:                                 }
 7825:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7826:                                     if (grep/^none$/,@groups) {
 7827:                                         return 'ok';
 7828:                                     }
 7829:                                 } else {
 7830:                                     if (grep/^all$/,@groups) {
 7831:                                         return 'ok';
 7832:                                     } 
 7833:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7834:                                         if (grep/^$group$/,@groups) {
 7835:                                             return 'ok';
 7836:                                         }
 7837:                                     }
 7838:                                 } 
 7839:                             }
 7840:                         }
 7841:                     }
 7842:                 }
 7843:             }
 7844:             if ($guest) {
 7845:                 return $guest;
 7846:             }
 7847:         }
 7848:     }
 7849:     return;
 7850: }
 7851: 
 7852: sub course_group_datechecker {
 7853:     my ($dates,$now,$status) = @_;
 7854:     my ($start,$end) = split(/\./,$dates);
 7855:     if (!$start && !$end) {
 7856:         return 'ok';
 7857:     }
 7858:     if (grep/^active$/,@{$status}) {
 7859:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7860:             return 'ok';
 7861:         }
 7862:     }
 7863:     if (grep/^previous$/,@{$status}) {
 7864:         if ($end > $now ) {
 7865:             return 'ok';
 7866:         }
 7867:     }
 7868:     if (grep/^future$/,@{$status}) {
 7869:         if ($start > $now) {
 7870:             return 'ok';
 7871:         }
 7872:     }
 7873:     return; 
 7874: }
 7875: 
 7876: sub parse_portfolio_url {
 7877:     my ($url) = @_;
 7878: 
 7879:     my ($type,$udom,$unum,$group,$file_name);
 7880:     
 7881:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7882: 	$type = 1;
 7883:         $udom = $1;
 7884:         $unum = $2;
 7885:         $file_name = $3;
 7886:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7887: 	$type = 2;
 7888:         $udom = $1;
 7889:         $unum = $2;
 7890:         $group = $3;
 7891:         $file_name = $3.'/'.$4;
 7892:     }
 7893:     if (wantarray) {
 7894: 	return ($type,$udom,$unum,$file_name,$group);
 7895:     }
 7896:     return $type;
 7897: }
 7898: 
 7899: sub is_portfolio_url {
 7900:     my ($url) = @_;
 7901:     return scalar(&parse_portfolio_url($url));
 7902: }
 7903: 
 7904: sub is_portfolio_file {
 7905:     my ($file) = @_;
 7906:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7907:         return 1;
 7908:     }
 7909:     return;
 7910: }
 7911: 
 7912: sub usertools_access {
 7913:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7914:     my ($access,%tools);
 7915:     if ($context eq '') {
 7916:         $context = 'tools';
 7917:     }
 7918:     if ($context eq 'requestcourses') {
 7919:         %tools = (
 7920:                       official   => 1,
 7921:                       unofficial => 1,
 7922:                       community  => 1,
 7923:                       textbook   => 1,
 7924:                       placement  => 1,
 7925:                       lti        => 1,
 7926:                  );
 7927:     } elsif ($context eq 'requestauthor') {
 7928:         %tools = (
 7929:                       requestauthor => 1,
 7930:                  );
 7931:     } else {
 7932:         %tools = (
 7933:                       aboutme   => 1,
 7934:                       blog      => 1,
 7935:                       webdav    => 1,
 7936:                       portfolio => 1,
 7937:                  );
 7938:     }
 7939:     return if (!defined($tools{$tool}));
 7940: 
 7941:     if (($udom eq '') || ($uname eq '')) {
 7942:         $udom = $env{'user.domain'};
 7943:         $uname = $env{'user.name'};
 7944:     }
 7945: 
 7946:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7947:         if ($action ne 'reload') {
 7948:             if ($context eq 'requestcourses') {
 7949:                 return $env{'environment.canrequest.'.$tool};
 7950:             } elsif ($context eq 'requestauthor') {
 7951:                 return $env{'environment.canrequest.author'};
 7952:             } else {
 7953:                 return $env{'environment.availabletools.'.$tool};
 7954:             }
 7955:         }
 7956:     }
 7957: 
 7958:     my ($toolstatus,$inststatus,$envkey);
 7959:     if ($context eq 'requestauthor') {
 7960:         $envkey = $context; 
 7961:     } else {
 7962:         $envkey = $context.'.'.$tool;
 7963:     }
 7964: 
 7965:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7966:          ($action ne 'reload')) {
 7967:         $toolstatus = $env{'environment.'.$envkey};
 7968:         $inststatus = $env{'environment.inststatus'};
 7969:     } else {
 7970:         if (ref($userenvref) eq 'HASH') {
 7971:             $toolstatus = $userenvref->{$envkey};
 7972:             $inststatus = $userenvref->{'inststatus'};
 7973:         } else {
 7974:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7975:             $toolstatus = $userenv{$envkey};
 7976:             $inststatus = $userenv{'inststatus'};
 7977:         }
 7978:     }
 7979: 
 7980:     if ($toolstatus ne '') {
 7981:         if ($toolstatus) {
 7982:             $access = 1;
 7983:         } else {
 7984:             $access = 0;
 7985:         }
 7986:         return $access;
 7987:     }
 7988: 
 7989:     my ($is_adv,%domdef);
 7990:     if (ref($is_advref) eq 'HASH') {
 7991:         $is_adv = $is_advref->{'is_adv'};
 7992:     } else {
 7993:         $is_adv = &is_advanced_user($udom,$uname);
 7994:     }
 7995:     if (ref($domdefref) eq 'HASH') {
 7996:         %domdef = %{$domdefref};
 7997:     } else {
 7998:         %domdef = &get_domain_defaults($udom);
 7999:     }
 8000:     if (ref($domdef{$tool}) eq 'HASH') {
 8001:         if ($is_adv) {
 8002:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8003:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8004:                     $access = 1;
 8005:                 } else {
 8006:                     $access = 0;
 8007:                 }
 8008:                 return $access;
 8009:             }
 8010:         }
 8011:         if ($inststatus ne '') {
 8012:             my ($hasaccess,$hasnoaccess);
 8013:             foreach my $affiliation (split(/:/,$inststatus)) {
 8014:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8015:                     if ($domdef{$tool}{$affiliation}) {
 8016:                         $hasaccess = 1;
 8017:                     } else {
 8018:                         $hasnoaccess = 1;
 8019:                     }
 8020:                 }
 8021:             }
 8022:             if ($hasaccess || $hasnoaccess) {
 8023:                 if ($hasaccess) {
 8024:                     $access = 1;
 8025:                 } elsif ($hasnoaccess) {
 8026:                     $access = 0; 
 8027:                 }
 8028:                 return $access;
 8029:             }
 8030:         } else {
 8031:             if ($domdef{$tool}{'default'} ne '') {
 8032:                 if ($domdef{$tool}{'default'}) {
 8033:                     $access = 1;
 8034:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8035:                     $access = 0;
 8036:                 }
 8037:                 return $access;
 8038:             }
 8039:         }
 8040:     } else {
 8041:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8042:             $access = 1;
 8043:         } else {
 8044:             $access = 0;
 8045:         }
 8046:         return $access;
 8047:     }
 8048: }
 8049: 
 8050: sub is_course_owner {
 8051:     my ($cdom,$cnum,$udom,$uname) = @_;
 8052:     if (($udom eq '') || ($uname eq '')) {
 8053:         $udom = $env{'user.domain'};
 8054:         $uname = $env{'user.name'};
 8055:     }
 8056:     unless (($udom eq '') || ($uname eq '')) {
 8057:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8058:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8059:                 return 1;
 8060:             } else {
 8061:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 8062:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8063:                     return 1;
 8064:                 }
 8065:             }
 8066:         }
 8067:     }
 8068:     return;
 8069: }
 8070: 
 8071: sub is_advanced_user {
 8072:     my ($udom,$uname) = @_;
 8073:     if ($udom ne '' && $uname ne '') {
 8074:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8075:             if (wantarray) {
 8076:                 return ($env{'user.adv'},$env{'user.author'});
 8077:             } else {
 8078:                 return $env{'user.adv'};
 8079:             }
 8080:         }
 8081:     }
 8082:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8083:     my %allroles;
 8084:     my ($is_adv,$is_author);
 8085:     foreach my $role (keys(%roleshash)) {
 8086:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8087:         my $area = '/'.$tdomain.'/'.$trest;
 8088:         if ($sec ne '') {
 8089:             $area .= '/'.$sec;
 8090:         }
 8091:         if (($area ne '') && ($trole ne '')) {
 8092:             my $spec=$trole.'.'.$area;
 8093:             if ($trole =~ /^cr\//) {
 8094:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8095:             } elsif ($trole ne 'gr') {
 8096:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8097:             }
 8098:             if ($trole eq 'au') {
 8099:                 $is_author = 1;
 8100:             }
 8101:         }
 8102:     }
 8103:     foreach my $role (keys(%allroles)) {
 8104:         last if ($is_adv);
 8105:         foreach my $item (split(/:/,$allroles{$role})) {
 8106:             if ($item ne '') {
 8107:                 my ($privilege,$restrictions)=split(/&/,$item);
 8108:                 if ($privilege eq 'adv') {
 8109:                     $is_adv = 1;
 8110:                     last;
 8111:                 }
 8112:             }
 8113:         }
 8114:     }
 8115:     if (wantarray) {
 8116:         return ($is_adv,$is_author);
 8117:     }
 8118:     return $is_adv;
 8119: }
 8120: 
 8121: sub check_can_request {
 8122:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8123:     my $canreq = 0;
 8124:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8125:         $uname = $env{'user.name'};
 8126:         $udom = $env{'user.domain'};
 8127:     }
 8128:     my ($types,$typename) = &Apache::loncommon::course_types();
 8129:     my @options = ('approval','validate','autolimit');
 8130:     my $optregex = join('|',@options);
 8131:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8132:         my %willtrust;
 8133:         foreach my $type (@{$types}) {
 8134:             if (&usertools_access($uname,$udom,$type,undef,
 8135:                                   'requestcourses')) {
 8136:                 $canreq ++;
 8137:                 if (ref($request_domains) eq 'HASH') {
 8138:                     push(@{$request_domains->{$type}},$udom);
 8139:                 }
 8140:                 if ($dom eq $udom) {
 8141:                     $can_request->{$type} = 1;
 8142:                 }
 8143:             }
 8144:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8145:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8146:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8147:                 if (@curr > 0) {
 8148:                     foreach my $item (@curr) {
 8149:                         if (ref($request_domains) eq 'HASH') {
 8150:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8151:                             if ($otherdom ne '') {
 8152:                                 unless (exists($willtrust{$otherdom})) {
 8153:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8154:                                 }
 8155:                                 if ($willtrust{$otherdom}) {
 8156:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8157:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8158:                                             push(@{$request_domains->{$type}},$otherdom);
 8159:                                         }
 8160:                                     } else {
 8161:                                         push(@{$request_domains->{$type}},$otherdom);
 8162:                                     }
 8163:                                 }
 8164:                             }
 8165:                         }
 8166:                     }
 8167:                     unless ($dom eq $env{'user.domain'}) {
 8168:                         $canreq ++;
 8169:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8170:                             $can_request->{$type} = 1;
 8171:                         }
 8172:                     }
 8173:                 }
 8174:             }
 8175:         }
 8176:     }
 8177:     return $canreq;
 8178: }
 8179: 
 8180: # ---------------------------------------------- Custom access rule evaluation
 8181: 
 8182: sub customaccess {
 8183:     my ($priv,$uri)=@_;
 8184:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8185:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8186:     $udom = &LONCAPA::clean_domain($udom);
 8187:     $ucrs = &LONCAPA::clean_username($ucrs);
 8188:     my $access=0;
 8189:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8190: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8191: 	if ($type eq 'user') {
 8192: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8193: 		my ($tdom,$tuname)=split(m{/},$scope);
 8194: 		if ($tdom) {
 8195: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8196: 		}
 8197: 		if ($tuname) {
 8198: 		    if ($tuname ne $env{'user.name'}) { next; }
 8199: 		}
 8200: 		$access=($effect eq 'allow');
 8201: 		last;
 8202: 	    }
 8203: 	} else {
 8204: 	    if ($role) {
 8205: 		if ($role ne $urole) { next; }
 8206: 	    }
 8207: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8208: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8209: 		if ($tdom) {
 8210: 		    if ($tdom ne $udom) { next; }
 8211: 		}
 8212: 		if ($tcrs) {
 8213: 		    if ($tcrs ne $ucrs) { next; }
 8214: 		}
 8215: 		if ($tsec) {
 8216: 		    if ($tsec ne $usec) { next; }
 8217: 		}
 8218: 		$access=($effect eq 'allow');
 8219: 		last;
 8220: 	    }
 8221: 	    if ($realm eq '' && $role eq '') {
 8222: 		$access=($effect eq 'allow');
 8223: 	    }
 8224: 	}
 8225:     }
 8226:     return $access;
 8227: }
 8228: 
 8229: # ------------------------------------------------- Check for a user privilege
 8230: 
 8231: sub allowed {
 8232:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8233:     my $ver_orguri=$uri;
 8234:     $uri=&deversion($uri);
 8235:     my $orguri=$uri;
 8236:     $uri=&declutter($uri);
 8237: 
 8238:     if ($priv eq 'evb') {
 8239: # Evade communication block restrictions for specified role in a course or domain
 8240:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8241:             return $1;
 8242:         } else {
 8243:             return;
 8244:         }
 8245:     }
 8246: 
 8247:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8248: # Free bre access to adm and meta resources
 8249:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8250: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8251: 	&& ($priv eq 'bre')) {
 8252: 	return 'F';
 8253:     }
 8254: 
 8255: # Free bre access to user's own portfolio contents
 8256:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8257:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8258: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8259:         my %setters;
 8260:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8261:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8262:         if (($startblock && $endblock) || ($by_ip)) {
 8263:             return 'B';
 8264:         } else {
 8265:             return 'F';
 8266:         }
 8267:     }
 8268: 
 8269: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8270:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8271:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8272:         if (exists($env{'request.course.id'})) {
 8273:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8274:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8275:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8276:                 my $courseprivid=$env{'request.course.id'};
 8277:                 $courseprivid=~s/\_/\//;
 8278:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8279:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8280:                     return $1; 
 8281:                 } else {
 8282:                     if ($env{'request.course.sec'}) {
 8283:                         $courseprivid.='/'.$env{'request.course.sec'};
 8284:                     }
 8285:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8286:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8287:                         return $2;
 8288:                     }
 8289:                 }
 8290:             }
 8291:         }
 8292:     }
 8293: 
 8294: # Free bre to public access
 8295: 
 8296:     if ($priv eq 'bre') {
 8297:         my $copyright;
 8298:         unless ($uri =~ /ext\.tool/) {
 8299:             $copyright=&metadata($uri,'copyright');
 8300:         }
 8301: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8302:            return 'F'; 
 8303:         }
 8304:         if ($copyright eq 'priv') {
 8305:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8306: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8307: 		return '';
 8308:             }
 8309:         }
 8310:         if ($copyright eq 'domain') {
 8311:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8312: 	    unless (($env{'user.domain'} eq $1) ||
 8313:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8314: 		return '';
 8315:             }
 8316:         }
 8317:         if ($env{'request.role'}=~ /li\.\//) {
 8318:             # Library role, so allow browsing of resources in this domain.
 8319:             return 'F';
 8320:         }
 8321:         if ($copyright eq 'custom') {
 8322: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8323:         }
 8324:     }
 8325:     # Domain coordinator is trying to create a course
 8326:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8327:         # uri is the requested domain in this case.
 8328:         # comparison to 'request.role.domain' shows if the user has selected
 8329:         # a role of dc for the domain in question.
 8330:         return 'F' if ($uri eq $env{'request.role.domain'});
 8331:     }
 8332: 
 8333:     my $thisallowed='';
 8334:     my $statecond=0;
 8335:     my $courseprivid='';
 8336: 
 8337:     my $ownaccess;
 8338:     # Community Coordinator or Assistant Co-author browsing resource space.
 8339:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8340:         if ($uri eq '') {
 8341:             $ownaccess = 1;
 8342:         } else {
 8343:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8344:                 my $udom = $env{'user.domain'};
 8345:                 my $uname = $env{'user.name'};
 8346:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8347:                     $ownaccess = 1;
 8348:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8349:                     unless ($uri =~ m{\.\./}) {
 8350:                         $ownaccess = 1;
 8351:                     }
 8352:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8353:                     my $now = time;
 8354:                     if ($uri =~ m{^([^/]+)/?$}) {
 8355:                         my $adom = $1;
 8356:                         foreach my $key (keys(%env)) {
 8357:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8358:                                 my ($start,$end) = split(/\./,$env{$key});
 8359:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8360:                                     $ownaccess = 1;
 8361:                                     last;
 8362:                                 }
 8363:                             }
 8364:                         }
 8365:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8366:                         my $adom = $1;
 8367:                         my $aname = $2;
 8368:                         foreach my $role ('ca','aa') { 
 8369:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8370:                                 my ($start,$end) =
 8371:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8372:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8373:                                     $ownaccess = 1;
 8374:                                     last;
 8375:                                 }
 8376:                             }
 8377:                         }
 8378:                     }
 8379:                 }
 8380:             }
 8381:         }
 8382:     }
 8383: 
 8384: # Course
 8385: 
 8386:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8387:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8388:             $thisallowed.=$1;
 8389:         }
 8390:     }
 8391: 
 8392: # Domain
 8393: 
 8394:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8395:        =~/\Q$priv\E\&([^\:]*)/) {
 8396:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8397:             $thisallowed.=$1;
 8398:         }
 8399:     }
 8400: 
 8401: # User who is not author or co-author might still be able to edit
 8402: # resource of an author in the domain (e.g., if Domain Coordinator).
 8403:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8404:         (&allowed('mdc',$env{'request.course.id'}))) {
 8405:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8406:             $thisallowed.=$1;
 8407:         }
 8408:     }
 8409: 
 8410: # Course: uri itself is a course
 8411:     my $courseuri=$uri;
 8412:     $courseuri=~s/\_(\d)/\/$1/;
 8413:     $courseuri=~s/^([^\/])/\/$1/;
 8414: 
 8415:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8416:        =~/\Q$priv\E\&([^\:]*)/) {
 8417:         if ($priv eq 'mip') {
 8418:             my $rem = $1;
 8419:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8420:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8421:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8422:                 if ($cdom ne '') {
 8423:                     my %passwdconf = &get_passwdconf($cdom);
 8424:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8425:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8426:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8427:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8428:                                 unless (@inststatuses) {
 8429:                                     @inststatuses = ('default');
 8430:                                 }
 8431:                                 foreach my $status (@inststatuses) {
 8432:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8433:                                         $thisallowed.=$rem;
 8434:                                     }
 8435:                                 }
 8436:                             }
 8437:                         }
 8438:                     }
 8439:                 }
 8440:             }
 8441:         } else {
 8442:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8443:                 $thisallowed.=$1;
 8444:             }
 8445:         }
 8446:     }
 8447: 
 8448: # URI is an uploaded document for this course, default permissions don't matter
 8449: # not allowing 'edit' access (editupload) to uploaded course docs
 8450:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8451: 	$thisallowed='';
 8452:         my ($match)=&is_on_map($uri);
 8453:         if ($match) {
 8454:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8455:                   =~/\Q$priv\E\&([^\:]*)/) {
 8456:                 my $value = $1;
 8457:                 my $deeplinkblock;
 8458:                 unless ($nodeeplinkcheck) {
 8459:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8460:                 }
 8461:                 if ($deeplinkblock) {
 8462:                     $thisallowed='D';
 8463:                 } elsif ($noblockcheck) {
 8464:                     $thisallowed.=$value;
 8465:                 } else {
 8466:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8467:                     if (@blockers > 0) {
 8468:                         $thisallowed = 'B';
 8469:                     } else {
 8470:                         $thisallowed.=$value;
 8471:                     }
 8472:                 }
 8473:             }
 8474:         } else {
 8475:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8476:             if ($refuri) {
 8477:                 if ($refuri =~ m|^/adm/|) {
 8478:                     $thisallowed='F';
 8479:                 } else {
 8480:                     $refuri=&declutter($refuri);
 8481:                     my ($match) = &is_on_map($refuri);
 8482:                     if ($match) {
 8483:                         my $deeplinkblock;
 8484:                         unless ($nodeeplinkcheck) {
 8485:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8486:                         }
 8487:                         if ($deeplinkblock) {
 8488:                             $thisallowed='D';
 8489:                         } elsif ($noblockcheck) {
 8490:                             $thisallowed='F';
 8491:                         } else {
 8492:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8493:                             if (@blockers > 0) {
 8494:                                 $thisallowed = 'B';
 8495:                             } else {
 8496:                                 $thisallowed='F';
 8497:                             }
 8498:                         }
 8499:                     }
 8500:                 }
 8501:             }
 8502:         }
 8503:     }
 8504: 
 8505:     if ($priv eq 'bre'
 8506: 	&& $thisallowed ne 'F' 
 8507: 	&& $thisallowed ne '2'
 8508: 	&& &is_portfolio_url($uri)) {
 8509: 	$thisallowed = &portfolio_access($uri,$clientip);
 8510:     }
 8511: 
 8512: # Full access at system, domain or course-wide level? Exit.
 8513:     if ($thisallowed=~/F/) {
 8514: 	return 'F';
 8515:     }
 8516: 
 8517: # If this is generating or modifying users, exit with special codes
 8518: 
 8519:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8520: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8521: 	    my ($audom,$auname)=split('/',$uri);
 8522: # no author name given, so this just checks on the general right to make a co-author in this domain
 8523: 	    unless ($auname) { return $thisallowed; }
 8524: # an author name is given, so we are about to actually make a co-author for a certain account
 8525: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8526: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8527: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8528: 	}
 8529: 	return $thisallowed;
 8530:     }
 8531: #
 8532: # Gathered so far: system, domain and course wide privileges
 8533: #
 8534: # Course: See if uri or referer is an individual resource that is part of 
 8535: # the course
 8536: 
 8537:     if ($env{'request.course.id'}) {
 8538: 
 8539: # If this is modifying password (internal auth) domains must match for user and user's role.
 8540: 
 8541:         if ($priv eq 'mip') {
 8542:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8543:                 return $thisallowed;
 8544:             } else {
 8545:                 return '';
 8546:             }
 8547:         }
 8548: 
 8549:        $courseprivid=$env{'request.course.id'};
 8550:        if ($env{'request.course.sec'}) {
 8551:           $courseprivid.='/'.$env{'request.course.sec'};
 8552:        }
 8553:        $courseprivid=~s/\_/\//;
 8554:        my $checkreferer=1;
 8555:        my ($match,$cond)=&is_on_map($uri);
 8556:        if ($match) {
 8557:            $statecond=$cond;
 8558:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8559:                =~/\Q$priv\E\&([^\:]*)/) {
 8560:                my $value = $1;
 8561:                if ($priv eq 'bre') {
 8562:                    my $deeplinkblock;
 8563:                    unless ($nodeeplinkcheck) {
 8564:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8565:                    }
 8566:                    if ($deeplinkblock) {
 8567:                        $thisallowed = 'D';
 8568:                    } elsif ($noblockcheck) {
 8569:                        $thisallowed.=$value;
 8570:                    } else {
 8571:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8572:                        if (@blockers > 0) {
 8573:                            $thisallowed = 'B';
 8574:                        } else {
 8575:                            $thisallowed.=$value;
 8576:                        }
 8577:                    }
 8578:                } else {
 8579:                    $thisallowed.=$value;
 8580:                }
 8581:                $checkreferer=0;
 8582:            }
 8583:        }
 8584: 
 8585:        if ($checkreferer) {
 8586: 	  my $refuri=$env{'httpref.'.$orguri};
 8587:             unless ($refuri) {
 8588:                 foreach my $key (keys(%env)) {
 8589: 		    if ($key=~/^httpref\..*\*/) {
 8590: 			my $pattern=$key;
 8591:                         $pattern=~s/^httpref\.\/res\///;
 8592:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8593:                         $pattern=~s/\//\\\//g;
 8594:                         if ($orguri=~/$pattern/) {
 8595: 			    $refuri=$env{$key};
 8596:                         }
 8597:                     }
 8598:                 }
 8599:             }
 8600: 
 8601:          if ($refuri) { 
 8602: 	  $refuri=&declutter($refuri);
 8603:           my ($match,$cond)=&is_on_map($refuri);
 8604:             if ($match) {
 8605:               my $refstatecond=$cond;
 8606:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8607:                   =~/\Q$priv\E\&([^\:]*)/) {
 8608:                   my $value = $1;
 8609:                   if ($priv eq 'bre') {
 8610:                       my $deeplinkblock;
 8611:                       unless ($nodeeplinkcheck) {
 8612:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8613:                       }
 8614:                       if ($deeplinkblock) {
 8615:                           $thisallowed = 'D';
 8616:                       } elsif ($noblockcheck) {
 8617:                           $thisallowed.=$value;
 8618:                       } else {
 8619:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8620:                           if (@blockers > 0) {
 8621:                               $thisallowed = 'B';
 8622:                           } else {
 8623:                               $thisallowed.=$value;
 8624:                           }
 8625:                       }
 8626:                   } else {
 8627:                       $thisallowed.=$value;
 8628:                   }
 8629:                   $uri=$refuri;
 8630:                   $statecond=$refstatecond;
 8631:               }
 8632:           }
 8633:         }
 8634:        }
 8635:    }
 8636: 
 8637: #
 8638: # Gathered now: all privileges that could apply, and condition number
 8639: # 
 8640: #
 8641: # Full or no access?
 8642: #
 8643: 
 8644:     if ($thisallowed=~/F/) {
 8645: 	return 'F';
 8646:     }
 8647: 
 8648:     unless ($thisallowed) {
 8649:         return '';
 8650:     }
 8651: 
 8652: # Restrictions exist, deal with them
 8653: #
 8654: #   C:according to course preferences
 8655: #   R:according to resource settings
 8656: #   L:unless locked
 8657: #   X:according to user session state
 8658: #
 8659: 
 8660: # Possibly locked functionality, check all courses
 8661: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8662: # Locks might take effect only after 10 minutes cache expiration for other
 8663: # courses, and 2 minutes for current course, in which user has st or ta role
 8664: # which is neither expired nor a future role (unless current course).
 8665: 
 8666:     my ($needlockcheck,$now,$crsonly);
 8667:     if ($thisallowed=~/L/) {
 8668:         $now = time;
 8669:         if ($priv eq 'bre') {
 8670:             if ($uri ne '') {
 8671:                 if ($orguri =~ m{^/+res/}) {
 8672:                     if ($uri =~ m{^lib/templates/}) {
 8673:                         if ($env{'request.course.id'}) {
 8674:                             $crsonly = 1;
 8675:                             $needlockcheck = 1;
 8676:                         }
 8677:                     } else {
 8678:                         $needlockcheck = 1;
 8679:                     }
 8680:                 } elsif ($env{'request.course.id'}) {
 8681:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8682:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8683:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8684:                         $crsonly = 1;
 8685:                     }
 8686:                     $needlockcheck = 1;
 8687:                 }
 8688:             }
 8689:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8690:             $needlockcheck = 1;
 8691:         }
 8692:     }
 8693:     if ($needlockcheck) {
 8694:         foreach my $envkey (keys(%env)) {
 8695:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8696:                my $courseid=$2;
 8697:                my $roleid=$1.'.'.$2;
 8698:                $courseid=~s/^\///;
 8699:                unless ($env{'request.role'} eq $roleid) {
 8700:                    my ($start,$end) = split(/\./,$env{$envkey});
 8701:                    next unless (($now >= $start) && (!$end || $end > $now));
 8702:                }
 8703:                my $expiretime=600;
 8704:                if ($env{'request.role'} eq $roleid) {
 8705: 		  $expiretime=120;
 8706:                }
 8707: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8708:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8709:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8710: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8711:                }
 8712:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8713:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8714: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8715:                        &log($env{'user.domain'},$env{'user.name'},
 8716:                             $env{'user.home'},
 8717:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8718:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8719:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8720: 		       return '';
 8721:                    }
 8722:                }
 8723:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8724:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8725: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8726:                        &log($env{'user.domain'},$env{'user.name'},
 8727:                             $env{'user.home'},
 8728:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8729:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8730:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8731: 		       return '';
 8732:                    }
 8733:                }
 8734: 	   }
 8735:        }
 8736:     }
 8737: 
 8738: #
 8739: # Rest of the restrictions depend on selected course
 8740: #
 8741: 
 8742:     unless ($env{'request.course.id'}) {
 8743: 	if ($thisallowed eq 'A') {
 8744: 	    return 'A';
 8745:         } elsif ($thisallowed eq 'B') {
 8746:             return 'B';
 8747: 	} else {
 8748: 	    return '1';
 8749: 	}
 8750:     }
 8751: 
 8752: #
 8753: # Now user is definitely in a course
 8754: #
 8755: 
 8756: 
 8757: # Course preferences
 8758: 
 8759:    if ($thisallowed=~/C/) {
 8760:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8761:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8762:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8763: 	   =~/\Q$rolecode\E/) {
 8764: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8765: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8766: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8767: 			$env{'request.course.id'});
 8768: 	   }
 8769:            return '';
 8770:        }
 8771: 
 8772:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8773: 	   =~/\Q$unamedom\E/) {
 8774: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8775: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8776: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8777: 			$env{'request.course.id'});
 8778: 	   }
 8779:            return '';
 8780:        }
 8781:    }
 8782: 
 8783: # Resource preferences
 8784: 
 8785:    if ($thisallowed=~/R/) {
 8786:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8787:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8788: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8789: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8790: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8791: 	   }
 8792: 	   return '';
 8793:        }
 8794:    }
 8795: 
 8796: # Restricted for deeplinked session?
 8797: 
 8798:     if ($env{'request.deeplink.login'}) {
 8799:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8800:             if (!$symb) { $symb=&symbread($uri,1); }
 8801:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8802:                 return '';
 8803:             }
 8804:         }
 8805:     }
 8806: 
 8807: # Restricted by state or randomout?
 8808: 
 8809:    if ($thisallowed=~/X/) {
 8810:       if ($env{'acc.randomout'}) {
 8811: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8812:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8813:             return ''; 
 8814:          }
 8815:       }
 8816:       if (&condval($statecond)) {
 8817: 	 return '2';
 8818:       } else {
 8819:          return '';
 8820:       }
 8821:    }
 8822: 
 8823:     if ($thisallowed eq 'A') {
 8824: 	return 'A';
 8825:     } elsif ($thisallowed eq 'B') {
 8826:         return 'B';
 8827:     } elsif ($thisallowed eq 'D') {
 8828:         return 'D';
 8829:     }
 8830:    return 'F';
 8831: }
 8832: 
 8833: # ------------------------------------------- Check construction space access
 8834: 
 8835: sub constructaccess {
 8836:     my ($url,$setpriv)=@_;
 8837: 
 8838: # We do not allow editing of previous versions of files
 8839:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8840: 
 8841: # Get username and domain from URL
 8842:     my ($ownername,$ownerdomain,$ownerhome);
 8843: 
 8844:     ($ownerdomain,$ownername) =
 8845:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8846: 
 8847: # The URL does not really point to any authorspace, forget it
 8848:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8849: 
 8850: # Now we need to see if the user has access to the authorspace of
 8851: # $ownername at $ownerdomain
 8852: 
 8853:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8854: # Real author for this?
 8855:        $ownerhome = $env{'user.home'};
 8856:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8857:           return ($ownername,$ownerdomain,$ownerhome);
 8858:        }
 8859:     } else {
 8860: # Co-author for this?
 8861:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8862:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8863:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8864:             return ($ownername,$ownerdomain,$ownerhome);
 8865:         }
 8866:         if ($env{'request.course.id'}) {
 8867:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8868:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8869:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8870:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8871:                     return ($ownername,$ownerdomain,$ownerhome);
 8872:                 }
 8873:             }
 8874:         }
 8875:     }
 8876: 
 8877: # We don't have any access right now. If we are not possibly going to do anything about this,
 8878: # we might as well leave
 8879:    unless ($setpriv) { return ''; }
 8880: 
 8881: # Backdoor access?
 8882:     my $allowed=&allowed('eco',$ownerdomain);
 8883: # Nope
 8884:     unless ($allowed) { return ''; }
 8885: # Looks like we may have access, but could be locked by the owner of the construction space
 8886:     if ($allowed eq 'U') {
 8887:         my %blocked=&get('environment',['domcoord.author'],
 8888:                          $ownerdomain,$ownername);
 8889: # Is blocked by owner
 8890:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8891:     }
 8892:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8893: # Grant temporary access
 8894:         my $then=$env{'user.login.time'};
 8895:         my $update=$env{'user.update.time'};
 8896:         if (!$update) { $update = $then; }
 8897:         my $refresh=$env{'user.refresh.time'};
 8898:         if (!$refresh) { $refresh = $update; }
 8899:         my $now = time;
 8900:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8901:                            $now,'ca','constructaccess');
 8902:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8903:         return($ownername,$ownerdomain,$ownerhome);
 8904:     }
 8905: # No business here
 8906:     return '';
 8907: }
 8908: 
 8909: # ----------------------------------------------------------- Content Blocking
 8910: 
 8911: {
 8912: # Caches for faster Course Contents display where content blocking
 8913: # is in operation (i.e., interval param set) for timed quiz.
 8914: #
 8915: # User for whom data are being temporarily cached.
 8916: my $cacheduser='';
 8917: # Course for which data are being temporarily cached.
 8918: my $cachedcid='';
 8919: # Cached blockers for this user (a hash of blocking items). 
 8920: my %cachedblockers=();
 8921: # When the data were last cached.
 8922: my $cachedlast='';
 8923: 
 8924: sub load_all_blockers {
 8925:     my ($uname,$udom)=@_;
 8926:     if (($uname ne '') && ($udom ne '')) { 
 8927:         if (($cacheduser eq $uname.':'.$udom) &&
 8928:             ($cachedcid eq $env{'request.course.id'}) &&
 8929:             (abs($cachedlast-time)<5)) {
 8930:             return;
 8931:         }
 8932:     }
 8933:     $cachedlast=time;
 8934:     $cacheduser=$uname.':'.$udom;
 8935:     $cachedcid=$env{'request.course.id'};
 8936:     %cachedblockers = &get_commblock_resources();
 8937:     return;
 8938: }
 8939: 
 8940: sub get_comm_blocks {
 8941:     my ($cdom,$cnum) = @_;
 8942:     if ($cdom eq '' || $cnum eq '') {
 8943:         return unless ($env{'request.course.id'});
 8944:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8945:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8946:     }
 8947:     my %commblocks;
 8948:     my $hashid=$cdom.'_'.$cnum;
 8949:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8950:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8951:         %commblocks = %{$blocksref};
 8952:     } else {
 8953:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8954:         my $cachetime = 600;
 8955:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8956:     }
 8957:     return %commblocks;
 8958: }
 8959: 
 8960: sub get_commblock_resources {
 8961:     my ($blocks) = @_;
 8962:     my %blockers = ();
 8963:     return %blockers unless ($env{'request.course.id'});
 8964:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8965:     if ($env{'request.course.sec'}) {
 8966:         $courseurl .= '/'.$env{'request.course.sec'};
 8967:     }
 8968:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8969:     my %commblocks;
 8970:     if (ref($blocks) eq 'HASH') {
 8971:         %commblocks = %{$blocks};
 8972:     } else {
 8973:         %commblocks = &get_comm_blocks();
 8974:     }
 8975:     return %blockers unless (keys(%commblocks) > 0); 
 8976:     my $navmap = Apache::lonnavmaps::navmap->new();
 8977:     return %blockers unless (ref($navmap));
 8978:     my $now = time;
 8979:     foreach my $block (keys(%commblocks)) {
 8980:         if ($block =~ /^(\d+)____(\d+)$/) {
 8981:             my ($start,$end) = ($1,$2);
 8982:             if ($start <= $now && $end >= $now) {
 8983:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8984:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8985:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8986:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8987:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8988:                             }
 8989:                         }
 8990:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8991:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8992:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8993:                             }
 8994:                         }
 8995:                     }
 8996:                 }
 8997:             }
 8998:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8999:             my $item = $1;
 9000:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9001:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9002:                     my (@interval,$mapname);
 9003:                     my $type = 'map';
 9004:                     if ($item eq 'course') {
 9005:                         $type = 'course';
 9006:                         @interval=&EXT("resource.0.interval");
 9007:                     } else {
 9008:                         if ($item =~ /___\d+___/) {
 9009:                             $type = 'resource';
 9010:                             @interval=&EXT("resource.0.interval",$item);
 9011:                         } else {
 9012:                             $mapname = &deversion($item);
 9013:                             if (ref($navmap)) {
 9014:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9015:                                 @interval = ($timelimit,'map');
 9016:                             }
 9017:                         }
 9018:                     }
 9019:                     if ($interval[0] =~ /^(\d+)/) {
 9020:                         my $timelimit = $1; 
 9021:                         my $first_access;
 9022:                         if ($type eq 'resource') {
 9023:                             $first_access=&get_first_access($interval[1],$item);
 9024:                         } elsif ($type eq 'map') {
 9025:                             $first_access=&get_first_access($interval[1],undef,$item);
 9026:                         } else {
 9027:                             $first_access=&get_first_access($interval[1]);
 9028:                         }
 9029:                         if ($first_access) {
 9030:                             my $timesup = $first_access+$timelimit;
 9031:                             if ($timesup > $now) {
 9032:                                 my $activeblock;
 9033:                                 if ($type eq 'resource') {
 9034:                                     if (ref($navmap)) {
 9035:                                         my $res = $navmap->getBySymb($item);
 9036:                                         if ($res->answerable()) {
 9037:                                             $activeblock = 1;
 9038:                                         }
 9039:                                     }
 9040:                                 } elsif ($type eq 'map') {
 9041:                                     my $mapsymb = &symbread($mapname,1);
 9042:                                     if (($mapsymb) && (ref($navmap))) {
 9043:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9044:                                         if (ref($mapres)) {
 9045:                                             my $first = $mapres->map_start();
 9046:                                             my $finish = $mapres->map_finish();
 9047:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9048:                                             if (ref($it)) {
 9049:                                                 my $res;
 9050:                                                 while ($res = $it->next(undef,1)) {
 9051:                                                     next unless (ref($res));
 9052:                                                     my $symb = $res->symb();
 9053:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9054:                                                     @interval=&EXT("resource.0.interval",$symb);
 9055:                                                     if ($interval[1] eq 'map') {
 9056:                                                         if ($res->answerable()) {
 9057:                                                             $activeblock = 1;
 9058:                                                             last;
 9059:                                                         }
 9060:                                                     }
 9061:                                                 }
 9062:                                             }
 9063:                                         }
 9064:                                     }
 9065:                                 }
 9066:                                 if ($activeblock) {
 9067:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9068:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9069:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9070:                                          }
 9071:                                     }
 9072:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9073:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9074:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9075:                                         }
 9076:                                     }
 9077:                                 }
 9078:                             }
 9079:                         }
 9080:                     }
 9081:                 }
 9082:             }
 9083:         }
 9084:     }
 9085:     return %blockers;
 9086: }
 9087: 
 9088: sub has_comm_blocking {
 9089:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9090:     my @blockers;
 9091:     return unless ($env{'request.course.id'});
 9092:     return unless ($priv eq 'bre');
 9093:     return if ($env{'request.state'} eq 'construct');
 9094:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9095:     if ($env{'request.course.sec'}) {
 9096:         $courseurl .= '/'.$env{'request.course.sec'};
 9097:     }
 9098:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9099:     my %blockinfo;
 9100:     if (ref($blocks) eq 'HASH') {
 9101:         %blockinfo = &get_commblock_resources($blocks);
 9102:     } else {
 9103:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9104:         %blockinfo = %cachedblockers;
 9105:     }
 9106:     return unless (keys(%blockinfo) > 0);
 9107:     my (%possibles,@symbs);
 9108:     if (!$symb) {
 9109:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9110:     }
 9111:     if ($symb) {
 9112:         @symbs = ($symb);
 9113:     } elsif (keys(%possibles)) { 
 9114:         @symbs = keys(%possibles);
 9115:     }
 9116:     my $noblock;
 9117:     foreach my $symb (@symbs) {
 9118:         last if ($noblock);
 9119:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9120:         foreach my $block (keys(%blockinfo)) {
 9121:             if ($block =~ /^firstaccess____(.+)$/) {
 9122:                 my $item = $1;
 9123:                 unless ($blocked) {
 9124:                     if (($item eq $map) || ($item eq $symb)) {
 9125:                         $noblock = 1;
 9126:                         last;
 9127:                     }
 9128:                 }
 9129:             }
 9130:             if (ref($blockinfo{$block}) eq 'HASH') {
 9131:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9132:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9133:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9134:                             push(@blockers,$block);
 9135:                         }
 9136:                     }
 9137:                 }
 9138:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9139:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9140:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9141:                             push(@blockers,$block);
 9142:                         }
 9143:                     }
 9144:                 }
 9145:             }
 9146:         }
 9147:     }
 9148:     unless ($noblock) { 
 9149:         return @blockers;
 9150:     }
 9151:     return;
 9152: }
 9153: }
 9154: 
 9155: sub deeplink_check {
 9156:     my ($priv,$symb,$uri) = @_;
 9157:     return unless ($env{'request.course.id'});
 9158:     return unless ($priv eq 'bre');
 9159:     return if ($env{'request.state'} eq 'construct');
 9160:     return if ($env{'request.role.adv'});
 9161:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9162:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9163:     my (%possibles,@symbs);
 9164:     if (!$symb) {
 9165:         $symb = &symbread($uri,1,1,1,\%possibles);
 9166:     }
 9167:     if ($symb) {
 9168:         @symbs = ($symb);
 9169:     } elsif (keys(%possibles)) {
 9170:         @symbs = keys(%possibles);
 9171:     }
 9172: 
 9173:     my ($deeplink_symb,$allow);
 9174:     if ($env{'request.deeplink.login'}) {
 9175:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9176:     }
 9177:     foreach my $symb (@symbs) {
 9178:         last if ($allow);
 9179:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9180:         if ($deeplink eq '') {
 9181:             $allow = 1;
 9182:         } else {
 9183:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9184:             if ($state ne 'only') {
 9185:                 $allow = 1;
 9186:             } else {
 9187:                 my $check_deeplink_entry;
 9188:                 if ($protect ne 'none') {
 9189:                     my ($acctype,$item) = split(/:/,$protect);
 9190:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9191:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9192:                             $check_deeplink_entry = 1
 9193:                         }
 9194:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9195:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9196:                             $check_deeplink_entry = 1;
 9197:                         }
 9198:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9199:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9200:                             $check_deeplink_entry = 1;
 9201:                         }
 9202:                     }
 9203:                 }
 9204:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9205:                     if ($scope eq 'res') {
 9206:                         if ($symb eq $deeplink_symb) {
 9207:                             $allow = 1;
 9208:                         }
 9209:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9210:                         my ($map_from_symb,$map_from_login);
 9211:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9212:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9213:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9214:                         } else {
 9215:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9216:                         }
 9217:                         if (($map_from_symb) && ($map_from_login)) {
 9218:                             if ($map_from_symb eq $map_from_login) {
 9219:                                 $allow = 1;
 9220:                             } elsif ($scope eq 'rec') {
 9221:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9222:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9223:                                     $allow = 1;
 9224:                                 }
 9225:                             }
 9226:                         }
 9227:                     }
 9228:                 }
 9229:             }
 9230:         }
 9231:     }
 9232:     return if ($allow);
 9233:     return 1;
 9234: }
 9235: 
 9236: # -------------------------------- Deversion and split uri into path an filename   
 9237: 
 9238: #
 9239: #   Removes the version from a URI and
 9240: #   splits it in to its filename and path to the filename.
 9241: #   Seems like File::Basename could have done this more clearly.
 9242: #   Parameters:
 9243: #      $uri   - input URI
 9244: #   Returns:
 9245: #     Two element list consisting of 
 9246: #     $pathname  - the URI up to and excluding the trailing /
 9247: #     $filename  - The part of the URI following the last /
 9248: #  NOTE:
 9249: #    Another realization of this is simply:
 9250: #    use File::Basename;
 9251: #    ...
 9252: #    $uri = shift;
 9253: #    $filename = basename($uri);
 9254: #    $path     = dirname($uri);
 9255: #    return ($filename, $path);
 9256: #
 9257: #     The implementation below is probably faster however.
 9258: #
 9259: sub split_uri_for_cond {
 9260:     my $uri=&deversion(&declutter(shift));
 9261:     my @uriparts=split(/\//,$uri);
 9262:     my $filename=pop(@uriparts);
 9263:     my $pathname=join('/',@uriparts);
 9264:     return ($pathname,$filename);
 9265: }
 9266: # --------------------------------------------------- Is a resource on the map?
 9267: 
 9268: sub is_on_map {
 9269:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9270:     #Trying to find the conditional for the file
 9271:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9272: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9273:     if ($match) {
 9274: 	return (1,$1);
 9275:     } else {
 9276: 	return (0,0);
 9277:     }
 9278: }
 9279: 
 9280: # --------------------------------------------------------- Get symb from alias
 9281: 
 9282: sub get_symb_from_alias {
 9283:     my $symb=shift;
 9284:     my ($map,$resid,$url)=&decode_symb($symb);
 9285: # Already is a symb
 9286:     if ($url) { return $symb; }
 9287: # Must be an alias
 9288:     my $aliassymb='';
 9289:     my %bighash;
 9290:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9291:                             &GDBM_READER(),0640)) {
 9292:         my $rid=$bighash{'mapalias_'.$symb};
 9293: 	if ($rid) {
 9294: 	    my ($mapid,$resid)=split(/\./,$rid);
 9295: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9296: 				    $resid,$bighash{'src_'.$rid});
 9297: 	}
 9298:         untie %bighash;
 9299:     }
 9300:     return $aliassymb;
 9301: }
 9302: 
 9303: # ----------------------------------------------------------------- Define Role
 9304: 
 9305: sub definerole {
 9306:   if (allowed('mcr','/')) {
 9307:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9308:     foreach my $role (split(':',$sysrole)) {
 9309: 	my ($crole,$cqual)=split(/\&/,$role);
 9310:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9311:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9312: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9313:                return "refused:s:$crole&$cqual"; 
 9314:             }
 9315:         }
 9316:     }
 9317:     foreach my $role (split(':',$domrole)) {
 9318: 	my ($crole,$cqual)=split(/\&/,$role);
 9319:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9320:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9321: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9322:                return "refused:d:$crole&$cqual"; 
 9323:             }
 9324:         }
 9325:     }
 9326:     foreach my $role (split(':',$courole)) {
 9327: 	my ($crole,$cqual)=split(/\&/,$role);
 9328:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9329:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9330: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9331:                return "refused:c:$crole&$cqual"; 
 9332:             }
 9333:         }
 9334:     }
 9335:     my $uhome;
 9336:     if (($uname ne '') && ($udom ne '')) {
 9337:         $uhome = &homeserver($uname,$udom);
 9338:         return $uhome if ($uhome eq 'no_host');
 9339:     } else {
 9340:         $uname = $env{'user.name'};
 9341:         $udom = $env{'user.domain'};
 9342:         $uhome = $env{'user.home'};
 9343:     }
 9344:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9345:                 "$udom:$uname:rolesdef_$rolename=".
 9346:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9347:     return reply($command,$uhome);
 9348:   } else {
 9349:     return 'refused';
 9350:   }
 9351: }
 9352: 
 9353: # ---------------- Make a metadata query against the network of library servers
 9354: 
 9355: sub metadata_query {
 9356:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9357:     my %rhash;
 9358:     my %libserv = &all_library();
 9359:     my @server_list = (defined($server_array) ? @$server_array
 9360:                                               : keys(%libserv) );
 9361:     for my $server (@server_list) {
 9362:         my $domains = ''; 
 9363:         if (ref($domains_hash) eq 'HASH') {
 9364:             $domains = $domains_hash->{$server}; 
 9365:         }
 9366: 	unless ($custom or $customshow) {
 9367: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9368: 	    $rhash{$server}=$reply;
 9369: 	}
 9370: 	else {
 9371: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9372: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9373: 			     $server);
 9374: 	    $rhash{$server}=$reply;
 9375: 	}
 9376:     }
 9377:     return \%rhash;
 9378: }
 9379: 
 9380: # ----------------------------------------- Send log queries and wait for reply
 9381: 
 9382: sub log_query {
 9383:     my ($uname,$udom,$query,%filters)=@_;
 9384:     my $uhome=&homeserver($uname,$udom);
 9385:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9386:     my $uhost=&hostname($uhome);
 9387:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9388:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9389:                        $uhome);
 9390:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9391:     return get_query_reply($queryid);
 9392: }
 9393: 
 9394: # -------------------------- Update MySQL table for portfolio file
 9395: 
 9396: sub update_portfolio_table {
 9397:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9398:     if ($group ne '') {
 9399:         $file_name =~s /^\Q$group\E//;
 9400:     }
 9401:     my $homeserver = &homeserver($uname,$udom);
 9402:     my $queryid=
 9403:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9404:                ':'.&escape($file_name).':'.$action,$homeserver);
 9405:     my $reply = &get_query_reply($queryid);
 9406:     return $reply;
 9407: }
 9408: 
 9409: # -------------------------- Update MySQL allusers table
 9410: 
 9411: sub update_allusers_table {
 9412:     my ($uname,$udom,$names) = @_;
 9413:     my $homeserver = &homeserver($uname,$udom);
 9414:     my $queryid=
 9415:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9416:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9417:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9418:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9419:                'generation='.&escape($names->{'generation'}).'%%'.
 9420:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9421:                'id='.&escape($names->{'id'}),$homeserver);
 9422:     return;
 9423: }
 9424: 
 9425: # ------- Request retrieval of institutional classlists for course(s)
 9426: 
 9427: sub fetch_enrollment_query {
 9428:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9429:     my ($homeserver,$sleep,$loopmax);
 9430:     my $maxtries = 1;
 9431:     if ($context eq 'automated') {
 9432:         $homeserver = $perlvar{'lonHostID'};
 9433:         $sleep = 2;
 9434:         $loopmax = 100;
 9435:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9436:     } else {
 9437:         $homeserver = &homeserver($cnum,$dom);
 9438:     }
 9439:     my $host=&hostname($homeserver);
 9440:     my $cmd = '';
 9441:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9442:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9443:     }
 9444:     $cmd =~ s/%%$//;
 9445:     $cmd = &escape($cmd);
 9446:     my $query = 'fetchenrollment';
 9447:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9448:     unless ($queryid=~/^\Q$host\E\_/) { 
 9449:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9450:         return 'error: '.$queryid;
 9451:     }
 9452:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9453:     my $tries = 1;
 9454:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9455:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9456:         $tries ++;
 9457:     }
 9458:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9459:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9460:     } else {
 9461:         my @responses = split(/:/,$reply);
 9462:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9463:             foreach my $line (@responses) {
 9464:                 my ($key,$value) = split(/=/,$line,2);
 9465:                 $$replyref{$key} = $value;
 9466:             }
 9467:         } else {
 9468:             my $pathname = LONCAPA::tempdir();
 9469:             foreach my $line (@responses) {
 9470:                 my ($key,$value) = split(/=/,$line);
 9471:                 $$replyref{$key} = $value;
 9472:                 if ($value > 0) {
 9473:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9474:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9475:                         my $destname = $pathname.'/'.$filename;
 9476:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9477:                         if ($xml_classlist =~ /^error/) {
 9478:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9479:                         } else {
 9480:                             if ( open(FILE,">",$destname) ) {
 9481:                                 print FILE &unescape($xml_classlist);
 9482:                                 close(FILE);
 9483:                             } else {
 9484:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9485:                             }
 9486:                         }
 9487:                     }
 9488:                 }
 9489:             }
 9490:         }
 9491:         return 'ok';
 9492:     }
 9493:     return 'error';
 9494: }
 9495: 
 9496: sub get_query_reply {
 9497:     my ($queryid,$sleep,$loopmax) = @_;
 9498:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9499:         $sleep = 0.2;
 9500:     }
 9501:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9502:         $loopmax = 100;
 9503:     }
 9504:     my $replyfile=LONCAPA::tempdir().$queryid;
 9505:     my $reply='';
 9506:     for (1..$loopmax) {
 9507: 	sleep($sleep);
 9508:         if (-e $replyfile.'.end') {
 9509: 	    if (open(my $fh,"<",$replyfile)) {
 9510: 		$reply = join('',<$fh>);
 9511: 		close($fh);
 9512: 	   } else { return 'error: reply_file_error'; }
 9513:            return &unescape($reply);
 9514: 	}
 9515:     }
 9516:     return 'timeout:'.$queryid;
 9517: }
 9518: 
 9519: sub courselog_query {
 9520: #
 9521: # possible filters:
 9522: # url: url or symb
 9523: # username
 9524: # domain
 9525: # action: view, submit, grade
 9526: # start: timestamp
 9527: # end: timestamp
 9528: #
 9529:     my (%filters)=@_;
 9530:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9531:     if ($filters{'url'}) {
 9532: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9533:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9534:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9535:     }
 9536:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9537:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9538:     return &log_query($cname,$cdom,'courselog',%filters);
 9539: }
 9540: 
 9541: sub userlog_query {
 9542: #
 9543: # possible filters:
 9544: # action: log check role
 9545: # start: timestamp
 9546: # end: timestamp
 9547: #
 9548:     my ($uname,$udom,%filters)=@_;
 9549:     return &log_query($uname,$udom,'userlog',%filters);
 9550: }
 9551: 
 9552: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9553: 
 9554: sub auto_run {
 9555:     my ($cnum,$cdom) = @_;
 9556:     my $response = 0;
 9557:     my $settings;
 9558:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9559:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9560:         $settings = $domconfig{'autoenroll'};
 9561:         if ($settings->{'run'} eq '1') {
 9562:             $response = 1;
 9563:         }
 9564:     } else {
 9565:         my $homeserver;
 9566:         if (&is_course($cdom,$cnum)) {
 9567:             $homeserver = &homeserver($cnum,$cdom);
 9568:         } else {
 9569:             $homeserver = &domain($cdom,'primary');
 9570:         }
 9571:         if ($homeserver ne 'no_host') {
 9572:             $response = &reply('autorun:'.$cdom,$homeserver);
 9573:         }
 9574:     }
 9575:     return $response;
 9576: }
 9577: 
 9578: sub auto_get_sections {
 9579:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9580:     my $homeserver;
 9581:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9582:         $homeserver = &homeserver($cnum,$cdom);
 9583:     }
 9584:     if (!defined($homeserver)) { 
 9585:         if ($cdom =~ /^$match_domain$/) {
 9586:             $homeserver = &domain($cdom,'primary');
 9587:         }
 9588:     }
 9589:     my @secs;
 9590:     if (defined($homeserver)) {
 9591:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9592:         unless ($response eq 'refused') {
 9593:             @secs = split(/:/,$response);
 9594:         }
 9595:     }
 9596:     return @secs;
 9597: }
 9598: 
 9599: sub auto_new_course {
 9600:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9601:     my $homeserver = &homeserver($cnum,$cdom);
 9602:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9603:     return $response;
 9604: }
 9605: 
 9606: sub auto_validate_courseID {
 9607:     my ($cnum,$cdom,$inst_course_id) = @_;
 9608:     my $homeserver = &homeserver($cnum,$cdom);
 9609:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9610:     return $response;
 9611: }
 9612: 
 9613: sub auto_validate_instcode {
 9614:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9615:     my ($homeserver,$response);
 9616:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9617:         $homeserver = &homeserver($cnum,$cdom);
 9618:     }
 9619:     if (!defined($homeserver)) {
 9620:         if ($cdom =~ /^$match_domain$/) {
 9621:             $homeserver = &domain($cdom,'primary');
 9622:         }
 9623:     }
 9624:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9625:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9626:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9627:     return ($outcome,$description,$defaultcredits);
 9628: }
 9629: 
 9630: sub auto_validate_inst_crosslist {
 9631:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9632:     my ($homeserver,$response);
 9633:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9634:         $homeserver = &homeserver($cnum,$cdom);
 9635:     }
 9636:     if (!defined($homeserver)) {
 9637:         if ($cdom =~ /^$match_domain$/) {
 9638:             $homeserver = &domain($cdom,'primary');
 9639:         }
 9640:     }
 9641:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9642:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9643:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9644:                          &escape($coowner),$homeserver);
 9645:     }
 9646:     return $response;
 9647: }
 9648: 
 9649: sub auto_create_password {
 9650:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9651:     my ($homeserver,$response);
 9652:     my $create_passwd = 0;
 9653:     my $authchk = '';
 9654:     if ($udom =~ /^$match_domain$/) {
 9655:         $homeserver = &domain($udom,'primary');
 9656:     }
 9657:     if ($homeserver eq '') {
 9658:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9659:             $homeserver = &homeserver($cnum,$cdom);
 9660:         }
 9661:     }
 9662:     if ($homeserver eq '') {
 9663:         $authchk = 'nodomain';
 9664:     } else {
 9665:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9666:         if ($response eq 'refused') {
 9667:             $authchk = 'refused';
 9668:         } else {
 9669:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9670:         }
 9671:     }
 9672:     return ($authparam,$create_passwd,$authchk);
 9673: }
 9674: 
 9675: sub auto_photo_permission {
 9676:     my ($cnum,$cdom,$students) = @_;
 9677:     my $homeserver = &homeserver($cnum,$cdom);
 9678:     my ($outcome,$perm_reqd,$conditions) = 
 9679: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9680:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9681: 	return (undef,undef);
 9682:     }
 9683:     return ($outcome,$perm_reqd,$conditions);
 9684: }
 9685: 
 9686: sub auto_checkphotos {
 9687:     my ($uname,$udom,$pid) = @_;
 9688:     my $homeserver = &homeserver($uname,$udom);
 9689:     my ($result,$resulttype);
 9690:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9691: 				   &escape($uname).':'.&escape($pid),
 9692: 				   $homeserver));
 9693:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9694: 	return (undef,undef);
 9695:     }
 9696:     if ($outcome) {
 9697:         ($result,$resulttype) = split(/:/,$outcome);
 9698:     } 
 9699:     return ($result,$resulttype);
 9700: }
 9701: 
 9702: sub auto_photochoice {
 9703:     my ($cnum,$cdom) = @_;
 9704:     my $homeserver = &homeserver($cnum,$cdom);
 9705:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9706: 						       &escape($cdom),
 9707: 						       $homeserver)));
 9708:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9709: 	return (undef,undef);
 9710:     }
 9711:     return ($update,$comment);
 9712: }
 9713: 
 9714: sub auto_photoupdate {
 9715:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9716:     my $homeserver = &homeserver($cnum,$dom);
 9717:     my $host=&hostname($homeserver);
 9718:     my $cmd = '';
 9719:     my $maxtries = 1;
 9720:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9721:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9722:     }
 9723:     $cmd =~ s/%%$//;
 9724:     $cmd = &escape($cmd);
 9725:     my $query = 'institutionalphotos';
 9726:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9727:     unless ($queryid=~/^\Q$host\E\_/) {
 9728:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9729:         return 'error: '.$queryid;
 9730:     }
 9731:     my $reply = &get_query_reply($queryid);
 9732:     my $tries = 1;
 9733:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9734:         $reply = &get_query_reply($queryid);
 9735:         $tries ++;
 9736:     }
 9737:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9738:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9739:     } else {
 9740:         my @responses = split(/:/,$reply);
 9741:         my $outcome = shift(@responses); 
 9742:         foreach my $item (@responses) {
 9743:             my ($key,$value) = split(/=/,$item);
 9744:             $$photo{$key} = $value;
 9745:         }
 9746:         return $outcome;
 9747:     }
 9748:     return 'error';
 9749: }
 9750: 
 9751: sub auto_instcode_format {
 9752:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9753: 	$cat_order) = @_;
 9754:     my $courses = '';
 9755:     my @homeservers;
 9756:     if ($caller eq 'global') {
 9757: 	my %servers = &get_servers($codedom,'library');
 9758: 	foreach my $tryserver (keys(%servers)) {
 9759: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9760: 		push(@homeservers,$tryserver);
 9761: 	    }
 9762:         }
 9763:     } elsif ($caller eq 'requests') {
 9764:         if ($codedom =~ /^$match_domain$/) {
 9765:             my $chome = &domain($codedom,'primary');
 9766:             unless ($chome eq 'no_host') {
 9767:                 push(@homeservers,$chome);
 9768:             }
 9769:         }
 9770:     } else {
 9771:         push(@homeservers,&homeserver($caller,$codedom));
 9772:     }
 9773:     foreach my $code (keys(%{$instcodes})) {
 9774:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9775:     }
 9776:     chop($courses);
 9777:     my $ok_response = 0;
 9778:     my $response;
 9779:     while (@homeservers > 0 && $ok_response == 0) {
 9780:         my $server = shift(@homeservers); 
 9781:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9782:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9783:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9784: 		split(/:/,$response);
 9785:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9786:             push(@{$codetitles},&str2array($codetitles_str));
 9787:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9788:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9789:             $ok_response = 1;
 9790:         }
 9791:     }
 9792:     if ($ok_response) {
 9793:         return 'ok';
 9794:     } else {
 9795:         return $response;
 9796:     }
 9797: }
 9798: 
 9799: sub auto_instcode_defaults {
 9800:     my ($domain,$returnhash,$code_order) = @_;
 9801:     my @homeservers;
 9802: 
 9803:     my %servers = &get_servers($domain,'library');
 9804:     foreach my $tryserver (keys(%servers)) {
 9805: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9806: 	    push(@homeservers,$tryserver);
 9807: 	}
 9808:     }
 9809: 
 9810:     my $response;
 9811:     foreach my $server (@homeservers) {
 9812:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9813:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9814: 	
 9815: 	foreach my $pair (split(/\&/,$response)) {
 9816: 	    my ($name,$value)=split(/\=/,$pair);
 9817: 	    if ($name eq 'code_order') {
 9818: 		@{$code_order} = split(/\&/,&unescape($value));
 9819: 	    } else {
 9820: 		$returnhash->{&unescape($name)}=&unescape($value);
 9821: 	    }
 9822: 	}
 9823: 	return 'ok';
 9824:     }
 9825: 
 9826:     return $response;
 9827: }
 9828: 
 9829: sub auto_possible_instcodes {
 9830:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9831:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9832:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9833:         return;
 9834:     }
 9835:     my (@homeservers,$uhome);
 9836:     if (defined(&domain($domain,'primary'))) {
 9837:         $uhome=&domain($domain,'primary');
 9838:         push(@homeservers,&domain($domain,'primary'));
 9839:     } else {
 9840:         my %servers = &get_servers($domain,'library');
 9841:         foreach my $tryserver (keys(%servers)) {
 9842:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9843:                 push(@homeservers,$tryserver);
 9844:             }
 9845:         }
 9846:     }
 9847:     my $response;
 9848:     foreach my $server (@homeservers) {
 9849:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9850:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9851:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9852:             split(':',$response);
 9853:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9854:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9855:         foreach my $item (split('&',$cat_title)) {   
 9856:             my ($name,$value)=split('=',$item);
 9857:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9858:         }
 9859:         foreach my $item (split('&',$cat_order)) {
 9860:             my ($name,$value)=split('=',$item);
 9861:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9862:         }
 9863:         return 'ok';
 9864:     }
 9865:     return $response;
 9866: }
 9867: 
 9868: sub auto_courserequest_checks {
 9869:     my ($dom) = @_;
 9870:     my ($homeserver,%validations);
 9871:     if ($dom =~ /^$match_domain$/) {
 9872:         $homeserver = &domain($dom,'primary');
 9873:     }
 9874:     unless ($homeserver eq 'no_host') {
 9875:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9876:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9877:             my @items = split(/&/,$response);
 9878:             foreach my $item (@items) {
 9879:                 my ($key,$value) = split('=',$item);
 9880:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9881:             }
 9882:         }
 9883:     }
 9884:     return %validations; 
 9885: }
 9886: 
 9887: sub auto_courserequest_validation {
 9888:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9889:     my ($homeserver,$response);
 9890:     if ($dom =~ /^$match_domain$/) {
 9891:         $homeserver = &domain($dom,'primary');
 9892:     }
 9893:     unless ($homeserver eq 'no_host') {
 9894:         my $customdata;
 9895:         if (ref($custominfo) eq 'HASH') {
 9896:             $customdata = &freeze_escape($custominfo);
 9897:         }
 9898:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9899:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9900:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9901:                                     $customdata,$homeserver));
 9902:     }
 9903:     return $response;
 9904: }
 9905: 
 9906: sub auto_validate_class_sec {
 9907:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9908:     my $homeserver = &homeserver($cnum,$cdom);
 9909:     my $ownerlist;
 9910:     if (ref($owners) eq 'ARRAY') {
 9911:         $ownerlist = join(',',@{$owners});
 9912:     } else {
 9913:         $ownerlist = $owners;
 9914:     }
 9915:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9916:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9917:     return $response;
 9918: }
 9919: 
 9920: sub auto_instsec_reformat {
 9921:     my ($cdom,$action,$instsecref) = @_;
 9922:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
 9923:     my @homeservers;
 9924:     if (defined(&domain($cdom,'primary'))) {
 9925:         push(@homeservers,&domain($cdom,'primary'));
 9926:     } else {
 9927:         my %servers = &get_servers($cdom,'library');
 9928:         foreach my $tryserver (keys(%servers)) {
 9929:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9930:                 push(@homeservers,$tryserver);
 9931:             }
 9932:         }
 9933:     }
 9934:     my $response;
 9935:     my %reformatted = %{$instsecref};
 9936:     foreach my $server (@homeservers) {
 9937:         if (ref($instsecref) eq 'HASH') {
 9938:             my $info = &freeze_escape($instsecref);
 9939:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
 9940:                                 $action.':'.$info,$server);
 9941:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
 9942:             my @items = split(/&/,$response);
 9943:             foreach my $item (@items) {
 9944:                 my ($key,$value) = split(/=/,$item);
 9945:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
 9946:             }
 9947:         }
 9948:     }
 9949:     return %reformatted;
 9950: }
 9951: 
 9952: sub auto_validate_instclasses {
 9953:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9954:     my ($homeserver,%validations);
 9955:     $homeserver = &homeserver($cnum,$cdom);
 9956:     unless ($homeserver eq 'no_host') {
 9957:         my $ownerlist;
 9958:         if (ref($owners) eq 'ARRAY') {
 9959:             $ownerlist = join(',',@{$owners});
 9960:         } else {
 9961:             $ownerlist = $owners;
 9962:         }
 9963:         if (ref($classesref) eq 'HASH') {
 9964:             my $classes = &freeze_escape($classesref);
 9965:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9966:                                 ':'.$cdom.':'.$classes,$homeserver);
 9967:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9968:                 my @items = split(/&/,$response);
 9969:                 foreach my $item (@items) {
 9970:                     my ($key,$value) = split('=',$item);
 9971:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9972:                 }
 9973:             }
 9974:         }
 9975:     }
 9976:     return %validations;
 9977: }
 9978: 
 9979: sub auto_crsreq_update {
 9980:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9981:         $code,$accessstart,$accessend,$inbound) = @_;
 9982:     my ($homeserver,%crsreqresponse);
 9983:     if ($cdom =~ /^$match_domain$/) {
 9984:         $homeserver = &domain($cdom,'primary');
 9985:     }
 9986:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9987:         my $info;
 9988:         if (ref($inbound) eq 'HASH') {
 9989:             $info = &freeze_escape($inbound);
 9990:         }
 9991:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9992:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9993:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9994:                             &escape($title).':'.&escape($code).':'.
 9995:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9996:                             $homeserver);
 9997:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9998:             my @items = split(/&/,$response);
 9999:             foreach my $item (@items) {
10000:                 my ($key,$value) = split('=',$item);
10001:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10002:             }
10003:         }
10004:     }
10005:     return \%crsreqresponse;
10006: }
10007: 
10008: sub auto_export_grades {
10009:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10010:     my ($homeserver,%exportresponse);
10011:     if ($cdom =~ /^$match_domain$/) {
10012:         $homeserver = &domain($cdom,'primary');
10013:     }
10014:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10015:         my $info;
10016:         if (ref($inforef) eq 'HASH') {
10017:             $info = &freeze_escape($inforef);
10018:         }
10019:         if (ref($gradesref) eq 'HASH') {
10020:             my $grades = &freeze_escape($gradesref);
10021:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10022:                                 $info.':'.$grades,$homeserver);
10023:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10024:                 my @items = split(/&/,$response);
10025:                 foreach my $item (@items) {
10026:                     my ($key,$value) = split('=',$item);
10027:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10028:                 }
10029:             }
10030:         }
10031:     }
10032:     return \%exportresponse;
10033: }
10034: 
10035: sub check_instcode_cloning {
10036:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10037:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10038:         return;
10039:     }
10040:     my $canclone;
10041:     if (@{$code_order} > 0) {
10042:         my $instcoderegexp ='^';
10043:         my @clonecodes = split(/\&/,$cloner);
10044:         foreach my $item (@{$code_order}) {
10045:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10046:                 foreach my $pair (@clonecodes) {
10047:                     my ($key,$val) = split(/\=/,$pair,2);
10048:                     $val = &unescape($val);
10049:                     if ($key eq $item) {
10050:                         $instcoderegexp .= '('.$val.')';
10051:                         last;
10052:                     }
10053:                 }
10054:             } else {
10055:                 $instcoderegexp .= $codedefaults->{$item};
10056:             }
10057:         }
10058:         $instcoderegexp .= '$';
10059:         my (@from,@to);
10060:         eval {
10061:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10062:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10063:         };
10064:         if ((@from > 0) && (@to > 0)) {
10065:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10066:             if (!@diffs) {
10067:                 $canclone = 1;
10068:             }
10069:         }
10070:     }
10071:     return $canclone;
10072: }
10073: 
10074: sub default_instcode_cloning {
10075:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10076:     my (%codedefaults,@code_order,$canclone);
10077:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10078:         %codedefaults = %{$codedefaultsref};
10079:         @code_order = @{$codeorderref};
10080:     } elsif ($clonedom) {
10081:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10082:     }
10083:     if (($domdefclone) && (@code_order)) {
10084:         my @clonecodes = split(/\+/,$domdefclone);
10085:         my $instcoderegexp ='^';
10086:         foreach my $item (@code_order) {
10087:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10088:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10089:             } else {
10090:                 $instcoderegexp .= $codedefaults{$item};
10091:             }
10092:         }
10093:         $instcoderegexp .= '$';
10094:         my (@from,@to);
10095:         eval {
10096:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10097:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10098:         };
10099:         if ((@from > 0) && (@to > 0)) {
10100:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10101:             if (!@diffs) {
10102:                 $canclone = 1;
10103:             }
10104:         }
10105:     }
10106:     return $canclone;
10107: }
10108: 
10109: # ------------------------------------------------------- Course Group routines
10110: 
10111: sub get_coursegroups {
10112:     my ($cdom,$cnum,$group,$namespace) = @_;
10113:     return(&dump($namespace,$cdom,$cnum,$group));
10114: }
10115: 
10116: sub modify_coursegroup {
10117:     my ($cdom,$cnum,$groupsettings) = @_;
10118:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10119: }
10120: 
10121: sub toggle_coursegroup_status {
10122:     my ($cdom,$cnum,$group,$action) = @_;
10123:     my ($from_namespace,$to_namespace);
10124:     if ($action eq 'delete') {
10125:         $from_namespace = 'coursegroups';
10126:         $to_namespace = 'deleted_groups';
10127:     } else {
10128:         $from_namespace = 'deleted_groups';
10129:         $to_namespace = 'coursegroups';
10130:     }
10131:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10132:     if (my $tmp = &error(%curr_group)) {
10133:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10134:         return ('read error',$tmp);
10135:     } else {
10136:         my %savedsettings = %curr_group; 
10137:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10138:         my $deloutcome;
10139:         if ($result eq 'ok') {
10140:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10141:         } else {
10142:             return ('write error',$result);
10143:         }
10144:         if ($deloutcome eq 'ok') {
10145:             return 'ok';
10146:         } else {
10147:             return ('delete error',$deloutcome);
10148:         }
10149:     }
10150: }
10151: 
10152: sub modify_group_roles {
10153:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10154:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10155:     my $role = 'gr/'.&escape($userprivs);
10156:     my ($uname,$udom) = split(/:/,$user);
10157:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10158:     if ($result eq 'ok') {
10159:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10160:     }
10161:     return $result;
10162: }
10163: 
10164: sub modify_coursegroup_membership {
10165:     my ($cdom,$cnum,$membership) = @_;
10166:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10167:     return $result;
10168: }
10169: 
10170: sub get_active_groups {
10171:     my ($udom,$uname,$cdom,$cnum) = @_;
10172:     my $now = time;
10173:     my %groups = ();
10174:     foreach my $key (keys(%env)) {
10175:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10176:             my ($start,$end) = split(/\./,$env{$key});
10177:             if (($end!=0) && ($end<$now)) { next; }
10178:             if (($start!=0) && ($start>$now)) { next; }
10179:             if ($1 eq $cdom && $2 eq $cnum) {
10180:                 $groups{$3} = $env{$key} ;
10181:             }
10182:         }
10183:     }
10184:     return %groups;
10185: }
10186: 
10187: sub get_group_membership {
10188:     my ($cdom,$cnum,$group) = @_;
10189:     return(&dump('groupmembership',$cdom,$cnum,$group));
10190: }
10191: 
10192: sub get_users_groups {
10193:     my ($udom,$uname,$courseid) = @_;
10194:     my @usersgroups;
10195:     my $cachetime=1800;
10196: 
10197:     my $hashid="$udom:$uname:$courseid";
10198:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10199:     if (defined($cached)) {
10200:         @usersgroups = split(/:/,$grouplist);
10201:     } else {  
10202:         $grouplist = '';
10203:         my $courseurl = &courseid_to_courseurl($courseid);
10204:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10205:         my $access_end = $env{'course.'.$courseid.
10206:                               '.default_enrollment_end_date'};
10207:         my $now = time;
10208:         foreach my $key (keys(%roleshash)) {
10209:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10210:                 my $group = $1;
10211:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10212:                     my $start = $2;
10213:                     my $end = $1;
10214:                     if ($start == -1) { next; } # deleted from group
10215:                     if (($start!=0) && ($start>$now)) { next; }
10216:                     if (($end!=0) && ($end<$now)) {
10217:                         if ($access_end && $access_end < $now) {
10218:                             if ($access_end - $end < 86400) {
10219:                                 push(@usersgroups,$group);
10220:                             }
10221:                         }
10222:                         next;
10223:                     }
10224:                     push(@usersgroups,$group);
10225:                 }
10226:             }
10227:         }
10228:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10229:         $grouplist = join(':',@usersgroups);
10230:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10231:     }
10232:     return @usersgroups;
10233: }
10234: 
10235: sub devalidate_getgroups_cache {
10236:     my ($udom,$uname,$cdom,$cnum)=@_;
10237:     my $courseid = $cdom.'_'.$cnum;
10238: 
10239:     my $hashid="$udom:$uname:$courseid";
10240:     &devalidate_cache_new('getgroups',$hashid);
10241: }
10242: 
10243: # ------------------------------------------------------------------ Plain Text
10244: 
10245: sub plaintext {
10246:     my ($short,$type,$cid,$forcedefault) = @_;
10247:     if ($short =~ m{^cr/}) {
10248: 	return (split('/',$short))[-1];
10249:     }
10250:     if (!defined($cid)) {
10251:         $cid = $env{'request.course.id'};
10252:     }
10253:     my %rolenames = (
10254:                       Course    => 'std',
10255:                       Community => 'alt1',
10256:                       Placement => 'std',
10257:                     );
10258:     if ($cid ne '') {
10259:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10260:             unless ($forcedefault) {
10261:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10262:                 &Apache::lonlocal::mt_escape(\$roletext);
10263:                 return &Apache::lonlocal::mt($roletext);
10264:             }
10265:         }
10266:     }
10267:     if ((defined($type)) && (defined($rolenames{$type})) &&
10268:         (defined($rolenames{$type})) && 
10269:         (defined($prp{$short}{$rolenames{$type}}))) {
10270:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10271:     } elsif ($cid ne '') {
10272:         my $crstype = $env{'course.'.$cid.'.type'};
10273:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10274:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10275:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10276:         }
10277:     }
10278:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10279: }
10280: 
10281: # ----------------------------------------------------------------- Assign Role
10282: 
10283: sub assignrole {
10284:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10285:         $context)=@_;
10286:     my $mrole;
10287:     if ($role =~ /^cr\//) {
10288:         my $cwosec=$url;
10289:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10290: 	unless (&allowed('ccr',$cwosec)) {
10291:            my $refused = 1;
10292:            if ($context eq 'requestcourses') {
10293:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10294:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10295:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10296:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10297:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10298:                            if ($crsenv{'internal.courseowner'} eq
10299:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10300:                                $refused = '';
10301:                            }
10302:                        }
10303:                    }
10304:                }
10305:            }
10306:            if ($refused) {
10307:                &logthis('Refused custom assignrole: '.
10308:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10309:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10310:                return 'refused';
10311:            }
10312:         }
10313:         $mrole='cr';
10314:     } elsif ($role =~ /^gr\//) {
10315:         my $cwogrp=$url;
10316:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10317:         unless (&allowed('mdg',$cwogrp)) {
10318:             &logthis('Refused group assignrole: '.
10319:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10320:                     $env{'user.name'}.' at '.$env{'user.domain'});
10321:             return 'refused';
10322:         }
10323:         $mrole='gr';
10324:     } else {
10325:         my $cwosec=$url;
10326:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10327:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10328:             my $refused;
10329:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10330:                 if (!(&allowed('c'.$role,$url))) {
10331:                     $refused = 1;
10332:                 }
10333:             } else {
10334:                 $refused = 1;
10335:             }
10336:             if ($refused) {
10337:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10338:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10339:                     my %crsenv;
10340:                     if ($role eq 'cc' || $role eq 'co') {
10341:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10342:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10343:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10344:                                 if ($crsenv{'internal.courseowner'} eq 
10345:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10346:                                     $refused = '';
10347:                                 }
10348:                             }
10349:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10350:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10351:                                 if ($crsenv{'internal.courseowner'} eq 
10352:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10353:                                     $refused = '';
10354:                                 }
10355:                             }
10356:                         }
10357:                     }
10358:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10359:                     if ($role eq 'st') {
10360:                         $refused = '';
10361:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10362:                         $refused = '';
10363:                     }
10364:                 } elsif ($context eq 'requestcourses') {
10365:                     my @possroles = ('st','ta','ep','in','cc','co');
10366:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10367:                         my $wrongcc;
10368:                         if ($cnum =~ /^$match_community$/) {
10369:                             $wrongcc = 1 if ($role eq 'cc');
10370:                         } else {
10371:                             $wrongcc = 1 if ($role eq 'co');
10372:                         }
10373:                         unless ($wrongcc) {
10374:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10375:                             if ($crsenv{'internal.courseowner'} eq 
10376:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10377:                                 $refused = '';
10378:                             }
10379:                         }
10380:                     }
10381:                 } elsif ($context eq 'requestauthor') {
10382:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10383:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10384:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10385:                             $refused = '';
10386:                         } else {
10387:                             my %domdefaults = &get_domain_defaults($udom);
10388:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10389:                                 my $checkbystatus;
10390:                                 if ($env{'user.adv'}) { 
10391:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10392:                                     if ($disposition eq 'automatic') {
10393:                                         $refused = '';
10394:                                     } elsif ($disposition eq '') {
10395:                                         $checkbystatus = 1;
10396:                                     } 
10397:                                 } else {
10398:                                     $checkbystatus = 1;
10399:                                 }
10400:                                 if ($checkbystatus) {
10401:                                     if ($env{'environment.inststatus'}) {
10402:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10403:                                         foreach my $type (@inststatuses) {
10404:                                             if (($type ne '') &&
10405:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10406:                                                 $refused = '';
10407:                                             }
10408:                                         }
10409:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10410:                                         $refused = '';
10411:                                     }
10412:                                 }
10413:                             }
10414:                         }
10415:                     }
10416:                 }
10417:                 if ($refused) {
10418:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10419:                              ' '.$role.' '.$end.' '.$start.' by '.
10420: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10421:                     return 'refused';
10422:                 }
10423:             }
10424:         } elsif ($role eq 'au') {
10425:             if ($url ne '/'.$udom.'/') {
10426:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10427:                          ' to assign author role for '.$uname.':'.$udom.
10428:                          ' in domain: '.$url.' refused (wrong domain).');
10429:                 return 'refused';
10430:             }
10431:         }
10432:         $mrole=$role;
10433:     }
10434:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10435:                 "$udom:$uname:$url".'_'."$mrole=$role";
10436:     if ($end) { $command.='_'.$end; }
10437:     if ($start) {
10438: 	if ($end) { 
10439:            $command.='_'.$start; 
10440:         } else {
10441:            $command.='_0_'.$start;
10442:         }
10443:     }
10444:     my $origstart = $start;
10445:     my $origend = $end;
10446:     my $delflag;
10447: # actually delete
10448:     if ($deleteflag) {
10449: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10450: # modify command to delete the role
10451:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10452:                 "$udom:$uname:$url".'_'."$mrole";
10453: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10454: # set start and finish to negative values for userrolelog
10455:            $start=-1;
10456:            $end=-1;
10457:            $delflag = 1;
10458:         }
10459:     }
10460: # send command
10461:     my $answer=&reply($command,&homeserver($uname,$udom));
10462: # log new user role if status is ok
10463:     if ($answer eq 'ok') {
10464: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10465:         if (($role eq 'cc') || ($role eq 'in') ||
10466:             ($role eq 'ep') || ($role eq 'ad') ||
10467:             ($role eq 'ta') || ($role eq 'st') ||
10468:             ($role=~/^cr/) || ($role eq 'gr') ||
10469:             ($role eq 'co')) {
10470: # for course roles, perform group memberships changes triggered by role change.
10471:             unless ($role =~ /^gr/) {
10472:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10473:                                                  $origstart,$selfenroll,$context);
10474:             }
10475:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10476:                            $selfenroll,$context);
10477:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10478:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10479:                  ($role eq 'da')) {
10480:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10481:                            $context);
10482:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10483:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10484:                              $context); 
10485:         }
10486:         if ($role eq 'cc') {
10487:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10488:         }
10489:     }
10490:     return $answer;
10491: }
10492: 
10493: sub autoupdate_coowners {
10494:     my ($url,$end,$start,$uname,$udom) = @_;
10495:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10496:     if (($cdom ne '') && ($cnum ne '')) {
10497:         my $now = time;
10498:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10499:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10500:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10501:             my $instcode = $coursehash{'internal.coursecode'};
10502:             my $xlists = $coursehash{'internal.crosslistings'};
10503:             if ($instcode ne '') {
10504:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10505:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10506:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10507:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10508:                         unless ($result eq 'valid') {
10509:                             if ($xlists ne '') {
10510:                                 foreach my $xlist (split(',',$xlists)) {
10511:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10512:                                     $result =
10513:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10514:                                                                       $inst_crosslist,$uname.':'.$udom);
10515:                                     last if ($result eq 'valid');
10516:                                 }
10517:                             }
10518:                         }
10519:                         if ($result eq 'valid') {
10520:                             if ($coursehash{'internal.co-owners'}) {
10521:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10522:                                     push(@newcoowners,$coowner);
10523:                                 }
10524:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10525:                                     push(@newcoowners,$uname.':'.$udom);
10526:                                 }
10527:                                 @newcoowners = sort(@newcoowners);
10528:                             } else {
10529:                                 push(@newcoowners,$uname.':'.$udom);
10530:                             }
10531:                         } elsif ($coursehash{'internal.co-owners'}) {
10532:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10533:                                 unless ($coowner eq $uname.':'.$udom) {
10534:                                     push(@newcoowners,$coowner);
10535:                                 }
10536:                             }
10537:                             unless (@newcoowners > 0) {
10538:                                 $delcoowners = 1;
10539:                                 $coowners = '';
10540:                             }
10541:                         }
10542:                         if (@newcoowners || $delcoowners) {
10543:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10544:                                             $delcoowners,@newcoowners);
10545:                         }
10546:                     }
10547:                 }
10548:             }
10549:         }
10550:     }
10551: }
10552: 
10553: sub store_coowners {
10554:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10555:     my $cid = $cdom.'_'.$cnum;
10556:     my ($coowners,$delresult,$putresult);
10557:     if (@newcoowners) {
10558:         $coowners = join(',',@newcoowners);
10559:         my %coownershash = (
10560:                             'internal.co-owners' => $coowners,
10561:                            );
10562:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10563:         if ($putresult eq 'ok') {
10564:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10565:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10566:             }
10567:         }
10568:     }
10569:     if ($delcoowners) {
10570:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10571:         if ($delresult eq 'ok') {
10572:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10573:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10574:             }
10575:         }
10576:     }
10577:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10578:         my %crsinfo =
10579:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10580:         if (ref($crsinfo{$cid}) eq 'HASH') {
10581:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10582:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10583:         }
10584:     }
10585: }
10586: 
10587: # -------------------------------------------------- Modify user authentication
10588: # Overrides without validation
10589: 
10590: sub modifyuserauth {
10591:     my ($udom,$uname,$umode,$upass)=@_;
10592:     my $uhome=&homeserver($uname,$udom);
10593:     my $allowed;
10594:     if (&allowed('mau',$udom)) {
10595:         $allowed = 1;
10596:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10597:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10598:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10599:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10600:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10601:         if (($cdom ne '') && ($cnum ne '')) {
10602:             my $is_owner = &is_course_owner($cdom,$cnum);
10603:             if ($is_owner) {
10604:                 $allowed = 1;
10605:             }
10606:         }
10607:     }
10608:     unless ($allowed) { return 'refused'; }
10609:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10610:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10611:              ' in domain '.$env{'request.role.domain'});  
10612:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10613: 		     &escape($upass),$uhome);
10614:     my $ip = &get_requestor_ip();
10615:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10616:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10617:          '(Remote '.$ip.'): '.$reply);
10618:     &log($udom,,$uname,$uhome,
10619:         'Authentication changed by '.$env{'user.domain'}.', '.
10620:                                      $env{'user.name'}.', '.$umode.
10621:          '(Remote '.$ip.'): '.$reply);
10622:     unless ($reply eq 'ok') {
10623:         &logthis('Authentication mode error: '.$reply);
10624: 	return 'error: '.$reply;
10625:     }   
10626:     return 'ok';
10627: }
10628: 
10629: # --------------------------------------------------------------- Modify a user
10630: 
10631: sub modifyuser {
10632:     my ($udom,    $uname, $uid,
10633:         $umode,   $upass, $first,
10634:         $middle,  $last,  $gene,
10635:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10636:     $udom= &LONCAPA::clean_domain($udom);
10637:     $uname=&LONCAPA::clean_username($uname);
10638:     my $showcandelete = 'none';
10639:     if (ref($candelete) eq 'ARRAY') {
10640:         if (@{$candelete} > 0) {
10641:             $showcandelete = join(', ',@{$candelete});
10642:         }
10643:     }
10644:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10645:              $umode.', '.$first.', '.$middle.', '.
10646: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10647:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10648:                                      ' desiredhome not specified'). 
10649:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10650:              ' in domain '.$env{'request.role.domain'});
10651:     my $uhome=&homeserver($uname,$udom,'true');
10652:     my $newuser;
10653:     if ($uhome eq 'no_host') {
10654:         $newuser = 1;
10655:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10656:                 ($umode eq 'lti')) {
10657:             return 'error: more information needed to create new user';
10658:         }
10659:     }
10660: # ----------------------------------------------------------------- Create User
10661:     if (($uhome eq 'no_host') && 
10662: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10663:         my $unhome='';
10664:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10665:             $unhome = $desiredhome;
10666: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10667: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10668:         } else { # load balancing routine for determining $unhome
10669:             my $loadm=10000000;
10670: 	    my %servers = &get_servers($udom,'library');
10671: 	    foreach my $tryserver (keys(%servers)) {
10672: 		my $answer=reply('load',$tryserver);
10673: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10674: 		    $loadm=$answer;
10675: 		    $unhome=$tryserver;
10676: 		}
10677: 	    }
10678:         }
10679:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10680: 	    return 'error: unable to find a home server for '.$uname.
10681:                    ' in domain '.$udom;
10682:         }
10683:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10684:                          &escape($upass),$unhome);
10685: 	unless ($reply eq 'ok') {
10686:             return 'error: '.$reply;
10687:         }   
10688:         $uhome=&homeserver($uname,$udom,'true');
10689:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10690: 	    return 'error: unable verify users home machine.';
10691:         }
10692:     }   # End of creation of new user
10693: # ---------------------------------------------------------------------- Add ID
10694:     if ($uid) {
10695:        $uid=~tr/A-Z/a-z/;
10696:        my %uidhash=&idrget($udom,$uname);
10697:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10698:          && (!$forceid)) {
10699: 	  unless ($uid eq $uidhash{$uname}) {
10700: 	      return 'error: user id "'.$uid.'" does not match '.
10701:                   'current user id "'.$uidhash{$uname}.'".';
10702:           }
10703:        } else {
10704: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10705:        }
10706:     }
10707: # -------------------------------------------------------------- Add names, etc
10708:     my @tmp=&get('environment',
10709: 		   ['firstname','middlename','lastname','generation','id',
10710:                     'permanentemail','inststatus'],
10711: 		   $udom,$uname);
10712:     my (%names,%oldnames);
10713:     if ($tmp[0] =~ m/^error:.*/) { 
10714:         %names=(); 
10715:     } else {
10716:         %names = @tmp;
10717:         %oldnames = %names;
10718:     }
10719: #
10720: # If name, email and/or uid are blank (e.g., because an uploaded file
10721: # of users did not contain them), do not overwrite existing values
10722: # unless field is in $candelete array ref.  
10723: #
10724: 
10725:     my @fields = ('firstname','middlename','lastname','generation',
10726:                   'permanentemail','id');
10727:     my %newvalues;
10728:     if (ref($candelete) eq 'ARRAY') {
10729:         foreach my $field (@fields) {
10730:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10731:                 if ($field eq 'firstname') {
10732:                     $names{$field} = $first;
10733:                 } elsif ($field eq 'middlename') {
10734:                     $names{$field} = $middle;
10735:                 } elsif ($field eq 'lastname') {
10736:                     $names{$field} = $last;
10737:                 } elsif ($field eq 'generation') { 
10738:                     $names{$field} = $gene;
10739:                 } elsif ($field eq 'permanentemail') {
10740:                     $names{$field} = $email;
10741:                 } elsif ($field eq 'id') {
10742:                     $names{$field}  = $uid;
10743:                 }
10744:             }
10745:         }
10746:     }
10747:     if ($first)  { $names{'firstname'}  = $first; }
10748:     if (defined($middle)) { $names{'middlename'} = $middle; }
10749:     if ($last)   { $names{'lastname'}   = $last; }
10750:     if (defined($gene))   { $names{'generation'} = $gene; }
10751:     if ($email) {
10752:        $email=~s/[^\w\@\.\-\,]//gs;
10753:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10754:     }
10755:     if ($uid) { $names{'id'}  = $uid; }
10756:     if (defined($inststatus)) {
10757:         $names{'inststatus'} = '';
10758:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10759:         if (ref($usertypes) eq 'HASH') {
10760:             my @okstatuses; 
10761:             foreach my $item (split(/:/,$inststatus)) {
10762:                 if (defined($usertypes->{$item})) {
10763:                     push(@okstatuses,$item);  
10764:                 }
10765:             }
10766:             if (@okstatuses) {
10767:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10768:             }
10769:         }
10770:     }
10771:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10772:                  $umode.', '.$first.', '.$middle.', '.
10773:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10774:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10775:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10776:     } else {
10777:         $logmsg .= ' during self creation';
10778:     }
10779:     my $changed;
10780:     if ($newuser) {
10781:         $changed = 1;
10782:     } else {
10783:         foreach my $field (@fields) {
10784:             if ($names{$field} ne $oldnames{$field}) {
10785:                 $changed = 1;
10786:                 last;
10787:             }
10788:         }
10789:     }
10790:     unless ($changed) {
10791:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10792:         &logthis($logmsg);
10793:         return 'ok';
10794:     }
10795:     my $reply = &put('environment', \%names, $udom,$uname);
10796:     if ($reply ne 'ok') { 
10797:         return 'error: '.$reply;
10798:     }
10799:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10800:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10801:     }
10802:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10803:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10804:     $logmsg = 'Success modifying user '.$logmsg;
10805:     &logthis($logmsg);
10806:     return 'ok';
10807: }
10808: 
10809: # -------------------------------------------------------------- Modify student
10810: 
10811: sub modifystudent {
10812:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10813:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10814:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10815:     if (!$cid) {
10816: 	unless ($cid=$env{'request.course.id'}) {
10817: 	    return 'not_in_class';
10818: 	}
10819:     }
10820: # --------------------------------------------------------------- Make the user
10821:     my $reply=&modifyuser
10822: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10823:          $desiredhome,$email,$inststatus);
10824:     unless ($reply eq 'ok') { return $reply; }
10825:     # This will cause &modify_student_enrollment to get the uid from the
10826:     # student's environment
10827:     $uid = undef if (!$forceid);
10828:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10829:                                         $gene,$usec,$end,$start,$type,$locktype,
10830:                                         $cid,$selfenroll,$context,$credits,$instsec);
10831:     return $reply;
10832: }
10833: 
10834: sub modify_student_enrollment {
10835:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10836:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10837:     my ($cdom,$cnum,$chome);
10838:     if (!$cid) {
10839: 	unless ($cid=$env{'request.course.id'}) {
10840: 	    return 'not_in_class';
10841: 	}
10842: 	$cdom=$env{'course.'.$cid.'.domain'};
10843: 	$cnum=$env{'course.'.$cid.'.num'};
10844:     } else {
10845: 	($cdom,$cnum)=split(/_/,$cid);
10846:     }
10847:     $chome=$env{'course.'.$cid.'.home'};
10848:     if (!$chome) {
10849: 	$chome=&homeserver($cnum,$cdom);
10850:     }
10851:     if (!$chome) { return 'unknown_course'; }
10852:     # Make sure the user exists
10853:     my $uhome=&homeserver($uname,$udom);
10854:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10855: 	return 'error: no such user';
10856:     }
10857:     # Get student data if we were not given enough information
10858:     if (!defined($first)  || $first  eq '' || 
10859:         !defined($last)   || $last   eq '' || 
10860:         !defined($uid)    || $uid    eq '' || 
10861:         !defined($middle) || $middle eq '' || 
10862:         !defined($gene)   || $gene   eq '') {
10863:         # They did not supply us with enough data to enroll the student, so
10864:         # we need to pick up more information.
10865:         my %tmp = &get('environment',
10866:                        ['firstname','middlename','lastname', 'generation','id']
10867:                        ,$udom,$uname);
10868: 
10869:         #foreach my $key (keys(%tmp)) {
10870:         #    &logthis("key $key = ".$tmp{$key});
10871:         #}
10872:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10873:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10874:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10875:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10876:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10877:     }
10878:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10879:     my $user = "$uname:$udom";
10880:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10881:     my $reply=cput('classlist',
10882: 		   {$user => 
10883: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10884: 		   $cdom,$cnum);
10885:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10886:         &devalidate_getsection_cache($udom,$uname,$cid);
10887:     } else { 
10888: 	return 'error: '.$reply;
10889:     }
10890:     # Add student role to user
10891:     my $uurl='/'.$cid;
10892:     $uurl=~s/\_/\//g;
10893:     if ($usec) {
10894: 	$uurl.='/'.$usec;
10895:     }
10896:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10897:                              $selfenroll,$context);
10898:     if ($result ne 'ok') {
10899:         if ($old_entry{$user} ne '') {
10900:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10901:         } else {
10902:             $reply = &del('classlist',[$user],$cdom,$cnum);
10903:         }
10904:     }
10905:     return $result; 
10906: }
10907: 
10908: sub format_name {
10909:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10910:     my $name;
10911:     if ($first ne 'lastname') {
10912: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10913:     } else {
10914: 	if ($lastname=~/\S/) {
10915: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10916: 	    $name=~s/\s+,/,/;
10917: 	} else {
10918: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10919: 	}
10920:     }
10921:     $name=~s/^\s+//;
10922:     $name=~s/\s+$//;
10923:     $name=~s/\s+/ /g;
10924:     return $name;
10925: }
10926: 
10927: # ------------------------------------------------- Write to course preferences
10928: 
10929: sub writecoursepref {
10930:     my ($courseid,%prefs)=@_;
10931:     $courseid=~s/^\///;
10932:     $courseid=~s/\_/\//g;
10933:     my ($cdomain,$cnum)=split(/\//,$courseid);
10934:     my $chome=homeserver($cnum,$cdomain);
10935:     if (($chome eq '') || ($chome eq 'no_host')) { 
10936: 	return 'error: no such course';
10937:     }
10938:     my $cstring='';
10939:     foreach my $pref (keys(%prefs)) {
10940: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10941:     }
10942:     $cstring=~s/\&$//;
10943:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10944: }
10945: 
10946: # ---------------------------------------------------------- Make/modify course
10947: 
10948: sub createcourse {
10949:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10950:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10951:     $url=&declutter($url);
10952:     my $cid='';
10953:     if ($context eq 'requestcourses') {
10954:         my $can_create = 0;
10955:         my ($ownername,$ownerdom) = split(':',$course_owner);
10956:         if ($udom eq $ownerdom) {
10957:             my $reload;
10958:             if (($callercontext eq 'auto') &&
10959:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10960:                 $reload = 'reload';
10961:             }
10962:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10963:                                   $context)) {
10964:                 $can_create = 1;
10965:             }
10966:         } else {
10967:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10968:                                            $category);
10969:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10970:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10971:                 if (@curr > 0) {
10972:                     my @options = qw(approval validate autolimit);
10973:                     my $optregex = join('|',@options);
10974:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10975:                         $can_create = 1;
10976:                     }
10977:                 }
10978:             }
10979:         }
10980:         if ($can_create) {
10981:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10982:                 unless (&allowed('ccc',$udom)) {
10983:                     return 'refused'; 
10984:                 }
10985:             }
10986:         } else {
10987:             return 'refused';
10988:         }
10989:     } elsif (!&allowed('ccc',$udom)) {
10990:         return 'refused';
10991:     }
10992: # --------------------------------------------------------------- Get Unique ID
10993:     my $uname;
10994:     if ($cnum =~ /^$match_courseid$/) {
10995:         my $chome=&homeserver($cnum,$udom,'true');
10996:         if (($chome eq '') || ($chome eq 'no_host')) {
10997:             $uname = $cnum;
10998:         } else {
10999:             $uname = &generate_coursenum($udom,$crstype);
11000:         }
11001:     } else {
11002:         $uname = &generate_coursenum($udom,$crstype);
11003:     }
11004:     return $uname if ($uname =~ /^error/);
11005: # -------------------------------------------------- Check supplied server name
11006:     if (!defined($course_server)) {
11007:         if (defined(&domain($udom,'primary'))) {
11008:             $course_server = &domain($udom,'primary');
11009:         } else {
11010:             $course_server = $env{'user.home'}; 
11011:         }
11012:     }
11013:     my %host_servers =
11014:         &Apache::lonnet::get_servers($udom,'library');
11015:     unless ($host_servers{$course_server}) {
11016:         return 'error: invalid home server for course: '.$course_server;
11017:     }
11018: # ------------------------------------------------------------- Make the course
11019:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11020:                       $course_server);
11021:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11022:     my $uhome=&homeserver($uname,$udom,'true');
11023:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11024: 	return 'error: no such course';
11025:     }
11026: # ----------------------------------------------------------------- Course made
11027: # log existence
11028:     my $now = time;
11029:     my $newcourse = {
11030:                     $udom.'_'.$uname => {
11031:                                      description => $description,
11032:                                      inst_code   => $inst_code,
11033:                                      owner       => $course_owner,
11034:                                      type        => $crstype,
11035:                                      creator     => $env{'user.name'}.':'.
11036:                                                     $env{'user.domain'},
11037:                                      created     => $now,
11038:                                      context     => $context,
11039:                                                 },
11040:                     };
11041:     &courseidput($udom,$newcourse,$uhome,'notime');
11042: # set toplevel url
11043:     my $topurl=$url;
11044:     unless ($nonstandard) {
11045: # ------------------------------------------ For standard courses, make top url
11046:         my $mapurl=&clutter($url);
11047:         if ($mapurl eq '/res/') { $mapurl=''; }
11048:         $env{'form.initmap'}=(<<ENDINITMAP);
11049: <map>
11050: <resource id="1" type="start"></resource>
11051: <resource id="2" src="$mapurl"></resource>
11052: <resource id="3" type="finish"></resource>
11053: <link index="1" from="1" to="2"></link>
11054: <link index="2" from="2" to="3"></link>
11055: </map>
11056: ENDINITMAP
11057:         $topurl=&declutter(
11058:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11059:                           );
11060:     }
11061: # ----------------------------------------------------------- Write preferences
11062:     &writecoursepref($udom.'_'.$uname,
11063:                      ('description'              => $description,
11064:                       'url'                      => $topurl,
11065:                       'internal.creator'         => $env{'user.name'}.':'.
11066:                                                     $env{'user.domain'},
11067:                       'internal.created'         => $now,
11068:                       'internal.creationcontext' => $context)
11069:                     );
11070:     return '/'.$udom.'/'.$uname;
11071: }
11072: 
11073: # ------------------------------------------------------------------- Create ID
11074: sub generate_coursenum {
11075:     my ($udom,$crstype) = @_;
11076:     my $domdesc = &domain($udom);
11077:     return 'error: invalid domain' if ($domdesc eq '');
11078:     my $first;
11079:     if ($crstype eq 'Community') {
11080:         $first = '0';
11081:     } else {
11082:         $first = int(1+rand(9)); 
11083:     } 
11084:     my $uname=$first.
11085:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11086:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11087:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11088: # ----------------------------------------------- Make sure that does not exist
11089:     my $uhome=&homeserver($uname,$udom,'true');
11090:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11091:         if ($crstype eq 'Community') {
11092:             $first = '0';
11093:         } else {
11094:             $first = int(1+rand(9));
11095:         }
11096:         $uname=$first.
11097:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11098:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11099:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11100:         $uhome=&homeserver($uname,$udom,'true');
11101:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11102:             return 'error: unable to generate unique course-ID';
11103:         }
11104:     }
11105:     return $uname;
11106: }
11107: 
11108: sub is_course {
11109:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11110:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11111: 
11112:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11113:     my $uhome=&homeserver($cnum,$cdom);
11114:     my $iscourse;
11115:     if (grep { $_ eq $uhome } current_machine_ids()) {
11116:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11117:     } else {
11118:         my $hashid = $cdom.':'.$cnum;
11119:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11120:         unless (defined($cached)) {
11121:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11122:                                         $cnum,undef,undef,'.');
11123:             $iscourse = 0;
11124:             if (exists($courses{$cdom.'_'.$cnum})) {
11125:                 $iscourse = 1;
11126:             }
11127:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11128:         }
11129:     }
11130:     return unless ($iscourse);
11131:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11132: }
11133: 
11134: sub store_userdata {
11135:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11136:     my $result;
11137:     if ($datakey ne '') {
11138:         if (ref($storehash) eq 'HASH') {
11139:             if ($udom eq '' || $uname eq '') {
11140:                 $udom = $env{'user.domain'};
11141:                 $uname = $env{'user.name'};
11142:             }
11143:             my $uhome=&homeserver($uname,$udom);
11144:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11145:                 $result = 'error: no_host';
11146:             } else {
11147:                 $storehash->{'ip'} = &get_requestor_ip();
11148:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11149: 
11150:                 my $namevalue='';
11151:                 foreach my $key (keys(%{$storehash})) {
11152:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11153:                 }
11154:                 $namevalue=~s/\&$//;
11155:                 unless ($namespace eq 'courserequests') {
11156:                     $datakey = &escape($datakey);
11157:                 }
11158:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11159:                                   $namevalue,$uhome);
11160:             }
11161:         } else {
11162:             $result = 'error: data to store was not a hash reference'; 
11163:         }
11164:     } else {
11165:         $result= 'error: invalid requestkey'; 
11166:     }
11167:     return $result;
11168: }
11169: 
11170: # ---------------------------------------------------------- Assign Custom Role
11171: 
11172: sub assigncustomrole {
11173:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11174:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11175:                        $end,$start,$deleteflag,$selfenroll,$context);
11176: }
11177: 
11178: # ----------------------------------------------------------------- Revoke Role
11179: 
11180: sub revokerole {
11181:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11182:     my $now=time;
11183:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11184: }
11185: 
11186: # ---------------------------------------------------------- Revoke Custom Role
11187: 
11188: sub revokecustomrole {
11189:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11190:     my $now=time;
11191:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11192:            $deleteflag,$selfenroll,$context);
11193: }
11194: 
11195: # ------------------------------------------------------------ Disk usage
11196: sub diskusage {
11197:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11198:     $directorypath =~ s/\/$//;
11199:     my $listing=&reply('du2:'.&escape($directorypath).':'
11200:                        .&escape($getpropath).':'.&escape($uname).':'
11201:                        .&escape($udom),homeserver($uname,$udom));
11202:     if ($listing eq 'unknown_cmd') {
11203:         if ($getpropath) {
11204:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11205:         }
11206:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11207:     }
11208:     return $listing;
11209: }
11210: 
11211: sub is_locked {
11212:     my ($file_name, $domain, $user, $which) = @_;
11213:     my @check;
11214:     my $is_locked;
11215:     push (@check,$file_name);
11216:     my %locked = &get('file_permissions',\@check,
11217: 		      $env{'user.domain'},$env{'user.name'});
11218:     my ($tmp)=keys(%locked);
11219:     if ($tmp=~/^error:/) { undef(%locked); }
11220:     
11221:     if (ref($locked{$file_name}) eq 'ARRAY') {
11222:         $is_locked = 'false';
11223:         foreach my $entry (@{$locked{$file_name}}) {
11224:            if (ref($entry) eq 'ARRAY') {
11225:                $is_locked = 'true';
11226:                if (ref($which) eq 'ARRAY') {
11227:                    push(@{$which},$entry);
11228:                } else {
11229:                    last;
11230:                }
11231:            }
11232:        }
11233:     } else {
11234:         $is_locked = 'false';
11235:     }
11236:     return $is_locked;
11237: }
11238: 
11239: sub declutter_portfile {
11240:     my ($file) = @_;
11241:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11242:     return $file;
11243: }
11244: 
11245: # ------------------------------------------------------------- Mark as Read Only
11246: 
11247: sub mark_as_readonly {
11248:     my ($domain,$user,$files,$what) = @_;
11249:     my %current_permissions = &dump('file_permissions',$domain,$user);
11250:     my ($tmp)=keys(%current_permissions);
11251:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11252:     foreach my $file (@{$files}) {
11253: 	$file = &declutter_portfile($file);
11254:         push(@{$current_permissions{$file}},$what);
11255:     }
11256:     &put('file_permissions',\%current_permissions,$domain,$user);
11257:     return;
11258: }
11259: 
11260: # ------------------------------------------------------------Save Selected Files
11261: 
11262: sub save_selected_files {
11263:     my ($user, $path, @files) = @_;
11264:     my $filename = $user."savedfiles";
11265:     my @other_files = &files_not_in_path($user, $path);
11266:     open (OUT,'>',LONCAPA::tempdir().$filename);
11267:     foreach my $file (@files) {
11268:         print (OUT $env{'form.currentpath'}.$file."\n");
11269:     }
11270:     foreach my $file (@other_files) {
11271:         print (OUT $file."\n");
11272:     }
11273:     close (OUT);
11274:     return 'ok';
11275: }
11276: 
11277: sub clear_selected_files {
11278:     my ($user) = @_;
11279:     my $filename = $user."savedfiles";
11280:     open (OUT,'>',LONCAPA::tempdir().$filename);
11281:     print (OUT undef);
11282:     close (OUT);
11283:     return ("ok");    
11284: }
11285: 
11286: sub files_in_path {
11287:     my ($user, $path) = @_;
11288:     my $filename = $user."savedfiles";
11289:     my %return_files;
11290:     open (IN,'<',LONCAPA::tempdir().$filename);
11291:     while (my $line_in = <IN>) {
11292:         chomp ($line_in);
11293:         my @paths_and_file = split (m!/!, $line_in);
11294:         my $file_part = pop (@paths_and_file);
11295:         my $path_part = join ('/', @paths_and_file);
11296:         $path_part.='/';
11297:         my $path_and_file = $path_part.$file_part;
11298:         if ($path_part eq $path) {
11299:             $return_files{$file_part}= 'selected';
11300:         }
11301:     }
11302:     close (IN);
11303:     return (\%return_files);
11304: }
11305: 
11306: # called in portfolio select mode, to show files selected NOT in current directory
11307: sub files_not_in_path {
11308:     my ($user, $path) = @_;
11309:     my $filename = $user."savedfiles";
11310:     my @return_files;
11311:     my $path_part;
11312:     open(IN, '<',LONCAPA::tempdir().$filename);
11313:     while (my $line = <IN>) {
11314:         #ok, I know it's clunky, but I want it to work
11315:         my @paths_and_file = split(m|/|, $line);
11316:         my $file_part = pop(@paths_and_file);
11317:         chomp($file_part);
11318:         my $path_part = join('/', @paths_and_file);
11319:         $path_part .= '/';
11320:         my $path_and_file = $path_part.$file_part;
11321:         if ($path_part ne $path) {
11322:             push(@return_files, ($path_and_file));
11323:         }
11324:     }
11325:     close(OUT);
11326:     return (@return_files);
11327: }
11328: 
11329: #------------------------------Submitted/Handedback Portfolio Files Versioning
11330:  
11331: sub portfiles_versioning {
11332:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11333:     my $portfolio_root = '/userfiles/portfolio';
11334:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11335:     foreach my $file (@{$portfiles}) {
11336:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11337:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11338:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11339:         my $getpropath = 1;
11340:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11341:                                              $stu_name,$getpropath);
11342:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11343:         my $new_answer = 
11344:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11345:         if ($new_answer ne 'problem getting file') {
11346:             push(@{$versioned_portfiles}, $directory.$new_answer);
11347:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11348:                               [$symb,$env{'request.course.id'},'graded']);
11349:         }
11350:     }
11351: }
11352: 
11353: sub get_next_version {
11354:     my ($answer_name, $answer_ext, $dir_list) = @_;
11355:     my $version;
11356:     if (ref($dir_list) eq 'ARRAY') {
11357:         foreach my $row (@{$dir_list}) {
11358:             my ($file) = split(/\&/,$row,2);
11359:             my ($file_name,$file_version,$file_ext) =
11360:                 &file_name_version_ext($file);
11361:             if (($file_name eq $answer_name) &&
11362:                 ($file_ext eq $answer_ext)) {
11363:                      # gets here if filename and extension match,
11364:                      # regardless of version
11365:                 if ($file_version ne '') {
11366:                     # a versioned file is found  so save it for later
11367:                     if ($file_version > $version) {
11368:                         $version = $file_version;
11369:                     }
11370:                 }
11371:             }
11372:         }
11373:     }
11374:     $version ++;
11375:     return($version);
11376: }
11377: 
11378: sub version_selected_portfile {
11379:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11380:     my ($answer_name,$answer_ver,$answer_ext) =
11381:         &file_name_version_ext($file_name);
11382:     my $new_answer;
11383:     $env{'form.copy'} =
11384:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11385:     if($env{'form.copy'} eq '-1') {
11386:         $new_answer = 'problem getting file';
11387:     } else {
11388:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11389:         my $copy_result = 
11390:             &finishuserfileupload($stu_name,$domain,'copy',
11391:                                   '/portfolio'.$directory.$new_answer);
11392:     }
11393:     undef($env{'form.copy'});
11394:     return ($new_answer);
11395: }
11396: 
11397: sub file_name_version_ext {
11398:     my ($file)=@_;
11399:     my @file_parts = split(/\./, $file);
11400:     my ($name,$version,$ext);
11401:     if (@file_parts > 1) {
11402:         $ext=pop(@file_parts);
11403:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11404:             $version=pop(@file_parts);
11405:         }
11406:         $name=join('.',@file_parts);
11407:     } else {
11408:         $name=join('.',@file_parts);
11409:     }
11410:     return($name,$version,$ext);
11411: }
11412: 
11413: #----------------------------------------------Get portfolio file permissions
11414: 
11415: sub get_portfile_permissions {
11416:     my ($domain,$user) = @_;
11417:     my %current_permissions = &dump('file_permissions',$domain,$user);
11418:     my ($tmp)=keys(%current_permissions);
11419:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11420:     return \%current_permissions;
11421: }
11422: 
11423: #---------------------------------------------Get portfolio file access controls
11424: 
11425: sub get_access_controls {
11426:     my ($current_permissions,$group,$file) = @_;
11427:     my %access;
11428:     my $real_file = $file;
11429:     $file =~ s/\.meta$//;
11430:     if (defined($file)) {
11431:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11432:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11433:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11434:             }
11435:         }
11436:     } else {
11437:         foreach my $key (keys(%{$current_permissions})) {
11438:             if ($key =~ /\0accesscontrol$/) {
11439:                 if (defined($group)) {
11440:                     if ($key !~ m-^\Q$group\E/-) {
11441:                         next;
11442:                     }
11443:                 }
11444:                 my ($fullpath) = split(/\0/,$key);
11445:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11446:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11447:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11448:                     }
11449:                 }
11450:             }
11451:         }
11452:     }
11453:     return %access;
11454: }
11455: 
11456: sub modify_access_controls {
11457:     my ($file_name,$changes,$domain,$user)=@_;
11458:     my ($outcome,$deloutcome);
11459:     my %store_permissions;
11460:     my %new_values;
11461:     my %new_control;
11462:     my %translation;
11463:     my @deletions = ();
11464:     my $now = time;
11465:     if (exists($$changes{'activate'})) {
11466:         if (ref($$changes{'activate'}) eq 'HASH') {
11467:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11468:             my $numnew = scalar(@newitems);
11469:             for (my $i=0; $i<$numnew; $i++) {
11470:                 my $newkey = $newitems[$i];
11471:                 my $newid = &Apache::loncommon::get_cgi_id();
11472:                 if ($newkey =~ /^\d+:/) { 
11473:                     $newkey =~ s/^(\d+)/$newid/;
11474:                     $translation{$1} = $newid;
11475:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11476:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11477:                     $translation{$1} = $newid;
11478:                 }
11479:                 $new_values{$file_name."\0".$newkey} = 
11480:                                           $$changes{'activate'}{$newitems[$i]};
11481:                 $new_control{$newkey} = $now;
11482:             }
11483:         }
11484:     }
11485:     my %todelete;
11486:     my %changed_items;
11487:     foreach my $action ('delete','update') {
11488:         if (exists($$changes{$action})) {
11489:             if (ref($$changes{$action}) eq 'HASH') {
11490:                 foreach my $key (keys(%{$$changes{$action}})) {
11491:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11492:                     if ($action eq 'delete') { 
11493:                         $todelete{$itemnum} = 1;
11494:                     } else {
11495:                         $changed_items{$itemnum} = $key;
11496:                     }
11497:                 }
11498:             }
11499:         }
11500:     }
11501:     # get lock on access controls for file.
11502:     my $lockhash = {
11503:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11504:                                                        ':'.$env{'user.domain'},
11505:                    }; 
11506:     my $tries = 0;
11507:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11508:    
11509:     while (($gotlock ne 'ok') && $tries < 10) {
11510:         $tries ++;
11511:         sleep(0.1);
11512:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11513:     }
11514:     if ($gotlock eq 'ok') {
11515:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11516:         my ($tmp)=keys(%curr_permissions);
11517:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11518:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11519:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11520:             if (ref($curr_controls) eq 'HASH') {
11521:                 foreach my $control_item (keys(%{$curr_controls})) {
11522:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11523:                     if (defined($todelete{$itemnum})) {
11524:                         push(@deletions,$file_name."\0".$control_item);
11525:                     } else {
11526:                         if (defined($changed_items{$itemnum})) {
11527:                             $new_control{$changed_items{$itemnum}} = $now;
11528:                             push(@deletions,$file_name."\0".$control_item);
11529:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11530:                         } else {
11531:                             $new_control{$control_item} = $$curr_controls{$control_item};
11532:                         }
11533:                     }
11534:                 }
11535:             }
11536:         }
11537:         my ($group);
11538:         if (&is_course($domain,$user)) {
11539:             ($group,my $file) = split(/\//,$file_name,2);
11540:         }
11541:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11542:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11543:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11544:         #  remove lock
11545:         my @del_lock = ($file_name."\0".'locked_access_records');
11546:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11547:         my $sqlresult =
11548:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11549:                                     $group);
11550:     } else {
11551:         $outcome = "error: could not obtain lockfile\n";  
11552:     }
11553:     return ($outcome,$deloutcome,\%new_values,\%translation);
11554: }
11555: 
11556: sub make_public_indefinitely {
11557:     my (@requrl) = @_;
11558:     return &automated_portfile_access('public',\@requrl);
11559: }
11560: 
11561: sub automated_portfile_access {
11562:     my ($accesstype,$addsref,$delsref,$info) = @_;
11563:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11564:         return 'invalid';
11565:     }
11566:     my %urls;
11567:     if (ref($addsref) eq 'ARRAY') {
11568:         foreach my $requrl (@{$addsref}) {
11569:             if (&is_portfolio_url($requrl)) {
11570:                 unless (exists($urls{$requrl})) {
11571:                     $urls{$requrl} = 'add';
11572:                 }
11573:             }
11574:         }
11575:     }
11576:     if (ref($delsref) eq 'ARRAY') {
11577:         foreach my $requrl (@{$delsref}) { 
11578:             if (&is_portfolio_url($requrl)) {
11579:                 unless (exists($urls{$requrl})) {
11580:                     $urls{$requrl} = 'delete'; 
11581:                 }
11582:             }
11583:         }
11584:     }
11585:     unless (keys(%urls)) {
11586:         return 'invalid';
11587:     }
11588:     my $ip;
11589:     if ($accesstype eq 'ip') {
11590:         if (ref($info) eq 'HASH') {
11591:             if ($info->{'ip'} ne '') {
11592:                 $ip = $info->{'ip'};
11593:             }
11594:         }
11595:         if ($ip eq '') {
11596:             return 'invalid';
11597:         }
11598:     }
11599:     my $errors;
11600:     my $now = time;
11601:     my %current_perms;
11602:     foreach my $requrl (sort(keys(%urls))) {
11603:         my $action;
11604:         if ($urls{$requrl} eq 'add') {
11605:             $action = 'activate';
11606:         } else {
11607:             $action = 'none';
11608:         }
11609:         my $aclnum = 0;
11610:         my (undef,$udom,$unum,$file_name,$group) =
11611:             &parse_portfolio_url($requrl);
11612:         unless (exists($current_perms{$unum.':'.$udom})) {
11613:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11614:         }
11615:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11616:                                                    $group,$file_name);
11617:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11618:             my ($num,$scope,$end,$start) = 
11619:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11620:             if ($scope eq $accesstype) {
11621:                 if (($start <= $now) && ($end == 0)) {
11622:                     if ($accesstype eq 'ip') {
11623:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11624:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11625:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11626:                                     if ($urls{$requrl} eq 'add') {
11627:                                         $action = 'none';
11628:                                         last;
11629:                                     } else {
11630:                                         $action = 'delete';
11631:                                         $aclnum = $num;
11632:                                         last;
11633:                                     }
11634:                                 }
11635:                             }
11636:                         }
11637:                     } elsif ($accesstype eq 'public') {
11638:                         if ($urls{$requrl} eq 'add') {
11639:                             $action = 'none';
11640:                             last;
11641:                         } else {
11642:                             $action = 'delete';
11643:                             $aclnum = $num;
11644:                             last;
11645:                         }
11646:                     }
11647:                 } elsif ($accesstype eq 'public') {
11648:                     $action = 'update';
11649:                     $aclnum = $num;
11650:                     last;
11651:                 }
11652:             }
11653:         }
11654:         if ($action eq 'none') {
11655:             next;
11656:         } else {
11657:             my %changes;
11658:             my $newend = 0;
11659:             my $newstart = $now;
11660:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11661:             $changes{$action}{$newkey} = {
11662:                 type => $accesstype,
11663:                 time => {
11664:                     start => $newstart,
11665:                     end   => $newend,
11666:                 },
11667:             };
11668:             if ($accesstype eq 'ip') {
11669:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11670:             }
11671:             my ($outcome,$deloutcome,$new_values,$translation) =
11672:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11673:             unless ($outcome eq 'ok') {
11674:                 $errors .= $outcome.' ';
11675:             }
11676:         }
11677:     }
11678:     if ($errors) {
11679:         $errors =~ s/\s$//;
11680:         return $errors;
11681:     } else {
11682:         return 'ok';
11683:     }
11684: }
11685: 
11686: #------------------------------------------------------Get Marked as Read Only
11687: 
11688: sub get_marked_as_readonly {
11689:     my ($domain,$user,$what,$group) = @_;
11690:     my $current_permissions = &get_portfile_permissions($domain,$user);
11691:     my @readonly_files;
11692:     my $cmp1=$what;
11693:     if (ref($what)) { $cmp1=join('',@{$what}) };
11694:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11695:         if (defined($group)) {
11696:             if ($file_name !~ m-^\Q$group\E/-) {
11697:                 next;
11698:             }
11699:         }
11700:         if (ref($value) eq "ARRAY"){
11701:             foreach my $stored_what (@{$value}) {
11702:                 my $cmp2=$stored_what;
11703:                 if (ref($stored_what) eq 'ARRAY') {
11704:                     $cmp2=join('',@{$stored_what});
11705:                 }
11706:                 if ($cmp1 eq $cmp2) {
11707:                     push(@readonly_files, $file_name);
11708:                     last;
11709:                 } elsif (!defined($what)) {
11710:                     push(@readonly_files, $file_name);
11711:                     last;
11712:                 }
11713:             }
11714:         }
11715:     }
11716:     return @readonly_files;
11717: }
11718: #-----------------------------------------------------------Get Marked as Read Only Hash
11719: 
11720: sub get_marked_as_readonly_hash {
11721:     my ($current_permissions,$group,$what) = @_;
11722:     my %readonly_files;
11723:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11724:         if (defined($group)) {
11725:             if ($file_name !~ m-^\Q$group\E/-) {
11726:                 next;
11727:             }
11728:         }
11729:         if (ref($value) eq "ARRAY"){
11730:             foreach my $stored_what (@{$value}) {
11731:                 if (ref($stored_what) eq 'ARRAY') {
11732:                     foreach my $lock_descriptor(@{$stored_what}) {
11733:                         if ($lock_descriptor eq 'graded') {
11734:                             $readonly_files{$file_name} = 'graded';
11735:                         } elsif ($lock_descriptor eq 'handback') {
11736:                             $readonly_files{$file_name} = 'handback';
11737:                         } else {
11738:                             if (!exists($readonly_files{$file_name})) {
11739:                                 $readonly_files{$file_name} = 'locked';
11740:                             }
11741:                         }
11742:                     }
11743:                 } 
11744:             }
11745:         } 
11746:     }
11747:     return %readonly_files;
11748: }
11749: # ------------------------------------------------------------ Unmark as Read Only
11750: 
11751: sub unmark_as_readonly {
11752:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11753:     # for portfolio submissions, $what contains [$symb,$crsid] 
11754:     my ($domain,$user,$what,$file_name,$group) = @_;
11755:     $file_name = &declutter_portfile($file_name);
11756:     my $symb_crs = $what;
11757:     if (ref($what)) { $symb_crs=join('',@$what); }
11758:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11759:     my ($tmp)=keys(%current_permissions);
11760:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11761:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11762:     foreach my $file (@readonly_files) {
11763: 	my $clean_file = &declutter_portfile($file);
11764: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11765: 	my $current_locks = $current_permissions{$file};
11766:         my @new_locks;
11767:         my @del_keys;
11768:         if (ref($current_locks) eq "ARRAY"){
11769:             foreach my $locker (@{$current_locks}) {
11770:                 my $compare=$locker;
11771:                 if (ref($locker) eq 'ARRAY') {
11772:                     $compare=join('',@{$locker});
11773:                     if ($compare ne $symb_crs) {
11774:                         push(@new_locks, $locker);
11775:                     }
11776:                 }
11777:             }
11778:             if (scalar(@new_locks) > 0) {
11779:                 $current_permissions{$file} = \@new_locks;
11780:             } else {
11781:                 push(@del_keys, $file);
11782:                 &del('file_permissions',\@del_keys, $domain, $user);
11783:                 delete($current_permissions{$file});
11784:             }
11785:         }
11786:     }
11787:     &put('file_permissions',\%current_permissions,$domain,$user);
11788:     return;
11789: }
11790: 
11791: # ------------------------------------------------------------ Directory lister
11792: 
11793: sub dirlist {
11794:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11795:     $uri=~s/^\///;
11796:     $uri=~s/\/$//;
11797:     my ($udom, $uname);
11798:     if ($getuserdir) {
11799:         $udom = $userdomain;
11800:         $uname = $username;
11801:     } else {
11802:         (undef,$udom,$uname)=split(/\//,$uri);
11803:         if(defined($userdomain)) {
11804:             $udom = $userdomain;
11805:         }
11806:         if(defined($username)) {
11807:             $uname = $username;
11808:         }
11809:     }
11810:     my ($dirRoot,$listing,@listing_results);
11811: 
11812:     $dirRoot = $perlvar{'lonDocRoot'};
11813:     if (defined($getpropath)) {
11814:         $dirRoot = &propath($udom,$uname);
11815:         $dirRoot =~ s/\/$//;
11816:     } elsif (defined($getuserdir)) {
11817:         my $subdir=$uname.'__';
11818:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11819:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11820:                    ."/$udom/$subdir/$uname";
11821:     } elsif (defined($alternateRoot)) {
11822:         $dirRoot = $alternateRoot;
11823:     }
11824: 
11825:     if($udom) {
11826:         if($uname) {
11827:             my $uhome = &homeserver($uname,$udom);
11828:             if ($uhome eq 'no_host') {
11829:                 return ([],'no_host');
11830:             }
11831:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11832:                               .$getuserdir.':'.&escape($dirRoot)
11833:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11834:             if ($listing eq 'unknown_cmd') {
11835:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11836:             } else {
11837:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11838:             }
11839:             if ($listing eq 'unknown_cmd') {
11840:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11841:                 @listing_results = split(/:/,$listing);
11842:             } else {
11843:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11844:             }
11845:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11846:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11847:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11848:                 return ([],$listing);
11849:             } else {
11850:                 return (\@listing_results);
11851:             }
11852:         } elsif(!$alternateRoot) {
11853:             my (%allusers,%listerror);
11854: 	    my %servers = &get_servers($udom,'library');
11855:  	    foreach my $tryserver (keys(%servers)) {
11856:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11857:                                   &escape($udom),$tryserver);
11858:                 if ($listing eq 'unknown_cmd') {
11859: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11860: 				      $udom, $tryserver);
11861:                 } else {
11862:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11863:                 }
11864: 		if ($listing eq 'unknown_cmd') {
11865: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11866: 				      $udom, $tryserver);
11867: 		    @listing_results = split(/:/,$listing);
11868: 		} else {
11869: 		    @listing_results =
11870: 			map { &unescape($_); } split(/:/,$listing);
11871: 		}
11872:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11873:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11874:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11875:                     $listerror{$tryserver} = $listing;
11876:                 } else {
11877: 		    foreach my $line (@listing_results) {
11878: 			my ($entry) = split(/&/,$line,2);
11879: 			$allusers{$entry} = 1;
11880: 		    }
11881: 		}
11882:             }
11883:             my @alluserslist=();
11884:             foreach my $user (sort(keys(%allusers))) {
11885:                 push(@alluserslist,$user.'&user');
11886:             }
11887: 
11888:             if (!%listerror) {
11889:                 # no errors
11890:                 return (\@alluserslist);
11891:             } elsif (scalar(keys(%servers)) == 1) {
11892:                 # one library server, one error 
11893:                 my ($key) = keys(%listerror);
11894:                 return (\@alluserslist, $listerror{$key});
11895:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11896:                 # con_lost indicates that we might miss data from at least one
11897:                 # library server
11898:                 return (\@alluserslist, 'con_lost');
11899:             } else {
11900:                 # multiple library servers and no con_lost -> data should be
11901:                 # complete. 
11902:                 return (\@alluserslist);
11903:             }
11904: 
11905:         } else {
11906:             return ([],'missing username');
11907:         }
11908:     } elsif(!defined($getpropath)) {
11909:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11910:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11911:         return (\@all_domains);
11912:     } else {
11913:         return ([],'missing domain');
11914:     }
11915: }
11916: 
11917: # --------------------------------------------- GetFileTimestamp
11918: # This function utilizes dirlist and returns the date stamp for
11919: # when it was last modified.  It will also return an error of -1
11920: # if an error occurs
11921: 
11922: sub GetFileTimestamp {
11923:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11924:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11925:     $studentName   = &LONCAPA::clean_username($studentName);
11926:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11927:                                     undef,$getuserdir);
11928:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11929:         return -1;
11930:     }
11931:     if (ref($fileref) eq 'ARRAY') {
11932:         my @stats = split('&',$fileref->[0]);
11933:         # @stats contains first the filename, then the stat output
11934:         return $stats[10]; # so this is 10 instead of 9.
11935:     } else {
11936:         return -1;
11937:     }
11938: }
11939: 
11940: sub stat_file {
11941:     my ($uri) = @_;
11942:     $uri = &clutter_with_no_wrapper($uri);
11943: 
11944:     my ($udom,$uname,$file);
11945:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11946: 	($udom,$uname,$file) =
11947: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11948: 	$file = 'userfiles/'.$file;
11949:     }
11950:     if ($uri =~ m-^/res/-) {
11951: 	($udom,$uname) = 
11952: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11953: 	$file = $uri;
11954:     }
11955: 
11956:     if (!$udom || !$uname || !$file) {
11957: 	# unable to handle the uri
11958: 	return ();
11959:     }
11960:     my $getpropath;
11961:     if ($file =~ /^userfiles\//) {
11962:         $getpropath = 1;
11963:     }
11964:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11965:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11966:         return ();
11967:     } else {
11968:         if (ref($listref) eq 'ARRAY') {
11969:             my @stats = split('&',$listref->[0]);
11970: 	    shift(@stats); #filename is first
11971: 	    return @stats;
11972:         }
11973:     }
11974:     return ();
11975: }
11976: 
11977: # --------------------------------------------------------- recursedirs
11978: # Recursive function to traverse either a specific user's Authoring Space
11979: # or corresponding Published Resource Space, and populate the hash ref:
11980: # $dirhashref with URLs of all directories, and if $filehashref hash
11981: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11982: # or .rights files in resource space, and .meta, .save, .log, and .bak
11983: # files in Authoring Space.
11984: #
11985: # Inputs:
11986: #
11987: # $is_home - true if current server is home server for user's space
11988: # $context - either: priv, or res respectively for Authoring or Resource Space.
11989: # $docroot - Document root (i.e., /home/httpd/html
11990: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11991: # $relpath - Current path (relative to top level).
11992: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11993: # $filehashref - reference to hash to populate with URLs of files (Optional)
11994: #
11995: # Returns: nothing
11996: #
11997: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11998: #
11999: # Currently used by interface/londocs.pm to create linked select boxes for
12000: # directory and filename to import a Course "Author" resource into a course, and
12001: # also to create linked select boxes for Authoring Space and Directory to choose
12002: # save location for creation of a new "standard" problem from the Course Editor.
12003: #
12004: 
12005: sub recursedirs {
12006:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12007:     return unless (ref($dirhashref) eq 'HASH');
12008:     my $currpath = $docroot.$toppath;
12009:     if ($relpath) {
12010:         $currpath .= "/$relpath";
12011:     }
12012:     my $savefile;
12013:     if (ref($filehashref)) {
12014:         $savefile = 1;
12015:     }
12016:     if ($is_home) {
12017:         if (opendir(my $dirh,$currpath)) {
12018:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12019:                 next if ($item eq '');
12020:                 if (-d "$currpath/$item") {
12021:                     my $newpath;
12022:                     if ($relpath) {
12023:                         $newpath = "$relpath/$item";
12024:                     } else {
12025:                         $newpath = $item;
12026:                     }
12027:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12028:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12029:                 } elsif ($savefile) {
12030:                     if ($context eq 'priv') {
12031:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12032:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12033:                         }
12034:                     } else {
12035:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
12036:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12037:                         }
12038:                     }
12039:                 }
12040:             }
12041:             closedir($dirh);
12042:         }
12043:     } else {
12044:         my ($dirlistref,$listerror) =
12045:             &dirlist($toppath.$relpath);
12046:         my @dir_lines;
12047:         my $dirptr=16384;
12048:         if (ref($dirlistref) eq 'ARRAY') {
12049:             foreach my $dir_line (sort
12050:                               {
12051:                                   my ($afile)=split('&',$a,2);
12052:                                   my ($bfile)=split('&',$b,2);
12053:                                   return (lc($afile) cmp lc($bfile));
12054:                               } (@{$dirlistref})) {
12055:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12056:                     split(/\&/,$dir_line,16);
12057:                 $item =~ s/\s+$//;
12058:                 next if (($item =~ /^\.\.?$/) || ($obs));
12059:                 if ($dirptr&$testdir) {
12060:                     my $newpath;
12061:                     if ($relpath) {
12062:                         $newpath = "$relpath/$item";
12063:                     } else {
12064:                         $relpath = '/';
12065:                         $newpath = $item;
12066:                     }
12067:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12068:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12069:                 } elsif ($savefile) {
12070:                     if ($context eq 'priv') {
12071:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12072:                             $filehashref->{$relpath}{$item} = 1;
12073:                         }
12074:                     } else {
12075:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
12076:                             $filehashref->{$relpath}{$item} = 1;
12077:                         }
12078:                     }
12079:                 }
12080:             }
12081:         }
12082:     }
12083:     return;
12084: }
12085: 
12086: # -------------------------------------------------------- Value of a Condition
12087: 
12088: # gets the value of a specific preevaluated condition
12089: #    stored in the string  $env{user.state.<cid>}
12090: # or looks up a condition reference in the bighash and if if hasn't
12091: # already been evaluated recurses into docondval to get the value of
12092: # the condition, then memoizing it to 
12093: #   $env{user.state.<cid>.<condition>}
12094: sub directcondval {
12095:     my $number=shift;
12096:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12097: 	&Apache::lonuserstate::evalstate();
12098:     }
12099:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12100: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12101:     } elsif ($number =~ /^_/) {
12102: 	my $sub_condition;
12103: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12104: 		&GDBM_READER(),0640)) {
12105: 	    $sub_condition=$bighash{'conditions'.$number};
12106: 	    untie(%bighash);
12107: 	}
12108: 	my $value = &docondval($sub_condition);
12109: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12110: 	return $value;
12111:     }
12112:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12113:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12114:     } else {
12115:        return 2;
12116:     }
12117: }
12118: 
12119: # get the collection of conditions for this resource
12120: sub condval {
12121:     my $condidx=shift;
12122:     my $allpathcond='';
12123:     foreach my $cond (split(/\|/,$condidx)) {
12124: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12125: 	    $allpathcond.=
12126: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12127: 	}
12128:     }
12129:     $allpathcond=~s/\|$//;
12130:     return &docondval($allpathcond);
12131: }
12132: 
12133: #evaluates an expression of conditions
12134: sub docondval {
12135:     my ($allpathcond) = @_;
12136:     my $result=0;
12137:     if ($env{'request.course.id'}
12138: 	&& defined($allpathcond)) {
12139: 	my $operand='|';
12140: 	my @stack;
12141: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12142: 	    if ($chunk eq '(') {
12143: 		push @stack,($operand,$result);
12144: 	    } elsif ($chunk eq ')') {
12145: 		my $before=pop @stack;
12146: 		if (pop @stack eq '&') {
12147: 		    $result=$result>$before?$before:$result;
12148: 		} else {
12149: 		    $result=$result>$before?$result:$before;
12150: 		}
12151: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12152: 		$operand=$chunk;
12153: 	    } else {
12154: 		my $new=directcondval($chunk);
12155: 		if ($operand eq '&') {
12156: 		    $result=$result>$new?$new:$result;
12157: 		} else {
12158: 		    $result=$result>$new?$result:$new;
12159: 		}
12160: 	    }
12161: 	}
12162:     }
12163:     return $result;
12164: }
12165: 
12166: # ---------------------------------------------------- Devalidate courseresdata
12167: 
12168: sub devalidatecourseresdata {
12169:     my ($coursenum,$coursedomain)=@_;
12170:     my $hashid=$coursenum.':'.$coursedomain;
12171:     &devalidate_cache_new('courseres',$hashid);
12172: }
12173: 
12174: 
12175: # --------------------------------------------------- Course Resourcedata Query
12176: #
12177: #  Parameters:
12178: #      $coursenum    - Number of the course.
12179: #      $coursedomain - Domain at which the course was created.
12180: #  Returns:
12181: #     A hash of the course parameters along (I think) with timestamps
12182: #     and version info.
12183: 
12184: sub get_courseresdata {
12185:     my ($coursenum,$coursedomain)=@_;
12186:     my $coursehom=&homeserver($coursenum,$coursedomain);
12187:     my $hashid=$coursenum.':'.$coursedomain;
12188:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12189:     my %dumpreply;
12190:     unless (defined($cached)) {
12191: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12192: 	$result=\%dumpreply;
12193: 	my ($tmp) = keys(%dumpreply);
12194: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12195: 	    &do_cache_new('courseres',$hashid,$result,600);
12196: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12197: 	    return $tmp;
12198: 	} elsif ($tmp =~ /^(error)/) {
12199: 	    $result=undef;
12200: 	    &do_cache_new('courseres',$hashid,$result,600);
12201: 	}
12202:     }
12203:     return $result;
12204: }
12205: 
12206: sub devalidateuserresdata {
12207:     my ($uname,$udom)=@_;
12208:     my $hashid="$udom:$uname";
12209:     &devalidate_cache_new('userres',$hashid);
12210: }
12211: 
12212: sub get_userresdata {
12213:     my ($uname,$udom)=@_;
12214:     #most student don\'t have any data set, check if there is some data
12215:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12216: 
12217:     my $hashid="$udom:$uname";
12218:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12219:     if (!defined($cached)) {
12220: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12221: 	$result=\%resourcedata;
12222: 	&do_cache_new('userres',$hashid,$result,600);
12223:     }
12224:     my ($tmp)=keys(%$result);
12225:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12226: 	return $result;
12227:     }
12228:     #error 2 occurs when the .db doesn't exist
12229:     if ($tmp!~/error: 2 /) {
12230:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12231: 	    &logthis("<font color=\"blue\">WARNING:".
12232: 		     " Trying to get resource data for ".
12233: 		     $uname." at ".$udom.": ".
12234: 		     $tmp."</font>");
12235:         }
12236:     } elsif ($tmp=~/error: 2 /) {
12237: 	#&EXT_cache_set($udom,$uname);
12238: 	&do_cache_new('userres',$hashid,undef,600);
12239: 	undef($tmp); # not really an error so don't send it back
12240:     }
12241:     return $tmp;
12242: }
12243: #----------------------------------------------- resdata - return resource data
12244: #  Purpose:
12245: #    Return resource data for either users or for a course.
12246: #  Parameters:
12247: #     $name      - Course/user name.
12248: #     $domain    - Name of the domain the user/course is registered on.
12249: #     $type      - Type of thing $name is (must be 'course' or 'user')
12250: #     $mapp      - decluttered URL of enclosing map  
12251: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12252: #     $recurseup - Ref to array of map URLs, starting with map containing
12253: #                  $mapp up through hierarchy of nested maps to top level map.  
12254: #     $courseid  - CourseID (first part of param identifier).
12255: #     $modifier  - Middle part of param identifier.
12256: #     $what      - Last part of param identifier.
12257: #     @which     - Array of names of resources desired.
12258: #  Returns:
12259: #     The value of the first reasource in @which that is found in the
12260: #     resource hash.
12261: #  Exceptional Conditions:
12262: #     If the $type passed in is not valid (not the string 'course' or 
12263: #     'user', an undefined  reference is returned.
12264: #     If none of the resources are found, an undef is returned
12265: sub resdata {
12266:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12267:         $modifier,$what,@which)=@_;
12268:     my $result;
12269:     if ($type eq 'course') {
12270: 	$result=&get_courseresdata($name,$domain);
12271:     } elsif ($type eq 'user') {
12272: 	$result=&get_userresdata($name,$domain);
12273:     }
12274:     if (!ref($result)) { return $result; }    
12275:     foreach my $item (@which) {
12276:         if ($item->[1] eq 'course') {
12277:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12278:                 unless ($$recursed) {
12279:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12280:                     $$recursed = 1;
12281:                 }
12282:                 foreach my $item (@${recurseup}) {
12283:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12284:                     last if (defined($result->{$norecursechk}));
12285:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12286:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12287:                 }
12288:             }
12289:         }
12290:         if (defined($result->{$item->[0]})) {
12291: 	    return [$result->{$item->[0]},$item->[1]];
12292: 	}
12293:     }
12294:     return undef;
12295: }
12296: 
12297: sub get_domain_lti {
12298:     my ($cdom,$context) = @_;
12299:     my ($name,$cachename,%lti);
12300:     if ($context eq 'consumer') {
12301:         $name = 'ltitools';
12302:     } elsif ($context eq 'provider') {
12303:         $name = 'lti';
12304:     } elsif ($context eq 'linkprot') {
12305:         $name = 'ltisec';
12306:     } else {
12307:         return %lti;
12308:     }
12309: 
12310:     if ($context eq 'linkprot') {
12311:         $cachename = $context;
12312:     } else {
12313:         $cachename = $name;
12314:     }
12315:     
12316:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12317:     if (defined($cached)) {
12318:         if (ref($result) eq 'HASH') {
12319:             %lti = %{$result};
12320:         }
12321:     } else {
12322:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12323:         if (ref($domconfig{$name}) eq 'HASH') {
12324:             if ($context eq 'linkprot') {
12325:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12326:                     %lti = %{$domconfig{$name}{'linkprot'}};
12327:                 }
12328:             } else {
12329:                 %lti = %{$domconfig{$name}};
12330:             }
12331:             if (($context eq 'consumer') && (keys(%lti))) {
12332:                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12333:                 if (ref($encdomconfig{$name}) eq 'HASH') {
12334:                     foreach my $id (keys(%lti)) {
12335:                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12336:                             foreach my $item ('key','secret') {
12337:                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12338:                             }
12339:                         }
12340:                     }
12341:                 }
12342:             }
12343:         }
12344:         my $cachetime = 24*60*60;
12345:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12346:     }
12347:     return %lti;
12348: }
12349: 
12350: sub get_course_lti {
12351:     my ($cnum,$cdom) = @_;
12352:     my $hashid=$cdom.'_'.$cnum;
12353:     my %courselti;
12354:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
12355:     if (defined($cached)) {
12356:         if (ref($result) eq 'HASH') {
12357:             %courselti = %{$result};
12358:         }
12359:     } else {
12360:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12361:         my $cachetime = 24*60*60;
12362:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12363:     }
12364:     return %courselti;
12365: }
12366: 
12367: sub courselti_itemid {
12368:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12369:     my ($chome,$itemid);
12370:     $chome = &homeserver($cnum,$cdom);
12371:     return if ($chome eq 'no_host');
12372:     if (ref($params) eq 'HASH') {
12373:         my $items = &freeze_escape($params);
12374:         my $rep;
12375:         if (grep { $_ eq $chome } current_machine_ids()) {
12376:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12377:         } else {
12378:             my $escurl = &escape($url);
12379:             my $escmethod = &escape($method);
12380:             my $items = &freeze_escape($params);
12381:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12382:         }
12383:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12384:                 ($rep eq 'unknown_cmd')) {
12385:             $itemid = $rep;
12386:         }
12387:     }
12388:     return $itemid;
12389: }
12390: 
12391: sub domainlti_itemid {
12392:     my ($cdom,$url,$method,$params,$context) = @_;
12393:     my ($primary_id,$itemid);
12394:     $primary_id = &domain($cdom,'primary');
12395:     return if ($primary_id eq '');
12396:     if (ref($params) eq 'HASH') {
12397:         my $items = &freeze_escape($params);
12398:         my $rep;
12399:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12400:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12401:         } else {
12402:             my $cnum = '';
12403:             my $escurl = &escape($url);
12404:             my $escmethod = &escape($method);
12405:             my $items = &freeze_escape($params);
12406:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12407:         }
12408:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12409:                 ($rep eq 'unknown_cmd')) {
12410:             $itemid = $rep;
12411:         }
12412:     }
12413:     return $itemid;
12414: }
12415: 
12416: sub get_numsuppfiles {
12417:     my ($cnum,$cdom,$ignorecache)=@_;
12418:     my $hashid=$cnum.':'.$cdom;
12419:     my ($suppcount,$cached);
12420:     unless ($ignorecache) {
12421:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12422:     }
12423:     unless (defined($cached)) {
12424:         my $chome=&homeserver($cnum,$cdom);
12425:         unless ($chome eq 'no_host') {
12426:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12427:             my $suppmap = 'supplemental.sequence';
12428:             ($suppcount,$supptools,$errors) =
12429:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12430:                                                          $supptools,$errors);
12431:         }
12432:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12433:     }
12434:     return $suppcount;
12435: }
12436: 
12437: #
12438: # EXT resource caching routines
12439: #
12440: 
12441: {
12442: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12443: #
12444: # The course for which we cache
12445: my $cachedmapkey='';
12446: # The cached recursive maps for this course
12447: my %cachedmaps=();
12448: # When this was last done
12449: my $cachedmaptime='';
12450: 
12451: sub clear_EXT_cache_status {
12452:     &delenv('cache.EXT.');
12453: }
12454: 
12455: sub EXT_cache_status {
12456:     my ($target_domain,$target_user) = @_;
12457:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12458:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12459:         # We know already the user has no data
12460:         return 1;
12461:     } else {
12462:         return 0;
12463:     }
12464: }
12465: 
12466: sub EXT_cache_set {
12467:     my ($target_domain,$target_user) = @_;
12468:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12469:     #&appenv({$cachename => time});
12470: }
12471: 
12472: # --------------------------------------------------------- Value of a Variable
12473: sub EXT {
12474: 
12475:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12476:     unless ($varname) { return ''; }
12477:     #get real user name/domain, courseid and symb
12478:     my $courseid;
12479:     my $publicuser;
12480:     if ($symbparm) {
12481: 	$symbparm=&get_symb_from_alias($symbparm);
12482:     }
12483:     if (!($uname && $udom)) {
12484:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12485:       if (!$symbparm) {	$symbparm=$cursymb; }
12486:     } else {
12487: 	$courseid=$env{'request.course.id'};
12488:     }
12489:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12490:     my $rest;
12491:     if (defined($therest[0])) {
12492:        $rest=join('.',@therest);
12493:     } else {
12494:        $rest='';
12495:     }
12496: 
12497:     my $qualifierrest=$qualifier;
12498:     if ($rest) { $qualifierrest.='.'.$rest; }
12499:     my $spacequalifierrest=$space;
12500:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12501:     if ($realm eq 'user') {
12502: # --------------------------------------------------------------- user.resource
12503: 	if ($space eq 'resource') {
12504: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12505: 		  || defined($Apache::lonhomework::parsing_a_task))
12506: 		 &&
12507: 		 ($symbparm eq &symbread()) ) {
12508: 		# if we are in the middle of processing the resource the
12509: 		# get the value we are planning on committing
12510:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12511:                     return $Apache::lonhomework::results{$qualifierrest};
12512:                 } else {
12513:                     return $Apache::lonhomework::history{$qualifierrest};
12514:                 }
12515: 	    } else {
12516: 		my %restored;
12517: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12518: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12519: 		} else {
12520: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12521: 		}
12522: 		return $restored{$qualifierrest};
12523: 	    }
12524: # ----------------------------------------------------------------- user.access
12525:         } elsif ($space eq 'access') {
12526: 	    # FIXME - not supporting calls for a specific user
12527:             return &allowed($qualifier,$rest);
12528: # ------------------------------------------ user.preferences, user.environment
12529:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12530: 	    if (($uname eq $env{'user.name'}) &&
12531: 		($udom eq $env{'user.domain'})) {
12532: 		return $env{join('.',('environment',$qualifierrest))};
12533: 	    } else {
12534: 		my %returnhash;
12535: 		if (!$publicuser) {
12536: 		    %returnhash=&userenvironment($udom,$uname,
12537: 						 $qualifierrest);
12538: 		}
12539: 		return $returnhash{$qualifierrest};
12540: 	    }
12541: # ----------------------------------------------------------------- user.course
12542:         } elsif ($space eq 'course') {
12543: 	    # FIXME - not supporting calls for a specific user
12544:             return $env{join('.',('request.course',$qualifier))};
12545: # ------------------------------------------------------------------- user.role
12546:         } elsif ($space eq 'role') {
12547: 	    # FIXME - not supporting calls for a specific user
12548:             my ($role,$where)=split(/\./,$env{'request.role'});
12549:             if ($qualifier eq 'value') {
12550: 		return $role;
12551:             } elsif ($qualifier eq 'extent') {
12552:                 return $where;
12553:             }
12554: # ----------------------------------------------------------------- user.domain
12555:         } elsif ($space eq 'domain') {
12556:             return $udom;
12557: # ------------------------------------------------------------------- user.name
12558:         } elsif ($space eq 'name') {
12559:             return $uname;
12560: # ---------------------------------------------------- Any other user namespace
12561:         } else {
12562: 	    my %reply;
12563: 	    if (!$publicuser) {
12564: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12565: 	    }
12566: 	    return $reply{$qualifierrest};
12567:         }
12568:     } elsif ($realm eq 'query') {
12569: # ---------------------------------------------- pull stuff out of query string
12570:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12571: 						[$spacequalifierrest]);
12572: 	return $env{'form.'.$spacequalifierrest}; 
12573:    } elsif ($realm eq 'request') {
12574: # ------------------------------------------------------------- request.browser
12575:         if ($space eq 'browser') {
12576:             return $env{'browser.'.$qualifier};
12577: # ------------------------------------------------------------ request.filename
12578:         } else {
12579:             return $env{'request.'.$spacequalifierrest};
12580:         }
12581:     } elsif ($realm eq 'course') {
12582: # ---------------------------------------------------------- course.description
12583:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12584:     } elsif ($realm eq 'resource') {
12585: 
12586: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12587: 	    if (!$symbparm) { $symbparm=&symbread(); }
12588: 	}
12589: 
12590:         if ($qualifier eq '') {
12591: 	    if ($space eq 'title') {
12592: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12593: 	        return &gettitle($symbparm);
12594: 	    }
12595: 	
12596: 	    if ($space eq 'map') {
12597: 	        my ($map) = &decode_symb($symbparm);
12598: 	        return &symbread($map);
12599: 	    }
12600:             if ($space eq 'maptitle') {
12601:                 my ($map) = &decode_symb($symbparm);
12602:                 return &gettitle($map);
12603:             }
12604: 	    if ($space eq 'filename') {
12605: 	        if ($symbparm) {
12606: 		    return &clutter((&decode_symb($symbparm))[2]);
12607: 	        }
12608: 	        return &hreflocation('',$env{'request.filename'});
12609: 	    }
12610: 
12611:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12612:                 if ($space eq 'visibleparts') {
12613:                     my $navmap = Apache::lonnavmaps::navmap->new();
12614:                     my $item;
12615:                     if (ref($navmap)) {
12616:                         my $res = $navmap->getBySymb($symbparm);
12617:                         my $parts = $res->parts();
12618:                         if (ref($parts) eq 'ARRAY') {
12619:                             $item = join(',',@{$parts});
12620:                         }
12621:                         undef($navmap);
12622:                     }
12623:                     return $item;
12624:                 }
12625:             }
12626:         }
12627: 
12628: 	my ($section, $group, @groups, @recurseup, $recursed);
12629:         if (ref($recurseupref) eq 'ARRAY') {
12630:             @recurseup = @{$recurseupref};
12631:             $recursed = 1;
12632:         }
12633: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12634:         if (($courseid eq '') && ($cid)) {
12635:             $courseid = $cid;
12636:         }
12637: 	if (($symbparm && $courseid) && 
12638: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12639: 
12640: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12641: 
12642: # ----------------------------------------------------- Cascading lookup scheme
12643: 	    my $symbp=$symbparm;
12644: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12645: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12646:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12647: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12648: 	    if (($env{'user.name'} eq $uname) &&
12649: 		($env{'user.domain'} eq $udom)) {
12650: 		$section=$env{'request.course.sec'};
12651:                 @groups = split(/:/,$env{'request.course.groups'});  
12652:                 @groups=&sort_course_groups($courseid,@groups); 
12653: 	    } else {
12654: 		if (! defined($usection)) {
12655: 		    $section=&getsection($udom,$uname,$courseid);
12656: 		} else {
12657: 		    $section = $usection;
12658: 		}
12659:                 @groups = &get_users_groups($udom,$uname,$courseid);
12660: 	    }
12661: 
12662: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12663: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12664:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12665: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12666: 
12667: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12668: 	    my $courselevelr=$courseid.'.'.$symbparm;
12669:             $courseleveli=$courseid.'.'.$recurseparm;
12670: 	    $courselevelm=$courseid.'.'.$mapparm;
12671: 
12672: # ----------------------------------------------------------- first, check user
12673: 
12674: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12675:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12676: 				       ([$courselevelr,'resource'],
12677: 					[$courselevelm,'map'     ],
12678:                                         [$courseleveli,'map'     ],
12679: 					[$courselevel, 'course'  ]));
12680: 	    if (defined($userreply)) { return &get_reply($userreply); }
12681: 
12682: # ------------------------------------------------ second, check some of course
12683:             my $coursereply;
12684:             if (@groups > 0) {
12685:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12686:                                        $recurseparm,$mapparm,$spacequalifierrest,
12687:                                        $mapp,\$recursed,\@recurseup);
12688:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12689:             }
12690: 
12691: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12692: 				  $env{'course.'.$courseid.'.domain'},
12693: 				  'course',$mapp,\$recursed,\@recurseup,
12694:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12695: 				  ([$seclevelr,   'resource'],
12696: 				   [$seclevelm,   'map'     ],
12697:                                    [$secleveli,   'map'     ],
12698: 				   [$seclevel,    'course'  ],
12699: 				   [$courselevelr,'resource']));
12700: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12701: 
12702: # ------------------------------------------------------ third, check map parms
12703: 	    my %parmhash=();
12704: 	    my $thisparm='';
12705: 	    if (tie(%parmhash,'GDBM_File',
12706: 		    $env{'request.course.fn'}.'_parms.db',
12707: 		    &GDBM_READER(),0640)) {
12708: 		$thisparm=$parmhash{$symbparm};
12709: 		untie(%parmhash);
12710: 	    }
12711: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12712: 	}
12713: # ------------------------------------------ fourth, look in resource metadata
12714:  
12715:         my $what = $spacequalifierrest;
12716: 	$what=~s/\./\_/;
12717: 	my $filename;
12718: 	if (!$symbparm) { $symbparm=&symbread(); }
12719: 	if ($symbparm) {
12720: 	    $filename=(&decode_symb($symbparm))[2];
12721: 	} else {
12722: 	    $filename=$env{'request.filename'};
12723: 	}
12724:         my $toolsymb;
12725:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12726:             $toolsymb = $symbparm;
12727:         }
12728: 	my $metadata=&metadata($filename,$what,$toolsymb);
12729: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12730: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12731: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12732: 
12733: # ----------------------------------------------- fifth, look in rest of course
12734: 	if ($symbparm && defined($courseid) && 
12735: 	    $courseid eq $env{'request.course.id'}) {
12736: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12737: 				     $env{'course.'.$courseid.'.domain'},
12738: 				     'course',$mapp,\$recursed,\@recurseup,
12739:                                      $courseid,'.',$spacequalifierrest,
12740: 				     ([$courselevelm,'map'   ],
12741:                                       [$courseleveli,'map'   ],
12742: 				      [$courselevel, 'course']));
12743: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12744: 	}
12745: # ------------------------------------------------------------------ Cascade up
12746: 	unless ($space eq '0') {
12747: 	    my @parts=split(/_/,$space);
12748: 	    my $id=pop(@parts);
12749: 	    my $part=join('_',@parts);
12750: 	    if ($part eq '') { $part='0'; }
12751: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12752: 				 $symbparm,$udom,$uname,$section,1);
12753: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12754: 	}
12755: 	if ($recurse) { return undef; }
12756: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12757: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12758: # ---------------------------------------------------- Any other user namespace
12759:     } elsif ($realm eq 'environment') {
12760: # ----------------------------------------------------------------- environment
12761: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12762: 	    return $env{'environment.'.$spacequalifierrest};
12763: 	} else {
12764: 	    if ($uname eq 'anonymous' && $udom eq '') {
12765: 		return '';
12766: 	    }
12767: 	    my %returnhash=&userenvironment($udom,$uname,
12768: 					    $spacequalifierrest);
12769: 	    return $returnhash{$spacequalifierrest};
12770: 	}
12771:     } elsif ($realm eq 'system') {
12772: # ----------------------------------------------------------------- system.time
12773: 	if ($space eq 'time') {
12774: 	    return time;
12775:         }
12776:     } elsif ($realm eq 'server') {
12777: # ----------------------------------------------------------------- system.time
12778: 	if ($space eq 'name') {
12779: 	    return $ENV{'SERVER_NAME'};
12780:         }
12781:     } elsif ($realm eq 'client') {
12782:         if ($space eq 'remote_addr') {
12783:             return &get_requestor_ip();
12784:         }
12785:     }
12786:     return '';
12787: }
12788: 
12789: sub get_reply {
12790:     my ($reply_value) = @_;
12791:     if (ref($reply_value) eq 'ARRAY') {
12792:         if (wantarray) {
12793: 	    return @$reply_value;
12794:         }
12795:         return $reply_value->[0];
12796:     } else {
12797:         return $reply_value;
12798:     }
12799: }
12800: 
12801: sub check_group_parms {
12802:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12803:         $recursed,$recurseupref) = @_;
12804:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12805:                   [$what,'course']);
12806:     my $coursereply;
12807:     foreach my $group (@{$groups}) {
12808:         my @groupitems = ();
12809:         foreach my $level (@levels) {
12810:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12811:              push(@groupitems,[$item,$level->[1]]);
12812:         }
12813:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12814:                                    $env{'course.'.$courseid.'.domain'},
12815:                                    'course',$mapp,$recursed,$recurseupref,
12816:                                    $courseid,'.['.$group.'].',$what,
12817:                                    @groupitems);
12818:         last if (defined($coursereply));
12819:     }
12820:     return $coursereply;
12821: }
12822: 
12823: sub get_map_hierarchy {
12824:     my ($mapname,$courseid) = @_;
12825:     my @recurseup = ();
12826:     if ($mapname) {
12827:         if (($cachedmapkey eq $courseid) &&
12828:             (abs($cachedmaptime-time)<5)) {
12829:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12830:                 return @{$cachedmaps{$mapname}};
12831:             }
12832:         }
12833:         my $navmap = Apache::lonnavmaps::navmap->new();
12834:         if (ref($navmap)) {
12835:             @recurseup = $navmap->recurseup_maps($mapname);
12836:             undef($navmap);
12837:             $cachedmaps{$mapname} = \@recurseup;
12838:             $cachedmaptime=time;
12839:             $cachedmapkey=$courseid;
12840:         }
12841:     }
12842:     return @recurseup;
12843: }
12844: 
12845: }
12846: 
12847: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12848:     my ($courseid,@groups) = @_;
12849:     @groups = sort(@groups);
12850:     return @groups;
12851: }
12852: 
12853: sub packages_tab_default {
12854:     my ($uri,$varname,$toolsymb)=@_;
12855:     my (undef,$part,$name)=split(/\./,$varname);
12856: 
12857:     my (@extension,@specifics,$do_default);
12858:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12859: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12860: 	if ($pack_type eq 'default') {
12861: 	    $do_default=1;
12862: 	} elsif ($pack_type eq 'extension') {
12863: 	    push(@extension,[$package,$pack_type,$pack_part]);
12864: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12865: 	    # only look at packages defaults for packages that this id is
12866: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12867: 	}
12868:     }
12869:     # first look for a package that matches the requested part id
12870:     foreach my $package (@specifics) {
12871: 	my (undef,$pack_type,$pack_part)=@{$package};
12872: 	next if ($pack_part ne $part);
12873: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12874: 	    return $packagetab{"$pack_type&$name&default"};
12875: 	}
12876:     }
12877:     # look for any possible matching non extension_ package
12878:     foreach my $package (@specifics) {
12879: 	my (undef,$pack_type,$pack_part)=@{$package};
12880: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12881: 	    return $packagetab{"$pack_type&$name&default"};
12882: 	}
12883: 	if ($pack_type eq 'part') { $pack_part='0'; }
12884: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12885: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12886: 	}
12887:     }
12888:     # look for any posible extension_ match
12889:     foreach my $package (@extension) {
12890: 	my ($package,$pack_type)=@{$package};
12891: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12892: 	    return $packagetab{"$pack_type&$name&default"};
12893: 	}
12894: 	if (defined($packagetab{$package."&$name&default"})) {
12895: 	    return $packagetab{$package."&$name&default"};
12896: 	}
12897:     }
12898:     # look for a global default setting
12899:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12900: 	return $packagetab{"default&$name&default"};
12901:     }
12902:     return undef;
12903: }
12904: 
12905: sub add_prefix_and_part {
12906:     my ($prefix,$part)=@_;
12907:     my $keyroot;
12908:     if (defined($prefix) && $prefix !~ /^__/) {
12909: 	# prefix that has a part already
12910: 	$keyroot=$prefix;
12911:     } elsif (defined($prefix)) {
12912: 	# prefix that is missing a part
12913: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12914:     } else {
12915: 	# no prefix at all
12916: 	if (defined($part)) { $keyroot='_'.$part; }
12917:     }
12918:     return $keyroot;
12919: }
12920: 
12921: # ---------------------------------------------------------------- Get metadata
12922: 
12923: my %metaentry;
12924: my %importedpartids;
12925: my %importedrespids;
12926: sub metadata {
12927:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12928:     $uri=&declutter($uri);
12929:     # if it is a non metadata possible uri return quickly
12930:     if (($uri eq '') || 
12931: 	(($uri =~ m|^/*adm/|) && 
12932: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12933:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12934: 	return undef;
12935:     }
12936:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12937: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12938: 	return undef;
12939:     }
12940:     my $filename=$uri;
12941:     $uri=~s/\.meta$//;
12942: #
12943: # Is the metadata already cached?
12944: # Look at timestamp of caching
12945: # Everything is cached by the main uri, libraries are never directly cached
12946: #
12947:     if (!defined($liburi)) {
12948: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12949: 	if (defined($cached)) { return $result->{':'.$what}; }
12950:     }
12951: 
12952: #
12953: # If the uri is for an external tool the file from
12954: # which metadata should be retrieved depends on whether
12955: # the tool had been configured to be gradable (set in the Course
12956: # Editor or Resource Editor).
12957: #
12958: # If a valid symb has been included as the third arg in the call
12959: # to &metadata() that can be used to retrieve the value of
12960: # parameter_0_gradable set for the resource, and included in the
12961: # uploaded map containing the tool. The value is retrieved via
12962: # &EXT(), if a valid symb is available.  Otherwise the value of
12963: # gradable in the exttool_$marker.db file for the tool instance
12964: # is retrieved via &get().
12965: #
12966: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12967: # hiddenresource and encrypturl (during course initialization)
12968: # the map-level parameter for resource.0.gradable included in the 
12969: # uploaded map containing the tool will not yet have been stored
12970: # in the user_course_parms.db file for the user's session, so in 
12971: # this case fall back to retrieving gradable status from the
12972: # exttool_$marker.db file.
12973: #
12974: # In order to avoid an infinite loop, &metadata() will return
12975: # before a call to &EXT(), if the uri is for an external tool
12976: # and the $what for which metadata is being requested is
12977: # parameter_0_gradable or 0_gradable.
12978: #
12979: 
12980:     if ($uri =~ /ext\.tool$/) {
12981:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12982:             return;
12983:         } else {
12984:             my ($checked,$use_passback);
12985:             if ($toolsymb ne '') {
12986:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12987:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12988:                     $checked = 1;
12989:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12990:                         $use_passback = 1;
12991:                     }
12992:                 }
12993:             }
12994:             unless ($checked) {
12995:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12996:                 $marker=~s/\D//g;
12997:                 if ($marker) {
12998:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12999:                     $use_passback = $toolsettings{'gradable'};
13000:                 }
13001:             }
13002:             if ($use_passback) {
13003:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13004:             } else {
13005:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13006:             }
13007:         }
13008:     }
13009: 
13010:     {
13011: # Imported parts would go here
13012:         my @origfiletagids=();
13013:         my $importedparts=0;
13014: 
13015: # Imported responseids would go here
13016:         my $importedresponses=0;
13017: #
13018: # Is this a recursive call for a library?
13019: #
13020: #	if (! exists($metacache{$uri})) {
13021: #	    $metacache{$uri}={};
13022: #	}
13023: 	my $cachetime = 60*60;
13024:         if ($liburi) {
13025: 	    $liburi=&declutter($liburi);
13026:             $filename=$liburi;
13027:         } else {
13028: 	    &devalidate_cache_new('meta',$uri);
13029: 	    undef(%metaentry);
13030: 	}
13031:         my %metathesekeys=();
13032:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13033: 	my $metastring;
13034: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13035: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13036: 	    $metastring = 
13037: 		&Apache::lonnet::ssi_body($which,
13038: 					  ('grade_target' => 'meta'));
13039: 	    $cachetime = 1; # only want this cached in the child not long term
13040: 	} elsif (($uri !~ m -^(editupload)/-) && 
13041:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13042: 	    my $file=&filelocation('',&clutter($filename));
13043: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13044: 	    $metastring=&getfile($file);
13045: 	}
13046:         my $parser=HTML::LCParser->new(\$metastring);
13047:         my $token;
13048:         undef %metathesekeys;
13049:         while ($token=$parser->get_token) {
13050: 	    if ($token->[0] eq 'S') {
13051: 		if (defined($token->[2]->{'package'})) {
13052: #
13053: # This is a package - get package info
13054: #
13055: 		    my $package=$token->[2]->{'package'};
13056: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13057: 		    if (defined($token->[2]->{'id'})) { 
13058: 			$keyroot.='_'.$token->[2]->{'id'}; 
13059: 		    }
13060: 		    if ($metaentry{':packages'}) {
13061: 			$metaentry{':packages'}.=','.$package.$keyroot;
13062: 		    } else {
13063: 			$metaentry{':packages'}=$package.$keyroot;
13064: 		    }
13065: 		    foreach my $pack_entry (keys(%packagetab)) {
13066: 			my $part=$keyroot;
13067: 			$part=~s/^\_//;
13068: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13069: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13070: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13071: 			    # ignore package.tab specified default values
13072:                             # here &package_tab_default() will fetch those
13073: 			    if ($subp eq 'default') { next; }
13074: 			    my $value=$packagetab{$pack_entry};
13075: 			    my $unikey;
13076: 			    if ($pack =~ /_0$/) {
13077: 				$unikey='parameter_0_'.$name;
13078: 				$part=0;
13079: 			    } else {
13080: 				$unikey='parameter'.$keyroot.'_'.$name;
13081: 			    }
13082: 			    if ($subp eq 'display') {
13083: 				$value.=' [Part: '.$part.']';
13084: 			    }
13085: 			    $metaentry{':'.$unikey.'.part'}=$part;
13086: 			    $metathesekeys{$unikey}=1;
13087: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13088: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13089: 			    }
13090: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13091: 				$metaentry{':'.$unikey}=
13092: 				    $metaentry{':'.$unikey.'.default'};
13093: 			    }
13094: 			}
13095: 		    }
13096: 		} else {
13097: #
13098: # This is not a package - some other kind of start tag
13099: #
13100: 		    my $entry=$token->[1];
13101: 		    my $unikey='';
13102: 
13103: 		    if ($entry eq 'import') {
13104: #
13105: # Importing a library here
13106: #
13107:                         my $location=$parser->get_text('/import');
13108:                         my $dir=$filename;
13109:                         $dir=~s|[^/]*$||;
13110:                         $location=&filelocation($dir,$location);
13111: 
13112:                         my $importid=$token->[2]->{'id'};
13113:                         my $importmode=$token->[2]->{'importmode'};
13114: #
13115: # Check metadata for imported file to
13116: # see if it contained response items
13117: #
13118:                         my ($origfile,@libfilekeys);
13119:                         my %currmetaentry = %metaentry;
13120:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13121:                                                            $depthcount+1));
13122:                         if (grep(/^responseorder$/,@libfilekeys)) {
13123:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13124:                                                              undef,$depthcount+1);
13125:                             if ($libresponseorder ne '') {
13126:                                 if ($#origfiletagids<0) {
13127:                                     undef(%importedrespids);
13128:                                     undef(%importedpartids);
13129:                                 }
13130:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13131:                                 if (@respids) {
13132:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13133:                                 }
13134:                                 if ($importedrespids{$importid} ne '') {
13135:                                     $importedresponses = 1;
13136: # We need to get the original file and the imported file to get the response order correct
13137: # Load and inspect original file
13138:                                     if ($#origfiletagids<0) {
13139:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13140:                                         $origfile=&getfile($origfilelocation);
13141:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13142:                                     }
13143:                                 }
13144:                             }
13145:                         }
13146: # Do not overwrite contents of %metaentry hash for resource itself with 
13147: # hash populated for imported library file
13148:                         %metaentry = %currmetaentry;
13149:                         undef(%currmetaentry);
13150:                         if ($importmode eq 'part') {
13151: # Import as part(s)
13152:                            $importedparts=1;
13153: # We need to get the original file and the imported file to get the part order correct
13154: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13155: # Load and inspect original file if we didn't do that already
13156:                            if ($#origfiletagids<0) {
13157:                                undef(%importedrespids);
13158:                                undef(%importedpartids);
13159:                                if ($origfile eq '') {
13160:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13161:                                    $origfile=&getfile($origfilelocation);
13162:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13163:                                }
13164:                            }
13165:                            my @impfilepartids;
13166: # If <partorder> tag is included in metadata for the imported file
13167: # get the parts in the imported file from that.
13168:                            if (grep(/^partorder$/,@libfilekeys)) {
13169:                                %currmetaentry = %metaentry;
13170:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13171:                                                             $depthcount+1);
13172:                                %metaentry = %currmetaentry;
13173:                                undef(%currmetaentry);
13174:                                if ($libpartorder ne '') {
13175:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13176:                                }
13177:                            } else {
13178: # If no <partorder> tag available, load and inspect imported file
13179:                                my $impfile=&getfile($location);
13180:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13181:                            }
13182:                            if ($#impfilepartids>=0) {
13183: # This problem had parts
13184:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13185:                            } else {
13186: # Importing by turning a single problem into a problem part
13187: # It gets the import-tags ID as part-ID
13188:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13189:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13190:                            }
13191:                         } else {
13192: # Import as problem or as normal import
13193:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13194:                             unless ($importmode eq 'problem') {
13195: # Normal import
13196:                                 if (defined($token->[2]->{'id'})) {
13197:                                     $unikey.='_'.$token->[2]->{'id'};
13198:                                 }
13199:                             }
13200: # Check metadata for imported file to
13201: # see if it contained parts
13202:                             if (grep(/^partorder$/,@libfilekeys)) {
13203:                                 %currmetaentry = %metaentry;
13204:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13205:                                                              $depthcount+1);
13206:                                 %metaentry = %currmetaentry;
13207:                                 undef(%currmetaentry);
13208:                                 if ($libpartorder ne '') {
13209:                                     $importedparts = 1;
13210:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13211:                                 }
13212:                             }
13213:                         }
13214: 			if ($depthcount<20) {
13215: 			    my $metadata = 
13216: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13217: 					  $depthcount+1);
13218: 			    foreach my $meta (split(',',$metadata)) {
13219: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13220: 				$metathesekeys{$meta}=1;
13221: 			    }
13222:                         }
13223: 		    } else {
13224: #
13225: # Not importing, some other kind of non-package, non-library start tag
13226: # 
13227:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13228:                         if (defined($token->[2]->{'id'})) {
13229:                             $unikey.='_'.$token->[2]->{'id'};
13230:                         }
13231: 			if (defined($token->[2]->{'name'})) { 
13232: 			    $unikey.='_'.$token->[2]->{'name'}; 
13233: 			}
13234: 			$metathesekeys{$unikey}=1;
13235: 			foreach my $param (@{$token->[3]}) {
13236: 			    $metaentry{':'.$unikey.'.'.$param} =
13237: 				$token->[2]->{$param};
13238: 			}
13239: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13240: 			my $default=$metaentry{':'.$unikey.'.default'};
13241: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13242: 		 # only ws inside the tag, and not in default, so use default
13243: 		 # as value
13244: 			    $metaentry{':'.$unikey}=$default;
13245: 			} elsif ( $internaltext =~ /\S/ ) {
13246: 		  # something interesting inside the tag
13247: 			    $metaentry{':'.$unikey}=$internaltext;
13248: 			} else {
13249: 		  # no interesting values, don't set a default
13250: 			}
13251: # end of not-a-package not-a-library import
13252: 		    }
13253: # end of not-a-package start tag
13254: 		}
13255: # the next is the end of "start tag"
13256: 	    }
13257: 	}
13258: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13259: 	$extension = lc($extension);
13260: 	if ($extension eq 'htm') { $extension='html'; }
13261: 
13262: 	foreach my $key (keys(%packagetab)) {
13263: 	    #no specific packages #how's our extension
13264: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13265: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13266: 					 \%metathesekeys);
13267: 	}
13268: 
13269: 	if (!exists($metaentry{':packages'})
13270: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13271: 	    foreach my $key (keys(%packagetab)) {
13272: 		#no specific packages well let's get default then
13273: 		if ($key!~/^default&/) { next; }
13274: 		&metadata_create_package_def($uri,$key,'default',
13275: 					     \%metathesekeys);
13276: 	    }
13277: 	}
13278: # are there custom rights to evaluate
13279: 	if ($metaentry{':copyright'} eq 'custom') {
13280: 
13281:     #
13282:     # Importing a rights file here
13283:     #
13284: 	    unless ($depthcount) {
13285: 		my $location=$metaentry{':customdistributionfile'};
13286: 		my $dir=$filename;
13287: 		$dir=~s|[^/]*$||;
13288: 		$location=&filelocation($dir,$location);
13289: 		my $rights_metadata =
13290: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13291: 			      $depthcount+1);
13292: 		foreach my $rights (split(',',$rights_metadata)) {
13293: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13294: 		    $metathesekeys{$rights}=1;
13295: 		}
13296: 	    }
13297: 	}
13298: 	# uniqifiy package listing
13299: 	my %seen;
13300: 	my @uniq_packages =
13301: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13302: 	$metaentry{':packages'} = join(',',@uniq_packages);
13303: 
13304:         if (($importedresponses) || ($importedparts)) {
13305:             if ($importedparts) {
13306: # We had imported parts and need to rebuild partorder
13307:                 $metaentry{':partorder'}='';
13308:                 $metathesekeys{'partorder'}=1;
13309:             }
13310:             if ($importedresponses) {
13311: # We had imported responses and need to rebuil responseorder
13312:                 $metaentry{':responseorder'}='';
13313:                 $metathesekeys{'responseorder'}=1;
13314:             }
13315:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13316:                 my $origid = $origfiletagids[$index+1];
13317:                 if ($origfiletagids[$index] eq 'part') {
13318: # Original part, part of the problem
13319:                     if ($importedparts) {
13320:                         $metaentry{':partorder'}.=','.$origid;
13321:                     }
13322:                 } elsif ($origfiletagids[$index] eq 'import') {
13323:                     if ($importedparts) {
13324: # We have imported parts at this position
13325:                         if ($importedpartids{$origid} ne '') {
13326:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13327:                         }
13328:                     }
13329:                     if ($importedresponses) {
13330: # We have imported responses at this position
13331:                         if ($importedrespids{$origid} ne '') {
13332:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13333:                         }
13334:                     }
13335:                 } else {
13336: # Original response item, part of the problem
13337:                     if ($importedresponses) {
13338:                         $metaentry{':responseorder'}.=','.$origid;
13339:                     }
13340:                 }
13341:             }
13342:             if ($importedparts) {
13343:                 $metaentry{':partorder'}=~s/^\,//;
13344:             }
13345:             if ($importedresponses) {
13346:                 $metaentry{':responseorder'}=~s/^\,//;
13347:             }
13348:         }
13349: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13350: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13351: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13352:         unless ($liburi) {
13353: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13354:         }
13355: # this is the end of "was not already recently cached
13356:     }
13357:     return $metaentry{':'.$what};
13358: }
13359: 
13360: sub metadata_create_package_def {
13361:     my ($uri,$key,$package,$metathesekeys)=@_;
13362:     my ($pack,$name,$subp)=split(/\&/,$key);
13363:     if ($subp eq 'default') { next; }
13364:     
13365:     if (defined($metaentry{':packages'})) {
13366: 	$metaentry{':packages'}.=','.$package;
13367:     } else {
13368: 	$metaentry{':packages'}=$package;
13369:     }
13370:     my $value=$packagetab{$key};
13371:     my $unikey;
13372:     $unikey='parameter_0_'.$name;
13373:     $metaentry{':'.$unikey.'.part'}=0;
13374:     $$metathesekeys{$unikey}=1;
13375:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13376: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13377:     }
13378:     if (defined($metaentry{':'.$unikey.'.default'})) {
13379: 	$metaentry{':'.$unikey}=
13380: 	    $metaentry{':'.$unikey.'.default'};
13381:     }
13382: }
13383: 
13384: sub metadata_generate_part0 {
13385:     my ($metadata,$metacache,$uri) = @_;
13386:     my %allnames;
13387:     foreach my $metakey (keys(%$metadata)) {
13388: 	if ($metakey=~/^parameter\_(.*)/) {
13389: 	  my $part=$$metacache{':'.$metakey.'.part'};
13390: 	  my $name=$$metacache{':'.$metakey.'.name'};
13391: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13392: 	    $allnames{$name}=$part;
13393: 	  }
13394: 	}
13395:     }
13396:     foreach my $name (keys(%allnames)) {
13397:       $$metadata{"parameter_0_$name"}=1;
13398:       my $key=":parameter_0_$name";
13399:       $$metacache{"$key.part"}='0';
13400:       $$metacache{"$key.name"}=$name;
13401:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13402: 					   $allnames{$name}.'_'.$name.
13403: 					   '.type'};
13404:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13405: 			     '.display'};
13406:       my $expr='[Part: '.$allnames{$name}.']';
13407:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13408:       $$metacache{"$key.display"}=$olddis;
13409:     }
13410: }
13411: 
13412: # ------------------------------------------------------ Devalidate title cache
13413: 
13414: sub devalidate_title_cache {
13415:     my ($url)=@_;
13416:     if (!$env{'request.course.id'}) { return; }
13417:     my $symb=&symbread($url);
13418:     if (!$symb) { return; }
13419:     my $key=$env{'request.course.id'}."\0".$symb;
13420:     &devalidate_cache_new('title',$key);
13421: }
13422: 
13423: # ------------------------------------------------- Get the title of a course
13424: 
13425: sub current_course_title {
13426:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13427: }
13428: # ------------------------------------------------- Get the title of a resource
13429: 
13430: sub gettitle {
13431:     my $urlsymb=shift;
13432:     my $symb=&symbread($urlsymb);
13433:     if ($symb) {
13434: 	my $key=$env{'request.course.id'}."\0".$symb;
13435: 	my ($result,$cached)=&is_cached_new('title',$key);
13436: 	if (defined($cached)) { 
13437: 	    return $result;
13438: 	}
13439: 	my ($map,$resid,$url)=&decode_symb($symb);
13440: 	my $title='';
13441: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13442: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13443: 	} else {
13444: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13445: 		    &GDBM_READER(),0640)) {
13446: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13447: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13448: 		untie(%bighash);
13449: 	    }
13450: 	}
13451: 	$title=~s/\&colon\;/\:/gs;
13452: 	if ($title) {
13453: # Remember both $symb and $title for dynamic metadata
13454:             $accesshash{$symb.'___crstitle'}=$title;
13455:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13456: # Cache this title and then return it
13457: 	    return &do_cache_new('title',$key,$title,600);
13458: 	}
13459: 	$urlsymb=$url;
13460:     }
13461:     my $title=&metadata($urlsymb,'title');
13462:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13463:     return $title;
13464: }
13465: 
13466: sub get_slot {
13467:     my ($which,$cnum,$cdom)=@_;
13468:     if (!$cnum || !$cdom) {
13469: 	(undef,my $courseid)=&whichuser();
13470: 	$cdom=$env{'course.'.$courseid.'.domain'};
13471: 	$cnum=$env{'course.'.$courseid.'.num'};
13472:     }
13473:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13474:     my %slotinfo;
13475:     if (exists($remembered{$key})) {
13476: 	$slotinfo{$which} = $remembered{$key};
13477:     } else {
13478: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13479: 	&Apache::lonhomework::showhash(%slotinfo);
13480: 	my ($tmp)=keys(%slotinfo);
13481: 	if ($tmp=~/^error:/) { return (); }
13482: 	$remembered{$key} = $slotinfo{$which};
13483:     }
13484:     if (ref($slotinfo{$which}) eq 'HASH') {
13485: 	return %{$slotinfo{$which}};
13486:     }
13487:     return $slotinfo{$which};
13488: }
13489: 
13490: sub get_reservable_slots {
13491:     my ($cnum,$cdom,$uname,$udom) = @_;
13492:     my $now = time;
13493:     my $reservable_info;
13494:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13495:     if (exists($remembered{$key})) {
13496:         $reservable_info = $remembered{$key};
13497:     } else {
13498:         my %resv;
13499:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13500:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13501:         $reservable_info = \%resv;
13502:         $remembered{$key} = $reservable_info;
13503:     }
13504:     return $reservable_info;
13505: }
13506: 
13507: sub get_course_slots {
13508:     my ($cnum,$cdom) = @_;
13509:     my $hashid=$cnum.':'.$cdom;
13510:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13511:     if (defined($cached)) {
13512:         if (ref($result) eq 'HASH') {
13513:             return %{$result};
13514:         }
13515:     } else {
13516:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13517:         my ($tmp) = keys(%slots);
13518:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13519:             &do_cache_new('allslots',$hashid,\%slots,600);
13520:             return %slots;
13521:         }
13522:     }
13523:     return;
13524: }
13525: 
13526: sub devalidate_slots_cache {
13527:     my ($cnum,$cdom)=@_;
13528:     my $hashid=$cnum.':'.$cdom;
13529:     &devalidate_cache_new('allslots',$hashid);
13530: }
13531: 
13532: sub get_coursechange {
13533:     my ($cdom,$cnum) = @_;
13534:     if ($cdom eq '' || $cnum eq '') {
13535:         return unless ($env{'request.course.id'});
13536:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13537:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13538:     }
13539:     my $hashid=$cdom.'_'.$cnum;
13540:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13541:     if ((defined($cached)) && ($change ne '')) {
13542:         return $change;
13543:     } else {
13544:         my %crshash;
13545:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13546:         if ($crshash{'internal.contentchange'} eq '') {
13547:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13548:             if ($change eq '') {
13549:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13550:                 $change = $crshash{'internal.created'};
13551:             }
13552:         } else {
13553:             $change = $crshash{'internal.contentchange'};
13554:         }
13555:         my $cachetime = 600;
13556:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13557:     }
13558:     return $change;
13559: }
13560: 
13561: sub devalidate_coursechange_cache {
13562:     my ($cnum,$cdom)=@_;
13563:     my $hashid=$cnum.':'.$cdom;
13564:     &devalidate_cache_new('crschange',$hashid);
13565: }
13566: 
13567: # ------------------------------------------------- Update symbolic store links
13568: 
13569: sub symblist {
13570:     my ($mapname,%newhash)=@_;
13571:     $mapname=&deversion(&declutter($mapname));
13572:     my %hash;
13573:     if (($env{'request.course.fn'}) && (%newhash)) {
13574:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13575:                       &GDBM_WRCREAT(),0640)) {
13576: 	    foreach my $url (keys(%newhash)) {
13577: 		next if ($url eq 'last_known'
13578: 			 && $env{'form.no_update_last_known'});
13579: 		$hash{declutter($url)}=&encode_symb($mapname,
13580: 						    $newhash{$url}->[1],
13581: 						    $newhash{$url}->[0]);
13582:             }
13583:             if (untie(%hash)) {
13584: 		return 'ok';
13585:             }
13586:         }
13587:     }
13588:     return 'error';
13589: }
13590: 
13591: # --------------------------------------------------------------- Verify a symb
13592: 
13593: sub symbverify {
13594:     my ($symb,$thisurl,$encstate)=@_;
13595:     my $thisfn=$thisurl;
13596:     $thisfn=&declutter($thisfn);
13597: # direct jump to resource in page or to a sequence - will construct own symbs
13598:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13599: # check URL part
13600:     my ($map,$resid,$url)=&decode_symb($symb);
13601: 
13602:     unless ($url eq $thisfn) { return 0; }
13603: 
13604:     $symb=&symbclean($symb);
13605:     $thisurl=&deversion($thisurl);
13606:     $thisfn=&deversion($thisfn);
13607: 
13608:     my %bighash;
13609:     my $okay=0;
13610: 
13611:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13612:                             &GDBM_READER(),0640)) {
13613:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13614:             $thisurl =~ s/\?.+$//;
13615:             if ($map =~ m{^uploaded/.+\.page$}) {
13616:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13617:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13618:             }
13619:         }
13620:         my $ids;
13621:         if ($map =~ m{^uploaded/.+\.page$}) {
13622:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13623:         } else {
13624:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13625:         }
13626:         unless ($ids) {
13627:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13628:             $ids=$bighash{$idkey};
13629:         }
13630:         if ($ids) {
13631: # ------------------------------------------------------------------- Has ID(s)
13632:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13633:                 $symb =~ s/\?.+$//;
13634:             }
13635: 	    foreach my $id (split(/\,/,$ids)) {
13636: 	       my ($mapid,$resid)=split(/\./,$id);
13637:                if (
13638:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13639:    eq $symb) {
13640:                    if (ref($encstate)) {
13641:                        $$encstate = $bighash{'encrypted_'.$id};
13642:                    }
13643: 		   if (($env{'request.role.adv'}) ||
13644: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13645:                        ($thisurl eq '/adm/navmaps')) {
13646: 		       $okay=1;
13647:                        last;
13648: 		   }
13649: 	       }
13650: 	   }
13651:         }
13652: 	untie(%bighash);
13653:     }
13654:     return $okay;
13655: }
13656: 
13657: # --------------------------------------------------------------- Clean-up symb
13658: 
13659: sub symbclean {
13660:     my $symb=shift;
13661:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13662: # remove version from map
13663:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13664: 
13665: # remove version from URL
13666:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13667: 
13668: # remove wrapper
13669: 
13670:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13671:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13672:     return $symb;
13673: }
13674: 
13675: # ---------------------------------------------- Split symb to find map and url
13676: 
13677: sub encode_symb {
13678:     my ($map,$resid,$url)=@_;
13679:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13680: }
13681: 
13682: sub decode_symb {
13683:     my $symb=shift;
13684:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13685:     my ($map,$resid,$url)=split(/___/,$symb);
13686:     return (&fixversion($map),$resid,&fixversion($url));
13687: }
13688: 
13689: sub fixversion {
13690:     my $fn=shift;
13691:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13692:     my %bighash;
13693:     my $uri=&clutter($fn);
13694:     my $key=$env{'request.course.id'}.'_'.$uri;
13695: # is this cached?
13696:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13697:     if (defined($cached)) { return $result; }
13698: # unfortunately not cached, or expired
13699:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13700: 	    &GDBM_READER(),0640)) {
13701:  	if ($bighash{'version_'.$uri}) {
13702:  	    my $version=$bighash{'version_'.$uri};
13703:  	    unless (($version eq 'mostrecent') || 
13704: 		    ($version==&getversion($uri))) {
13705:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13706:  	    }
13707:  	}
13708:  	untie %bighash;
13709:     }
13710:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13711: }
13712: 
13713: sub deversion {
13714:     my $url=shift;
13715:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13716:     return $url;
13717: }
13718: 
13719: # ------------------------------------------------------ Return symb list entry
13720: 
13721: sub symbread {
13722:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13723:         $ignoresymbdb,$noenccheck)=@_;
13724:     my $cache_str='request.symbread.cached.'.$thisfn;
13725:     if (defined($env{$cache_str})) {
13726:         unless (ref($possibles) eq 'HASH') {
13727:             if ($ignorecachednull) {
13728:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13729:             } else {
13730:                 return $env{$cache_str};
13731:             }
13732:         }
13733:     }
13734: # no filename provided? try from environment
13735:     unless ($thisfn) {
13736:         if ($env{'request.symb'}) {
13737:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13738: 	}
13739: 	$thisfn=$env{'request.filename'};
13740:     }
13741:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13742: # is that filename actually a symb? Verify, clean, and return
13743:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13744: 	if (&symbverify($thisfn,$1)) {
13745: 	    return $env{$cache_str}=&symbclean($thisfn);
13746: 	}
13747:     }
13748:     $thisfn=declutter($thisfn);
13749:     my %hash;
13750:     my %bighash;
13751:     my $syval='';
13752:     if (($env{'request.course.fn'}) && ($thisfn)) {
13753:         unless ($ignoresymbdb) {
13754:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13755:                           &GDBM_READER(),0640)) {
13756: 	        $syval=$hash{$thisfn};
13757:                 untie(%hash);
13758:             }
13759:             if ($syval && $checkforblock) {
13760:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13761:                 if (@blockers) {
13762:                     $syval='';
13763:                 }
13764:             }
13765:         }
13766: # ---------------------------------------------------------- There was an entry
13767:         if ($syval) {
13768: 	    #unless ($syval=~/\_\d+$/) {
13769: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13770: 		    #&appenv({'request.ambiguous' => $thisfn});
13771: 		    #return $env{$cache_str}='';
13772: 		#}    
13773: 		#$syval.=$1;
13774: 	    #}
13775:         } else {
13776: # ------------------------------------------------------- Was not in symb table
13777:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13778:                             &GDBM_READER(),0640)) {
13779: # ---------------------------------------------- Get ID(s) for current resource
13780:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13781:               unless ($ids) { 
13782:                  $ids=$bighash{'ids_/'.$thisfn};
13783:               }
13784:               unless ($ids) {
13785: # alias?
13786: 		  $ids=$bighash{'mapalias_'.$thisfn};
13787:               }
13788:               if ($ids) {
13789: # ------------------------------------------------------------------- Has ID(s)
13790:                  my @possibilities=split(/\,/,$ids);
13791:                  if ($#possibilities==0) {
13792: # ----------------------------------------------- There is only one possibility
13793: 		     my ($mapid,$resid)=split(/\./,$ids);
13794: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13795: 						    $resid,$thisfn);
13796:                      if (ref($possibles) eq 'HASH') {
13797:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13798:                              $possibles->{$syval} = 1;
13799:                          }
13800:                      }
13801:                      if ($checkforblock) {
13802:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13803:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13804:                              if (@blockers) {
13805:                                  $syval = '';
13806:                                  untie(%bighash);
13807:                                  return $env{$cache_str}='';
13808:                              }
13809:                          }
13810:                      }
13811:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13812: # ------------------------------------------ There is more than one possibility
13813:                      my $realpossible=0;
13814:                      foreach my $id (@possibilities) {
13815: 			 my $file=$bighash{'src_'.$id};
13816:                          my $canaccess;
13817:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13818:                              $canaccess = 1;
13819:                          } else { 
13820:                              $canaccess = &allowed('bre',$file);
13821:                          }
13822:                          if ($canaccess) {
13823:          		     my ($mapid,$resid)=split(/\./,$id);
13824:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13825:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13826: 						             $resid,$thisfn);
13827:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13828:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13829:                                  if ($checkforblock) {
13830:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13831:                                      if (@blockers > 0) {
13832:                                          $syval = '';
13833:                                      } else {
13834:                                          $syval = $poss_syval;
13835:                                          $realpossible++;
13836:                                      }
13837:                                  } else {
13838:                                      $syval = $poss_syval;
13839:                                      $realpossible++;
13840:                                  }
13841:                                  if ($syval) {
13842:                                      if (ref($possibles) eq 'HASH') {
13843:                                          $possibles->{$syval} = 1;
13844:                                      }
13845:                                  }
13846:                              }
13847: 			 }
13848:                      }
13849: 		     if ($realpossible!=1) { $syval=''; }
13850:                  } else {
13851:                      $syval='';
13852:                  }
13853: 	      }
13854:               untie(%bighash);
13855:            }
13856:         }
13857:         if ($syval) {
13858: 	    return $env{$cache_str}=$syval;
13859:         }
13860:     }
13861:     &appenv({'request.ambiguous' => $thisfn});
13862:     return $env{$cache_str}='';
13863: }
13864: 
13865: # ---------------------------------------------------------- Return random seed
13866: 
13867: sub numval {
13868:     my $txt=shift;
13869:     $txt=~tr/A-J/0-9/;
13870:     $txt=~tr/a-j/0-9/;
13871:     $txt=~tr/K-T/0-9/;
13872:     $txt=~tr/k-t/0-9/;
13873:     $txt=~tr/U-Z/0-5/;
13874:     $txt=~tr/u-z/0-5/;
13875:     $txt=~s/\D//g;
13876:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13877:     return int($txt);
13878: }
13879: 
13880: sub numval2 {
13881:     my $txt=shift;
13882:     $txt=~tr/A-J/0-9/;
13883:     $txt=~tr/a-j/0-9/;
13884:     $txt=~tr/K-T/0-9/;
13885:     $txt=~tr/k-t/0-9/;
13886:     $txt=~tr/U-Z/0-5/;
13887:     $txt=~tr/u-z/0-5/;
13888:     $txt=~s/\D//g;
13889:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13890:     my $total;
13891:     foreach my $val (@txts) { $total+=$val; }
13892:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13893:     return int($total);
13894: }
13895: 
13896: sub numval3 {
13897:     use integer;
13898:     my $txt=shift;
13899:     $txt=~tr/A-J/0-9/;
13900:     $txt=~tr/a-j/0-9/;
13901:     $txt=~tr/K-T/0-9/;
13902:     $txt=~tr/k-t/0-9/;
13903:     $txt=~tr/U-Z/0-5/;
13904:     $txt=~tr/u-z/0-5/;
13905:     $txt=~s/\D//g;
13906:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13907:     my $total;
13908:     foreach my $val (@txts) { $total+=$val; }
13909:     if ($_64bit) { $total=(($total<<32)>>32); }
13910:     return $total;
13911: }
13912: 
13913: sub digest {
13914:     my ($data)=@_;
13915:     my $digest=&Digest::MD5::md5($data);
13916:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13917:     my ($e,$f);
13918:     {
13919:         use integer;
13920:         $e=($a+$b);
13921:         $f=($c+$d);
13922:         if ($_64bit) {
13923:             $e=(($e<<32)>>32);
13924:             $f=(($f<<32)>>32);
13925:         }
13926:     }
13927:     if (wantarray) {
13928: 	return ($e,$f);
13929:     } else {
13930: 	my $g;
13931: 	{
13932: 	    use integer;
13933: 	    $g=($e+$f);
13934: 	    if ($_64bit) {
13935: 		$g=(($g<<32)>>32);
13936: 	    }
13937: 	}
13938: 	return $g;
13939:     }
13940: }
13941: 
13942: sub latest_rnd_algorithm_id {
13943:     return '64bit5';
13944: }
13945: 
13946: sub get_rand_alg {
13947:     my ($courseid)=@_;
13948:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13949:     if ($courseid) {
13950: 	return $env{"course.$courseid.rndseed"};
13951:     }
13952:     return &latest_rnd_algorithm_id();
13953: }
13954: 
13955: sub validCODE {
13956:     my ($CODE)=@_;
13957:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13958:     return 0;
13959: }
13960: 
13961: sub getCODE {
13962:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13963:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13964: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13965: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13966: 	return $Apache::lonhomework::history{'resource.CODE'};
13967:     }
13968:     return undef;
13969: }
13970: #
13971: #  Determines the random seed for a specific context:
13972: #
13973: # parameters:
13974: #   symb      - in course context the symb for the seed.
13975: #   course_id - The course id of the form domain_coursenum.
13976: #   domain    - Domain for the user.
13977: #   course    - Course for the user.
13978: #   cenv      - environment of the course.
13979: #
13980: # NOTE:
13981: #   All parameters are picked out of the environment if missing
13982: #   or not defined.
13983: #   If a symb cannot be determined the current time is used instead.
13984: #
13985: #  For a given well defined symb, courside, domain, username,
13986: #  and course environment, the seed is reproducible.
13987: #
13988: sub rndseed {
13989:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13990:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13991:     if (!defined($symb)) {
13992: 	unless ($symb=$wsymb) { return time; }
13993:     }
13994:     if (!defined $courseid) { 
13995: 	$courseid=$wcourseid; 
13996:     }
13997:     if (!defined $domain) { $domain=$wdomain; }
13998:     if (!defined $username) { $username=$wusername }
13999: 
14000:     my $which;
14001:     if (defined($cenv->{'rndseed'})) {
14002: 	$which = $cenv->{'rndseed'};
14003:     } else {
14004: 	$which =&get_rand_alg($courseid);
14005:     }
14006:     if (defined(&getCODE())) {
14007: 
14008: 	if ($which eq '64bit5') {
14009: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14010: 	} elsif ($which eq '64bit4') {
14011: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14012: 	} else {
14013: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14014: 	}
14015:     } elsif ($which eq '64bit5') {
14016: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14017:     } elsif ($which eq '64bit4') {
14018: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14019:     } elsif ($which eq '64bit3') {
14020: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14021:     } elsif ($which eq '64bit2') {
14022: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14023:     } elsif ($which eq '64bit') {
14024: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14025:     }
14026:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14027: }
14028: 
14029: sub rndseed_32bit {
14030:     my ($symb,$courseid,$domain,$username)=@_;
14031:     {
14032: 	use integer;
14033: 	my $symbchck=unpack("%32C*",$symb) << 27;
14034: 	my $symbseed=numval($symb) << 22;
14035: 	my $namechck=unpack("%32C*",$username) << 17;
14036: 	my $nameseed=numval($username) << 12;
14037: 	my $domainseed=unpack("%32C*",$domain) << 7;
14038: 	my $courseseed=unpack("%32C*",$courseid);
14039: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14040: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14041: 	#&logthis("rndseed :$num:$symb");
14042: 	if ($_64bit) { $num=(($num<<32)>>32); }
14043: 	return $num;
14044:     }
14045: }
14046: 
14047: sub rndseed_64bit {
14048:     my ($symb,$courseid,$domain,$username)=@_;
14049:     {
14050: 	use integer;
14051: 	my $symbchck=unpack("%32S*",$symb) << 21;
14052: 	my $symbseed=numval($symb) << 10;
14053: 	my $namechck=unpack("%32S*",$username);
14054: 	
14055: 	my $nameseed=numval($username) << 21;
14056: 	my $domainseed=unpack("%32S*",$domain) << 10;
14057: 	my $courseseed=unpack("%32S*",$courseid);
14058: 	
14059: 	my $num1=$symbchck+$symbseed+$namechck;
14060: 	my $num2=$nameseed+$domainseed+$courseseed;
14061: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14062: 	#&logthis("rndseed :$num:$symb");
14063: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14064: 	return "$num1,$num2";
14065:     }
14066: }
14067: 
14068: sub rndseed_64bit2 {
14069:     my ($symb,$courseid,$domain,$username)=@_;
14070:     {
14071: 	use integer;
14072: 	# strings need to be an even # of cahracters long, it it is odd the
14073:         # last characters gets thrown away
14074: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14075: 	my $symbseed=numval($symb) << 10;
14076: 	my $namechck=unpack("%32S*",$username.' ');
14077: 	
14078: 	my $nameseed=numval($username) << 21;
14079: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14080: 	my $courseseed=unpack("%32S*",$courseid.' ');
14081: 	
14082: 	my $num1=$symbchck+$symbseed+$namechck;
14083: 	my $num2=$nameseed+$domainseed+$courseseed;
14084: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14085: 	#&logthis("rndseed :$num:$symb");
14086: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14087: 	return "$num1,$num2";
14088:     }
14089: }
14090: 
14091: sub rndseed_64bit3 {
14092:     my ($symb,$courseid,$domain,$username)=@_;
14093:     {
14094: 	use integer;
14095: 	# strings need to be an even # of cahracters long, it it is odd the
14096:         # last characters gets thrown away
14097: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14098: 	my $symbseed=numval2($symb) << 10;
14099: 	my $namechck=unpack("%32S*",$username.' ');
14100: 	
14101: 	my $nameseed=numval2($username) << 21;
14102: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14103: 	my $courseseed=unpack("%32S*",$courseid.' ');
14104: 	
14105: 	my $num1=$symbchck+$symbseed+$namechck;
14106: 	my $num2=$nameseed+$domainseed+$courseseed;
14107: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14108: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14109: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14110: 	
14111: 	return "$num1:$num2";
14112:     }
14113: }
14114: 
14115: sub rndseed_64bit4 {
14116:     my ($symb,$courseid,$domain,$username)=@_;
14117:     {
14118: 	use integer;
14119: 	# strings need to be an even # of cahracters long, it it is odd the
14120:         # last characters gets thrown away
14121: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14122: 	my $symbseed=numval3($symb) << 10;
14123: 	my $namechck=unpack("%32S*",$username.' ');
14124: 	
14125: 	my $nameseed=numval3($username) << 21;
14126: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14127: 	my $courseseed=unpack("%32S*",$courseid.' ');
14128: 	
14129: 	my $num1=$symbchck+$symbseed+$namechck;
14130: 	my $num2=$nameseed+$domainseed+$courseseed;
14131: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14132: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14133: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14134: 	
14135: 	return "$num1:$num2";
14136:     }
14137: }
14138: 
14139: sub rndseed_64bit5 {
14140:     my ($symb,$courseid,$domain,$username)=@_;
14141:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14142:     return "$num1:$num2";
14143: }
14144: 
14145: sub rndseed_CODE_64bit {
14146:     my ($symb,$courseid,$domain,$username)=@_;
14147:     {
14148: 	use integer;
14149: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14150: 	my $symbseed=numval2($symb);
14151: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14152: 	my $CODEseed=numval(&getCODE());
14153: 	my $courseseed=unpack("%32S*",$courseid.' ');
14154: 	my $num1=$symbseed+$CODEchck;
14155: 	my $num2=$CODEseed+$courseseed+$symbchck;
14156: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14157: 	#&logthis("rndseed :$num1:$num2:$symb");
14158: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14159: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14160: 	return "$num1:$num2";
14161:     }
14162: }
14163: 
14164: sub rndseed_CODE_64bit4 {
14165:     my ($symb,$courseid,$domain,$username)=@_;
14166:     {
14167: 	use integer;
14168: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14169: 	my $symbseed=numval3($symb);
14170: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14171: 	my $CODEseed=numval3(&getCODE());
14172: 	my $courseseed=unpack("%32S*",$courseid.' ');
14173: 	my $num1=$symbseed+$CODEchck;
14174: 	my $num2=$CODEseed+$courseseed+$symbchck;
14175: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14176: 	#&logthis("rndseed :$num1:$num2:$symb");
14177: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14178: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14179: 	return "$num1:$num2";
14180:     }
14181: }
14182: 
14183: sub rndseed_CODE_64bit5 {
14184:     my ($symb,$courseid,$domain,$username)=@_;
14185:     my $code = &getCODE();
14186:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14187:     return "$num1:$num2";
14188: }
14189: 
14190: sub setup_random_from_rndseed {
14191:     my ($rndseed)=@_;
14192:     if ($rndseed =~/([,:])/) {
14193:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14194:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14195:             &Math::Random::random_set_seed_from_phrase($rndseed);
14196:         } else {
14197:             &Math::Random::random_set_seed($num1,$num2);
14198:         }
14199:     } else {
14200: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14201:     }
14202: }
14203: 
14204: sub latest_receipt_algorithm_id {
14205:     return 'receipt3';
14206: }
14207: 
14208: sub recunique {
14209:     my $fucourseid=shift;
14210:     my $unique;
14211:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14212: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14213: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14214:     } else {
14215: 	$unique=$perlvar{'lonReceipt'};
14216:     }
14217:     return unpack("%32C*",$unique);
14218: }
14219: 
14220: sub recprefix {
14221:     my $fucourseid=shift;
14222:     my $prefix;
14223:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14224: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14225: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14226:     } else {
14227: 	$prefix=$perlvar{'lonHostID'};
14228:     }
14229:     return unpack("%32C*",$prefix);
14230: }
14231: 
14232: sub ireceipt {
14233:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14234: 
14235:     my $return =&recprefix($fucourseid).'-';
14236: 
14237:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14238: 	$env{'request.state'} eq 'construct') {
14239: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14240: 	return $return;
14241:     }
14242: 
14243:     my $cuname=unpack("%32C*",$funame);
14244:     my $cudom=unpack("%32C*",$fudom);
14245:     my $cucourseid=unpack("%32C*",$fucourseid);
14246:     my $cusymb=unpack("%32C*",$fusymb);
14247:     my $cunique=&recunique($fucourseid);
14248:     my $cpart=unpack("%32S*",$part);
14249:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14250: 
14251: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14252: 			       
14253: 	$return.= ($cunique%$cuname+
14254: 		   $cunique%$cudom+
14255: 		   $cusymb%$cuname+
14256: 		   $cusymb%$cudom+
14257: 		   $cucourseid%$cuname+
14258: 		   $cucourseid%$cudom+
14259: 		   $cpart%$cuname+
14260: 		   $cpart%$cudom);
14261:     } else {
14262: 	$return.= ($cunique%$cuname+
14263: 		   $cunique%$cudom+
14264: 		   $cusymb%$cuname+
14265: 		   $cusymb%$cudom+
14266: 		   $cucourseid%$cuname+
14267: 		   $cucourseid%$cudom);
14268:     }
14269:     return $return;
14270: }
14271: 
14272: sub receipt {
14273:     my ($part)=@_;
14274:     my ($symb,$courseid,$domain,$name) = &whichuser();
14275:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14276: }
14277: 
14278: sub whichuser {
14279:     my ($passedsymb)=@_;
14280:     my ($symb,$courseid,$domain,$name,$publicuser);
14281:     if (defined($env{'form.grade_symb'})) {
14282: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14283: 	my $allowed=&allowed('vgr',$tmp_courseid);
14284: 	if (!$allowed &&
14285: 	    exists($env{'request.course.sec'}) &&
14286: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14287: 	    $allowed=&allowed('vgr',$tmp_courseid.
14288: 			      '/'.$env{'request.course.sec'});
14289: 	}
14290: 	if ($allowed) {
14291: 	    ($symb)=&get_env_multiple('form.grade_symb');
14292: 	    $courseid=$tmp_courseid;
14293: 	    ($domain)=&get_env_multiple('form.grade_domain');
14294: 	    ($name)=&get_env_multiple('form.grade_username');
14295: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14296: 	}
14297:     }
14298:     if (!$passedsymb) {
14299: 	$symb=&symbread();
14300:     } else {
14301: 	$symb=$passedsymb;
14302:     }
14303:     $courseid=$env{'request.course.id'};
14304:     $domain=$env{'user.domain'};
14305:     $name=$env{'user.name'};
14306:     if ($name eq 'public' && $domain eq 'public') {
14307: 	if (!defined($env{'form.username'})) {
14308: 	    $env{'form.username'}.=time.rand(10000000);
14309: 	}
14310: 	$name.=$env{'form.username'};
14311:     }
14312:     return ($symb,$courseid,$domain,$name,$publicuser);
14313: 
14314: }
14315: 
14316: # ------------------------------------------------------------ Serves up a file
14317: # returns either the contents of the file or 
14318: # -1 if the file doesn't exist
14319: #
14320: # if the target is a file that was uploaded via DOCS, 
14321: # a check will be made to see if a current copy exists on the local server,
14322: # if it does this will be served, otherwise a copy will be retrieved from
14323: # the home server for the course and stored in /home/httpd/html/userfiles on
14324: # the local server.   
14325: 
14326: sub getfile {
14327:     my ($file) = @_;
14328:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14329:     &repcopy($file);
14330:     return &readfile($file);
14331: }
14332: 
14333: sub repcopy_userfile {
14334:     my ($file)=@_;
14335:     my $londocroot = $perlvar{'lonDocRoot'};
14336:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14337:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14338:     my ($cdom,$cnum,$filename) = 
14339: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14340:     my $uri="/uploaded/$cdom/$cnum/$filename";
14341:     if (-e "$file") {
14342: # we already have a local copy, check it out
14343: 	my @fileinfo = stat($file);
14344: 	my $rtncode;
14345: 	my $info;
14346: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14347: 	if ($lwpresp ne 'ok') {
14348: # there is no such file anymore, even though we had a local copy
14349: 	    if ($rtncode eq '404') {
14350: 		unlink($file);
14351: 	    }
14352: 	    return -1;
14353: 	}
14354: 	if ($info < $fileinfo[9]) {
14355: # nice, the file we have is up-to-date, just say okay
14356: 	    return 'ok';
14357: 	} else {
14358: # the file is outdated, get rid of it
14359: 	    unlink($file);
14360: 	}
14361:     }
14362: # one way or the other, at this point, we don't have the file
14363: # construct the correct path for the file
14364:     my @parts = ($cdom,$cnum); 
14365:     if ($filename =~ m|^(.+)/[^/]+$|) {
14366: 	push @parts, split(/\//,$1);
14367:     }
14368:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14369:     foreach my $part (@parts) {
14370: 	$path .= '/'.$part;
14371: 	if (!-e $path) {
14372: 	    mkdir($path,0770);
14373: 	}
14374:     }
14375: # now the path exists for sure
14376: # get a user agent
14377:     my $transferfile=$file.'.in.transfer';
14378: # FIXME: this should flock
14379:     if (-e $transferfile) { return 'ok'; }
14380:     my $request;
14381:     $uri=~s/^\///;
14382:     my $homeserver = &homeserver($cnum,$cdom);
14383:     my $hostname = &hostname($homeserver);
14384:     my $protocol = $protocol{$homeserver};
14385:     $protocol = 'http' if ($protocol ne 'https');
14386:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14387:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14388: # did it work?
14389:     if ($response->is_error()) {
14390: 	unlink($transferfile);
14391: 	&logthis("Userfile repcopy failed for $uri");
14392: 	return -1;
14393:     }
14394: # worked, rename the transfer file
14395:     rename($transferfile,$file);
14396:     return 'ok';
14397: }
14398: 
14399: sub tokenwrapper {
14400:     my $uri=shift;
14401:     $uri=~s|^https?\://([^/]+)||;
14402:     $uri=~s|^/||;
14403:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14404:     my $token=$1;
14405:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14406:     if ($udom && $uname && $file) {
14407: 	$file=~s|(\?\.*)*$||;
14408:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14409:         my $homeserver = &homeserver($uname,$udom);
14410:         my $hostname = &hostname($homeserver);
14411:         my $protocol = $protocol{$homeserver};
14412:         $protocol = 'http' if ($protocol ne 'https');
14413:         return $protocol.'://'.$hostname.'/'.$uri.
14414:                (($uri=~/\?/)?'&':'?').'token='.$token.
14415:                                '&tokenissued='.$perlvar{'lonHostID'};
14416:     } else {
14417:         return '/adm/notfound.html';
14418:     }
14419: }
14420: 
14421: # call with reqtype HEAD: get last modification time
14422: # call with reqtype GET: get the file contents
14423: # Do not call this with reqtype GET for large files! It loads everything into memory
14424: #
14425: sub getuploaded {
14426:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14427:     $uri=~s/^\///;
14428:     my $homeserver = &homeserver($cnum,$cdom);
14429:     my $hostname = &hostname($homeserver);
14430:     my $protocol = $protocol{$homeserver};
14431:     $protocol = 'http' if ($protocol ne 'https');
14432:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14433:     my $request=new HTTP::Request($reqtype,$uri);
14434:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14435:     $$rtncode = $response->code;
14436:     if (! $response->is_success()) {
14437: 	return 'failed';
14438:     }      
14439:     if ($reqtype eq 'HEAD') {
14440: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14441:     } elsif ($reqtype eq 'GET') {
14442: 	$$info = $response->content;
14443:     }
14444:     return 'ok';
14445: }
14446: 
14447: sub readfile {
14448:     my $file = shift;
14449:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14450:     my $fh;
14451:     open($fh,"<",$file);
14452:     my $a='';
14453:     while (my $line = <$fh>) { $a .= $line; }
14454:     return $a;
14455: }
14456: 
14457: sub filelocation {
14458:     my ($dir,$file) = @_;
14459:     my $location;
14460:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14461: 
14462:     if ($file =~ m-^/adm/-) {
14463: 	$file=~s-^/adm/wrapper/-/-;
14464: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14465:     }
14466: 
14467:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14468:         $location = $file;
14469:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14470:         my ($udom,$uname,$filename)=
14471:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14472:         my $home=&homeserver($uname,$udom);
14473:         my $is_me=0;
14474:         my @ids=&current_machine_ids();
14475:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14476:         if ($is_me) {
14477:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14478:         } else {
14479:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14480:   	      $udom.'/'.$uname.'/'.$filename;
14481:         }
14482:     } elsif ($file =~ m-^/adm/-) {
14483: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14484:     } else {
14485:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14486:         $file=~s:^/(res|priv)/:/:;
14487:         my $space=$1;
14488:         if ( !( $file =~ m:^/:) ) {
14489:             $location = $dir. '/'.$file;
14490:         } else {
14491:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14492:         }
14493:     }
14494:     $location=~s://+:/:g; # remove duplicate /
14495:     while ($location=~m{/\.\./}) {
14496: 	if ($location =~ m{/[^/]+/\.\./}) {
14497: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14498: 	} else {
14499: 	    $location=~ s{/\.\./}{/}g;
14500: 	}
14501:     } #remove dir/..
14502:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14503:     return $location;
14504: }
14505: 
14506: sub hreflocation {
14507:     my ($dir,$file)=@_;
14508:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14509: 	$file=filelocation($dir,$file);
14510:     } elsif ($file=~m-^/adm/-) {
14511: 	$file=~s-^/adm/wrapper/-/-;
14512: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14513:     }
14514:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14515: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14516:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14517: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14518: 	        {/uploaded/$1/$2/}x;
14519:     }
14520:     if ($file=~ m{^/userfiles/}) {
14521: 	$file =~ s{^/userfiles/}{/uploaded/};
14522:     }
14523:     return $file;
14524: }
14525: 
14526: 
14527: 
14528: 
14529: 
14530: sub current_machine_domains {
14531:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14532: }
14533: 
14534: sub machine_domains {
14535:     my ($hostname) = @_;
14536:     my @domains;
14537:     my %hostname = &all_hostnames();
14538:     while( my($id, $name) = each(%hostname)) {
14539: #	&logthis("-$id-$name-$hostname-");
14540: 	if ($hostname eq $name) {
14541: 	    push(@domains,&host_domain($id));
14542: 	}
14543:     }
14544:     return @domains;
14545: }
14546: 
14547: sub current_machine_ids {
14548:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14549: }
14550: 
14551: sub machine_ids {
14552:     my ($hostname) = @_;
14553:     $hostname ||= &hostname($perlvar{'lonHostID'});
14554:     my @ids;
14555:     my %name_to_host = &all_names();
14556:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14557: 	return @{ $name_to_host{$hostname} };
14558:     }
14559:     return;
14560: }
14561: 
14562: sub additional_machine_domains {
14563:     my @domains;
14564:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14565:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14566:             while (my $line = <$fh>) {
14567:                 chomp($line);           
14568:                 $line =~ s/\s//g;
14569:                 push(@domains,$line);
14570:             }
14571:             close($fh);
14572:         }
14573:     }
14574:     return @domains;
14575: }
14576: 
14577: sub default_login_domain {
14578:     my $domain = $perlvar{'lonDefDomain'};
14579:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14580:     foreach my $posdom (&current_machine_domains(),
14581:                         &additional_machine_domains()) {
14582:         if (lc($posdom) eq lc($testdomain)) {
14583:             $domain=$posdom;
14584:             last;
14585:         }
14586:     }
14587:     return $domain;
14588: }
14589: 
14590: sub shared_institution {
14591:     my ($dom,$lonhost) = @_;
14592:     if ($lonhost eq '') {
14593:         $lonhost = $perlvar{'lonHostID'};
14594:     }
14595:     my $same_intdom;
14596:     my $hostintdom = &internet_dom($lonhost);
14597:     if ($hostintdom ne '') {
14598:         my %iphost = &get_iphost();
14599:         my $primary_id = &domain($dom,'primary');
14600:         my $primary_ip = &get_host_ip($primary_id);
14601:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14602:             foreach my $id (@{$iphost{$primary_ip}}) {
14603:                 my $intdom = &internet_dom($id);
14604:                 if ($intdom eq $hostintdom) {
14605:                     $same_intdom = 1;
14606:                     last;
14607:                 }
14608:             }
14609:         }
14610:     }
14611:     return $same_intdom;
14612: }
14613: 
14614: sub uses_sts {
14615:     my ($ignore_cache) = @_;
14616:     my $lonhost = $perlvar{'lonHostID'};
14617:     my $hostname = &hostname($lonhost);
14618:     my $sts_on;
14619:     if ($protocol{$lonhost} eq 'https') {
14620:         my $cachetime = 12*3600;
14621:         if (!$ignore_cache) {
14622:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14623:             if (defined($cached)) {
14624:                 return $sts_on;
14625:             }
14626:         }
14627:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14628:         my $request=new HTTP::Request('HEAD',$url);
14629:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14630:         if ($response->is_success) {
14631:             my $has_sts = $response->header('Strict-Transport-Security');
14632:             if ($has_sts eq '') {
14633:                 $sts_on = 0;
14634:             } else {
14635:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14636:                     my $maxage = $1;
14637:                     if ($maxage) {
14638:                         $sts_on = 1;
14639:                     } else {
14640:                         $sts_on = 0;
14641:                     }
14642:                 } else {
14643:                     $sts_on = 0;
14644:                 }
14645:             }
14646:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14647:         }
14648:     }
14649:     return;
14650: }
14651: 
14652: sub waf_allssl {
14653:     my ($host_name) = @_;
14654:     my $alias = &get_proxy_alias();
14655:     if ($host_name eq '') {
14656:         $host_name = $ENV{'SERVER_NAME'};
14657:     }
14658:     if (($host_name ne '') && ($alias eq $host_name)) {
14659:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14660:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14661:         if ($defdomdefaults{'waf_sslopt'}) {
14662:             return $defdomdefaults{'waf_sslopt'};
14663:         }
14664:     }
14665:     return;
14666: }
14667: 
14668: sub get_requestor_ip {
14669:     my ($r,$nolookup,$noproxy) = @_;
14670:     my $from_ip;
14671:     if (ref($r)) {
14672:         if ($r->can('useragent_ip')) {
14673:             if ($noproxy && $r->can('client_ip')) {
14674:                 $from_ip = $r->client_ip();
14675:             } else {
14676:                 $from_ip = $r->useragent_ip();
14677:             }
14678:         } elsif ($r->connection->can('remote_ip')) {
14679:             $from_ip = $r->connection->remote_ip();
14680:         } else {
14681:             $from_ip = $r->get_remote_host($nolookup);
14682:         }
14683:     } else {
14684:         $from_ip = $ENV{'REMOTE_ADDR'};
14685:     }
14686:     return $from_ip if ($noproxy); 
14687:     # Who controls proxy settings for server
14688:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14689:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14690:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14691:         if ($proxyinfo->{'vpnint'}) {
14692:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14693:                 return $from_ip;
14694:             }
14695:         }
14696:         if ($proxyinfo->{'trusted'}) {
14697:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14698:                 my $ipheader = $proxyinfo->{'ipheader'};
14699:                 my ($ip,$xfor);
14700:                 if (ref($r)) {
14701:                     if ($ipheader) {
14702:                         $ip = $r->headers_in->{$ipheader};
14703:                     }
14704:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14705:                 } else {
14706:                     if ($ipheader) {
14707:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14708:                     }
14709:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14710:                 }
14711:                 if (($ip eq '') && ($xfor ne '')) {
14712:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14713:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14714:                             $ip = $poss_ip;
14715:                             last;
14716:                         }
14717:                     }
14718:                 }
14719:                 if ($ip ne '') {
14720:                     return $ip;
14721:                 }
14722:             }
14723:         }
14724:     }
14725:     return $from_ip;
14726: }
14727: 
14728: sub get_proxy_settings {
14729:     my ($dom_in_use) = @_;
14730:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14731:     my $proxyinfo = {
14732:                        ipheader => $domdefaults{'waf_ipheader'},
14733:                        trusted  => $domdefaults{'waf_trusted'},
14734:                        vpnint   => $domdefaults{'waf_vpnint'},
14735:                        vpnext   => $domdefaults{'waf_vpnext'},
14736:                        sslopt   => $domdefaults{'waf_sslopt'},
14737:                     };
14738:     return $proxyinfo;
14739: }
14740: 
14741: sub ip_match {
14742:     my ($ip,$pattern_str) = @_;
14743:     $ip=Net::CIDR::cidrvalidate($ip);
14744:     if ($ip) {
14745:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14746:     }
14747:     return;
14748: }
14749: 
14750: sub get_proxy_alias {
14751:     my ($lonid) = @_;
14752:     if ($lonid eq '') {
14753:         $lonid = $perlvar{'lonHostID'};
14754:     }
14755:     if (!defined(&hostname($lonid))) {
14756:         return;
14757:     }
14758:     if ($lonid ne '') {
14759:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14760:         if ($cached) {
14761:             return $alias;
14762:         }
14763:         my $dom = &Apache::lonnet::host_domain($lonid);
14764:         if ($dom ne '') {
14765:             my $cachetime = 60*60*24;
14766:             my %domconfig =
14767:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14768:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14769:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14770:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14771:                 }
14772:             }
14773:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14774:         }
14775:     }
14776:     return;
14777: }
14778: 
14779: sub use_proxy_alias {
14780:     my ($r,$lonid) = @_;
14781:     my $alias = &get_proxy_alias($lonid);
14782:     if ($alias) {
14783:         my $dom = &host_domain($lonid);
14784:         if ($dom ne '') {
14785:             my $proxyinfo = &get_proxy_settings($dom);
14786:             my ($vpnint,$remote_ip);
14787:             if (ref($proxyinfo) eq 'HASH') {
14788:                 $vpnint = $proxyinfo->{'vpnint'};
14789:                 if ($vpnint) {
14790:                     $remote_ip = &get_requestor_ip($r,1,1);
14791:                 }
14792:             }
14793:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14794:                 return $alias;
14795:             }
14796:         }
14797:     }
14798:     return;
14799: }
14800: 
14801: sub alias_sso {
14802:     my ($lonid) = @_;
14803:     if ($lonid eq '') {
14804:         $lonid = $perlvar{'lonHostID'};
14805:     }
14806:     if (!defined(&hostname($lonid))) {
14807:         return;
14808:     }
14809:     if ($lonid ne '') {
14810:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14811:         if ($cached) {
14812:             return $use_alias;
14813:         }
14814:         my $dom = &Apache::lonnet::host_domain($lonid);
14815:         if ($dom ne '') {
14816:             my $cachetime = 60*60*24;
14817:             my %domconfig =
14818:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14819:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14820:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14821:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14822:                 }
14823:             }
14824:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14825:         }
14826:     }
14827:     return;
14828: }
14829: 
14830: sub get_saml_landing {
14831:     my ($lonid) = @_;
14832:     if ($lonid eq '') {
14833:         my $defdom = &default_login_domain();
14834:         my @hosts = &current_machine_ids();
14835:         if (@hosts > 1) {
14836:             foreach my $hostid (@hosts) {
14837:                 if (&host_domain($hostid) eq $defdom) {
14838:                     $lonid = $hostid;
14839:                     last;
14840:                 }
14841:             }
14842:         } else {
14843:             $lonid = $perlvar{'lonHostID'};
14844:         }
14845:         if ($lonid) {
14846:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14847:                 return;
14848:             }
14849:         } else {
14850:             return;
14851:         }
14852:     } elsif (!defined(&hostname($lonid))) {
14853:         return;
14854:     }
14855:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14856:     if ($cached) {
14857:         return $landing;
14858:     }
14859:     my $dom = &Apache::lonnet::host_domain($lonid);
14860:     if ($dom ne '') {
14861:         my $cachetime = 60*60*24;
14862:         my %domconfig =
14863:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
14864:         if (ref($domconfig{'login'}) eq 'HASH') {
14865:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14866:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14867:                     $landing = 1;
14868:                 }
14869:             }
14870:         }
14871:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14872:     }
14873:     return;
14874: }
14875: 
14876: # ------------------------------------------------------------- Declutters URLs
14877: 
14878: sub declutter {
14879:     my $thisfn=shift;
14880:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14881:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14882:         $thisfn=~s{^/home/httpd/html}{};
14883:     }
14884:     $thisfn=~s/^\///;
14885:     $thisfn=~s|^adm/wrapper/||;
14886:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14887:     $thisfn=~s/^res\///;
14888:     $thisfn=~s/^priv\///;
14889:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14890:         $thisfn=~s/\?.+$//;
14891:     }
14892:     return $thisfn;
14893: }
14894: 
14895: # ------------------------------------------------------------- Clutter up URLs
14896: 
14897: sub clutter {
14898:     my $thisfn='/'.&declutter(shift);
14899:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14900: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14901:        $thisfn='/res'.$thisfn; 
14902:     }
14903:     if ($thisfn !~m|^/adm|) {
14904: 	if ($thisfn =~ m|^/ext/|) {
14905: 	    $thisfn='/adm/wrapper'.$thisfn;
14906: 	} else {
14907: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14908: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14909: 	    if ($embstyle eq 'ssi'
14910: 		|| ($embstyle eq 'hdn')
14911: 		|| ($embstyle eq 'rat')
14912: 		|| ($embstyle eq 'prv')
14913: 		|| ($embstyle eq 'ign')) {
14914: 		#do nothing with these
14915: 	    } elsif (($embstyle eq 'img') 
14916: 		|| ($embstyle eq 'emb')
14917: 		|| ($embstyle eq 'wrp')) {
14918: 		$thisfn='/adm/wrapper'.$thisfn;
14919: 	    } elsif ($embstyle eq 'unk'
14920: 		     && $thisfn!~/\.(sequence|page)$/) {
14921: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14922: 	    } else {
14923: #		&logthis("Got a blank emb style");
14924: 	    }
14925: 	}
14926:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14927:         $thisfn='/adm/wrapper'.$thisfn;
14928:     }
14929:     return $thisfn;
14930: }
14931: 
14932: sub clutter_with_no_wrapper {
14933:     my $uri = &clutter(shift);
14934:     if ($uri =~ m-^/adm/-) {
14935: 	$uri =~ s-^/adm/wrapper/-/-;
14936: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14937:     }
14938:     return $uri;
14939: }
14940: 
14941: sub freeze_escape {
14942:     my ($value)=@_;
14943:     if (ref($value)) {
14944: 	$value=&nfreeze($value);
14945: 	return '__FROZEN__'.&escape($value);
14946:     }
14947:     return &escape($value);
14948: }
14949: 
14950: 
14951: sub thaw_unescape {
14952:     my ($value)=@_;
14953:     if ($value =~ /^__FROZEN__/) {
14954: 	substr($value,0,10,undef);
14955: 	$value=&unescape($value);
14956: 	return &thaw($value);
14957:     }
14958:     return &unescape($value);
14959: }
14960: 
14961: sub correct_line_ends {
14962:     my ($result)=@_;
14963:     $$result =~s/\r\n/\n/mg;
14964:     $$result =~s/\r/\n/mg;
14965: }
14966: # ================================================================ Main Program
14967: 
14968: sub goodbye {
14969:    &logthis("Starting Shut down");
14970: #not converted to using infrastruture and probably shouldn't be
14971:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14972: #converted
14973: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14974:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14975: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14976: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14977: #1.1 only
14978: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14979: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14980: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14981: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14982:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14983:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14984:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14985:    &flushcourselogs();
14986:    &logthis("Shutting down");
14987: }
14988: 
14989: sub get_dns {
14990:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14991:     if (!$ignore_cache) {
14992: 	my ($content,$cached)=
14993: 	    &Apache::lonnet::is_cached_new('dns',$url);
14994: 	if ($cached) {
14995: 	    &$func($content,$hashref);
14996: 	    return;
14997: 	}
14998:     }
14999: 
15000:     my %alldns;
15001:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15002:         foreach my $dns (<$config>) {
15003: 	    next if ($dns !~ /^\^(\S*)/x);
15004:             my $line = $1;
15005:             my ($host,$protocol) = split(/:/,$line);
15006:             if ($protocol ne 'https') {
15007:                 $protocol = 'http';
15008:             }
15009: 	    $alldns{$host} = $protocol;
15010:         }
15011:         close($config);
15012:     }
15013:     while (%alldns) {
15014: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15015:         my ($contents,@content);
15016:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15017:             my $command = (split('/',$url))[3];
15018:             my ($dir,$file) = &parse_getdns_url($command,$url);
15019:             delete($alldns{$dns});
15020:             next if (($dir eq '') || ($file eq ''));
15021:             if (open(my $config,'<',"$dir/$file")) {
15022:                 @content = <$config>;
15023:                 close($config);
15024:             }
15025:             if ($url eq '/adm/dns/loncapaCRL') {
15026:                 $contents = join('',@content);
15027:             }
15028:         } else {
15029: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15030:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15031:             delete($alldns{$dns});
15032: 	    next if ($response->is_error());
15033:             if ($url eq '/adm/dns/loncapaCRL') {
15034:                 $contents = $response->content;
15035:             } else {
15036:                 @content = split("\n",$response->content);
15037:             }
15038:         }
15039:         if ($url eq '/adm/dns/loncapaCRL') {
15040:             return &$func($contents);
15041:         } else {
15042: 	    unless ($nocache) {
15043: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15044: 	    }
15045: 	    &$func(\@content,$hashref);
15046:             return;
15047:         }
15048:     }
15049:     my $which = (split('/',$url,4))[3];
15050:     if ($which eq 'loncapaCRL') {
15051:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15052:         if (-e $diskfile) {
15053:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15054:         } else {
15055:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15056:         }
15057:     } else {
15058:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15059:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15060:             my @content = <$config>;
15061:             close($config);
15062:             &$func(\@content,$hashref);
15063:         }
15064:     }
15065:     return;
15066: }
15067: 
15068: # ------------------------------------------------------Get DNS checksums file
15069: sub parse_dns_checksums_tab {
15070:     my ($lines,$hashref) = @_;
15071:     my $lonhost = $perlvar{'lonHostID'};
15072:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
15073:     my $loncaparev = &get_server_loncaparev($machine_dom);
15074:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15075:     my $webconfdir = '/etc/httpd/conf';
15076:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15077:         $webconfdir = '/etc/apache2';
15078:     } elsif ($distro =~ /^sles(\d+)$/) {
15079:         if ($1 >= 10) {
15080:             $webconfdir = '/etc/apache2';
15081:         }
15082:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15083:         if ($1 >= 10.0) {
15084:             $webconfdir = '/etc/apache2';
15085:         }
15086:     }
15087:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15088:     my (%chksum,%revnum);
15089:     if (ref($lines) eq 'ARRAY') {
15090:         chomp(@{$lines});
15091:         my $version = shift(@{$lines});
15092:         if ($version eq $release) {  
15093:             foreach my $line (@{$lines}) {
15094:                 my ($file,$version,$shasum) = split(/,/,$line);
15095:                 if ($file =~ m{^/etc/httpd/conf}) {
15096:                     if ($webconfdir eq '/etc/apache2') {
15097:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15098:                     }
15099:                 }
15100:                 $chksum{$file} = $shasum;
15101:                 $revnum{$file} = $version;
15102:             }
15103:             if (ref($hashref) eq 'HASH') {
15104:                 %{$hashref} = (
15105:                                 sums     => \%chksum,
15106:                                 versions => \%revnum,
15107:                               );
15108:             }
15109:         }
15110:     }
15111:     return;
15112: }
15113: 
15114: sub fetch_dns_checksums {
15115:     my %checksums;
15116:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
15117:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15118:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15119:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15120:              \%checksums);
15121:     return \%checksums;
15122: }
15123: 
15124: sub fetch_crl_pemfile {
15125:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15126: }
15127: 
15128: sub save_crl_pem {
15129:     my ($content) = @_;
15130:     my ($msg,$hadchanges);
15131:     if ($content ne '') {
15132:         my $now = time;
15133:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15134:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15135:         if (open(my $fh,'>',"$tmpcrl")) {
15136:             print $fh $content;
15137:             close($fh);
15138:             if (-e $lonca) {
15139:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15140:                     my $check = <PIPE>;
15141:                     close(PIPE);
15142:                     chomp($check);
15143:                     if ($check eq 'verify OK') {
15144:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15145:                         my $backup;
15146:                         if (-e $dest) {
15147:                             if (&File::Copy::move($dest,"$dest.bak")) {
15148:                                 $backup = 'ok';
15149:                             }
15150:                         }
15151:                         if (&File::Copy::move($tmpcrl,$dest)) {
15152:                             $msg = 'ok';
15153:                             if ($backup) {
15154:                                 my (%oldnums,%newnums);
15155:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15156:                                     while (<PIPE>) {
15157:                                         $oldnums{(split(/:/))[1]} = 1;
15158:                                     }
15159:                                     close(PIPE);
15160:                                 }
15161:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15162:                                     while(<PIPE>) {
15163:                                         $newnums{(split(/:/))[1]} = 1;
15164:                                     }
15165:                                     close(PIPE);
15166:                                 }
15167:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15168:                                     unless (exists($oldnums{$key})) {
15169:                                         $hadchanges = 1;
15170:                                         last;
15171:                                     }
15172:                                 }
15173:                                 unless ($hadchanges) {
15174:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15175:                                         unless (exists($newnums{$key})) {
15176:                                             $hadchanges = 1;
15177:                                             last;
15178:                                         }
15179:                                     }
15180:                                 }
15181:                             }
15182:                         }
15183:                     } else {
15184:                         unlink($tmpcrl);
15185:                     }
15186:                 } else {
15187:                     unlink($tmpcrl);
15188:                 }
15189:             } else {
15190:                 unlink($tmpcrl);
15191:             }
15192:         }
15193:     }
15194:     return ($msg,$hadchanges);
15195: }
15196: 
15197: sub parse_getdns_url {
15198:     my ($command,$url) = @_;
15199:     my $dir = $perlvar{'lonTabDir'};
15200:     my $file;
15201:     if ($command eq 'hosts') {
15202:         $file = 'dns_hosts.tab';
15203:     } elsif ($command eq 'domain') {
15204:         $file = 'dns_domain.tab';
15205:     } elsif ($command eq 'checksums') {
15206:         my $version = (split('/',$url))[4];
15207:         $file = "dns_checksums/$version.tab",
15208:     } elsif ($command eq 'loncapaCRL') {
15209:         $dir = $perlvar{'lonCertificateDirectory'};
15210:         $file = $perlvar{'lonnetCertRevocationList'};
15211:     }
15212:     return ($dir,$file);
15213: }
15214: 
15215: # ------------------------------------------------------------ Read domain file
15216: {
15217:     my $loaded;
15218:     my %domain;
15219: 
15220:     sub parse_domain_tab {
15221: 	my ($lines) = @_;
15222: 	foreach my $line (@$lines) {
15223: 	    next if ($line =~ /^(\#|\s*$ )/x);
15224: 
15225: 	    chomp($line);
15226: 	    my ($name,@elements) = split(/:/,$line,9);
15227: 	    my %this_domain;
15228: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15229: 			       'lang_def', 'city', 'longi', 'lati',
15230: 			       'primary') {
15231: 		$this_domain{$field} = shift(@elements);
15232: 	    }
15233: 	    $domain{$name} = \%this_domain;
15234: 	}
15235:     }
15236: 
15237:     sub reset_domain_info {
15238: 	undef($loaded);
15239: 	undef(%domain);
15240:     }
15241: 
15242:     sub load_domain_tab {
15243: 	my ($ignore_cache,$nocache) = @_;
15244: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15245: 	my $fh;
15246: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15247: 	    my @lines = <$fh>;
15248: 	    &parse_domain_tab(\@lines);
15249: 	}
15250: 	close($fh);
15251: 	$loaded = 1;
15252:     }
15253: 
15254:     sub domain {
15255: 	&load_domain_tab() if (!$loaded);
15256: 
15257: 	my ($name,$what) = @_;
15258: 	return if ( !exists($domain{$name}) );
15259: 
15260: 	if (!$what) {
15261: 	    return $domain{$name}{'description'};
15262: 	}
15263: 	return $domain{$name}{$what};
15264:     }
15265: 
15266:     sub domain_info {
15267:         &load_domain_tab() if (!$loaded);
15268:         return %domain;
15269:     }
15270: 
15271: }
15272: 
15273: 
15274: # ------------------------------------------------------------- Read hosts file
15275: {
15276:     my %hostname;
15277:     my %hostdom;
15278:     my %libserv;
15279:     my $loaded;
15280:     my %name_to_host;
15281:     my %internetdom;
15282:     my %LC_dns_serv;
15283: 
15284:     sub parse_hosts_tab {
15285: 	my ($file) = @_;
15286: 	foreach my $configline (@$file) {
15287: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15288:             chomp($configline);
15289: 	    if ($configline =~ /^\^/) {
15290:                 if ($configline =~ /^\^([\w.\-]+)/) {
15291:                     $LC_dns_serv{$1} = 1;
15292:                 }
15293:                 next;
15294:             }
15295: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15296: 	    $name=~s/\s//g;
15297: 	    if ($id && $domain && $role && $name) {
15298:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15299:                     my $curr = $hostname{$id};
15300:                     my $skip;
15301:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15302:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15303:                             $skip = 1;
15304:                         } else {
15305:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15306:                         }
15307:                     }
15308:                     unless ($skip) {
15309:                         push(@{$name_to_host{$name}},$id);
15310:                     }
15311:                 } else {
15312:                     push(@{$name_to_host{$name}},$id);
15313:                 }
15314: 		$hostname{$id}=$name;
15315: 		$hostdom{$id}=$domain;
15316: 		if ($role eq 'library') { $libserv{$id}=$name; }
15317:                 if (defined($protocol)) {
15318:                     if ($protocol eq 'https') {
15319:                         $protocol{$id} = $protocol;
15320:                     } else {
15321:                         $protocol{$id} = 'http'; 
15322:                     }
15323:                 } else {
15324:                     $protocol{$id} = 'http';
15325:                 }
15326:                 if (defined($intdom)) {
15327:                     $internetdom{$id} = $intdom;
15328:                 }
15329: 	    }
15330: 	}
15331:     }
15332:     
15333:     sub reset_hosts_info {
15334: 	&purge_remembered();
15335: 	&reset_domain_info();
15336: 	&reset_hosts_ip_info();
15337:         undef(%internetdom);
15338: 	undef(%name_to_host);
15339: 	undef(%hostname);
15340: 	undef(%hostdom);
15341: 	undef(%libserv);
15342: 	undef($loaded);
15343:     }
15344: 
15345:     sub load_hosts_tab {
15346: 	my ($ignore_cache,$nocache) = @_;
15347: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15348: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15349: 	my @config = <$config>;
15350: 	&parse_hosts_tab(\@config);
15351: 	close($config);
15352: 	$loaded=1;
15353:     }
15354: 
15355:     sub hostname {
15356: 	&load_hosts_tab() if (!$loaded);
15357: 
15358: 	my ($lonid) = @_;
15359: 	return $hostname{$lonid};
15360:     }
15361: 
15362:     sub all_hostnames {
15363: 	&load_hosts_tab() if (!$loaded);
15364: 
15365: 	return %hostname;
15366:     }
15367: 
15368:     sub all_names {
15369:         my ($ignore_cache,$nocache) = @_;
15370: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15371: 
15372: 	return %name_to_host;
15373:     }
15374: 
15375:     sub all_host_domain {
15376:         &load_hosts_tab() if (!$loaded);
15377:         return %hostdom;
15378:     }
15379: 
15380:     sub all_host_intdom {
15381:         &load_hosts_tab() if (!$loaded);
15382:         return %internetdom;
15383:     }
15384: 
15385:     sub is_library {
15386: 	&load_hosts_tab() if (!$loaded);
15387: 
15388: 	return exists($libserv{$_[0]});
15389:     }
15390: 
15391:     sub all_library {
15392: 	&load_hosts_tab() if (!$loaded);
15393: 
15394: 	return %libserv;
15395:     }
15396: 
15397:     sub unique_library {
15398: 	#2x reverse removes all hostnames that appear more than once
15399:         my %unique = reverse &all_library();
15400:         return reverse %unique;
15401:     }
15402: 
15403:     sub get_servers {
15404: 	&load_hosts_tab() if (!$loaded);
15405: 
15406: 	my ($domain,$type) = @_;
15407: 	my %possible_hosts = ($type eq 'library') ? %libserv
15408: 	                                          : %hostname;
15409: 	my %result;
15410: 	if (ref($domain) eq 'ARRAY') {
15411: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15412: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15413: 		    $result{$host} = $hostname;
15414: 		}
15415: 	    }
15416: 	} else {
15417: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15418: 		if ($hostdom{$host} eq $domain) {
15419: 		    $result{$host} = $hostname;
15420: 		}
15421: 	    }
15422: 	}
15423: 	return %result;
15424:     }
15425: 
15426:     sub get_unique_servers {
15427:         my %unique = reverse &get_servers(@_);
15428: 	return reverse %unique;
15429:     }
15430: 
15431:     sub host_domain {
15432: 	&load_hosts_tab() if (!$loaded);
15433: 
15434: 	my ($lonid) = @_;
15435: 	return $hostdom{$lonid};
15436:     }
15437: 
15438:     sub all_domains {
15439: 	&load_hosts_tab() if (!$loaded);
15440: 
15441: 	my %seen;
15442: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15443: 	return @uniq;
15444:     }
15445: 
15446:     sub internet_dom {
15447:         &load_hosts_tab() if (!$loaded);
15448: 
15449:         my ($lonid) = @_;
15450:         return $internetdom{$lonid};
15451:     }
15452: 
15453:     sub is_LC_dns {
15454:         &load_hosts_tab() if (!$loaded);
15455: 
15456:         my ($hostname) = @_;
15457:         return exists($LC_dns_serv{$hostname});
15458:     }
15459: 
15460: }
15461: 
15462: { 
15463:     my %iphost;
15464:     my %name_to_ip;
15465:     my %lonid_to_ip;
15466: 
15467:     sub get_hosts_from_ip {
15468: 	my ($ip) = @_;
15469: 	my %iphosts = &get_iphost();
15470: 	if (ref($iphosts{$ip})) {
15471: 	    return @{$iphosts{$ip}};
15472: 	}
15473: 	return;
15474:     }
15475:     
15476:     sub reset_hosts_ip_info {
15477: 	undef(%iphost);
15478: 	undef(%name_to_ip);
15479: 	undef(%lonid_to_ip);
15480:     }
15481: 
15482:     sub get_host_ip {
15483: 	my ($lonid) = @_;
15484: 	if (exists($lonid_to_ip{$lonid})) {
15485: 	    return $lonid_to_ip{$lonid};
15486: 	}
15487: 	my $name=&hostname($lonid);
15488:    	my $ip = gethostbyname($name);
15489: 	return if (!$ip || length($ip) ne 4);
15490: 	$ip=inet_ntoa($ip);
15491: 	$name_to_ip{$name}   = $ip;
15492: 	$lonid_to_ip{$lonid} = $ip;
15493: 	return $ip;
15494:     }
15495:     
15496:     sub get_iphost {
15497: 	my ($ignore_cache,$nocache) = @_;
15498: 
15499: 	if (!$ignore_cache) {
15500: 	    if (%iphost) {
15501: 		return %iphost;
15502: 	    }
15503: 	    my ($ip_info,$cached)=
15504: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15505: 	    if ($cached) {
15506: 		%iphost      = %{$ip_info->[0]};
15507: 		%name_to_ip  = %{$ip_info->[1]};
15508: 		%lonid_to_ip = %{$ip_info->[2]};
15509: 		return %iphost;
15510: 	    }
15511: 	}
15512: 
15513: 	# get yesterday's info for fallback
15514: 	my %old_name_to_ip;
15515: 	my ($ip_info,$cached)=
15516: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15517: 	if ($cached) {
15518: 	    %old_name_to_ip = %{$ip_info->[1]};
15519: 	}
15520: 
15521: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15522: 	foreach my $name (keys(%name_to_host)) {
15523: 	    my $ip;
15524: 	    if (!exists($name_to_ip{$name})) {
15525: 		$ip = gethostbyname($name);
15526: 		if (!$ip || length($ip) ne 4) {
15527: 		    if (defined($old_name_to_ip{$name})) {
15528: 			$ip = $old_name_to_ip{$name};
15529: 			&logthis("Can't find $name defaulting to old $ip");
15530: 		    } else {
15531: 			&logthis("Name $name no IP found");
15532: 			next;
15533: 		    }
15534: 		} else {
15535: 		    $ip=inet_ntoa($ip);
15536: 		}
15537: 		$name_to_ip{$name} = $ip;
15538: 	    } else {
15539: 		$ip = $name_to_ip{$name};
15540: 	    }
15541: 	    foreach my $id (@{ $name_to_host{$name} }) {
15542: 		$lonid_to_ip{$id} = $ip;
15543: 	    }
15544: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15545: 	}
15546:         unless ($nocache) {
15547: 	    &do_cache_new('iphost','iphost',
15548: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15549: 		          48*60*60);
15550:         }
15551: 
15552: 	return %iphost;
15553:     }
15554: 
15555:     #
15556:     #  Given a DNS returns the loncapa host name for that DNS 
15557:     # 
15558:     sub host_from_dns {
15559:         my ($dns) = @_;
15560:         my @hosts;
15561:         my $ip;
15562: 
15563:         if (exists($name_to_ip{$dns})) {
15564:             $ip = $name_to_ip{$dns};
15565:         }
15566:         if (!$ip) {
15567:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15568:             if (length($ip) == 4) { 
15569: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15570:             }
15571:         }
15572:         if ($ip) {
15573: 	    @hosts = get_hosts_from_ip($ip);
15574: 	    return $hosts[0];
15575:         }
15576:         return undef;
15577:     }
15578: 
15579:     sub get_internet_names {
15580:         my ($lonid) = @_;
15581:         return if ($lonid eq '');
15582:         my ($idnref,$cached)=
15583:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15584:         if ($cached) {
15585:             return $idnref;
15586:         }
15587:         my $ip = &get_host_ip($lonid);
15588:         my @hosts = &get_hosts_from_ip($ip);
15589:         my %iphost = &get_iphost();
15590:         my (@idns,%seen);
15591:         foreach my $id (@hosts) {
15592:             my $dom = &host_domain($id);
15593:             my $prim_id = &domain($dom,'primary');
15594:             my $prim_ip = &get_host_ip($prim_id);
15595:             next if ($seen{$prim_ip});
15596:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15597:                 foreach my $id (@{$iphost{$prim_ip}}) {
15598:                     my $intdom = &internet_dom($id);
15599:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15600:                         push(@idns,$intdom);
15601:                     }
15602:                 }
15603:             }
15604:             $seen{$prim_ip} = 1;
15605:         }
15606:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15607:     }
15608: 
15609: }
15610: 
15611: sub all_loncaparevs {
15612:     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);
15613: }
15614: 
15615: # ---------------------------------------------------------- Read loncaparev table
15616: {
15617:     sub load_loncaparevs { 
15618:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15619:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15620:                 while (my $configline=<$config>) {
15621:                     chomp($configline);
15622:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15623:                     $loncaparevs{$hostid}=$loncaparev;
15624:                 }
15625:                 close($config);
15626:             }
15627:         }
15628:     }
15629: }
15630: 
15631: # ---------------------------------------------------------- Read serverhostID table
15632: {
15633:     sub load_serverhomeIDs {
15634:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15635:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15636:                 while (my $configline=<$config>) {
15637:                     chomp($configline);
15638:                     my ($name,$id)=split(/:/,$configline);
15639:                     $serverhomeIDs{$name}=$id;
15640:                 }
15641:                 close($config);
15642:             }
15643:         }
15644:     }
15645: }
15646: 
15647: 
15648: BEGIN {
15649: 
15650: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15651:     unless ($readit) {
15652: {
15653:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15654:     %perlvar = (%perlvar,%{$configvars});
15655: }
15656: 
15657: 
15658: # ------------------------------------------------------ Read spare server file
15659: {
15660:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15661: 
15662:     while (my $configline=<$config>) {
15663:        chomp($configline);
15664:        if ($configline) {
15665: 	   my ($host,$type) = split(':',$configline,2);
15666: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15667: 	   push(@{ $spareid{$type} }, $host);
15668:        }
15669:     }
15670:     close($config);
15671: }
15672: # ------------------------------------------------------------ Read permissions
15673: {
15674:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15675: 
15676:     while (my $configline=<$config>) {
15677: 	chomp($configline);
15678: 	if ($configline) {
15679: 	    my ($role,$perm)=split(/ /,$configline);
15680: 	    if ($perm ne '') { $pr{$role}=$perm; }
15681: 	}
15682:     }
15683:     close($config);
15684: }
15685: 
15686: # -------------------------------------------- Read plain texts for permissions
15687: {
15688:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15689: 
15690:     while (my $configline=<$config>) {
15691: 	chomp($configline);
15692: 	if ($configline) {
15693: 	    my ($short,@plain)=split(/:/,$configline);
15694:             %{$prp{$short}} = ();
15695: 	    if (@plain > 0) {
15696:                 $prp{$short}{'std'} = $plain[0];
15697:                 for (my $i=1; $i<@plain; $i++) {
15698:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15699:                 }
15700:             }
15701: 	}
15702:     }
15703:     close($config);
15704: }
15705: 
15706: # ---------------------------------------------------------- Read package table
15707: {
15708:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15709: 
15710:     while (my $configline=<$config>) {
15711: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15712: 	chomp($configline);
15713: 	my ($short,$plain)=split(/:/,$configline);
15714: 	my ($pack,$name)=split(/\&/,$short);
15715: 	if ($plain ne '') {
15716: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15717: 	    $packagetab{$short}=$plain; 
15718: 	}
15719:     }
15720:     close($config);
15721: }
15722: 
15723: # ---------------------------------------------------------- Read loncaparev table
15724: 
15725: &load_loncaparevs();
15726: 
15727: # ---------------------------------------------------------- Read serverhostID table
15728: 
15729: &load_serverhomeIDs();
15730: 
15731: # ---------------------------------------------------------- Read releaseslist XML
15732: {
15733:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15734:     if (-e $file) {
15735:         my $parser = HTML::LCParser->new($file);
15736:         while (my $token = $parser->get_token()) {
15737:             if ($token->[0] eq 'S') {
15738:                 my $item = $token->[1];
15739:                 my $name = $token->[2]{'name'};
15740:                 my $value = $token->[2]{'value'};
15741:                 my $valuematch = $token->[2]{'valuematch'};
15742:                 my $namematch = $token->[2]{'namematch'};
15743:                 if ($item eq 'parameter') {
15744:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15745:                         my $release = $parser->get_text();
15746:                         $release =~ s/(^\s*|\s*$ )//gx;
15747:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15748:                     }
15749:                 } elsif ($item ne '' && $name ne '') {
15750:                     my $release = $parser->get_text();
15751:                     $release =~ s/(^\s*|\s*$ )//gx;
15752:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15753:                 }
15754:             }
15755:         }
15756:     }
15757: }
15758: 
15759: # ---------------------------------------------------------- Read managers table
15760: {
15761:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15762:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15763:             while (my $configline=<$config>) {
15764:                 chomp($configline);
15765:                 next if ($configline =~ /^\#/);
15766:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15767:                     $managerstab{$configline} = 1;
15768:                 }
15769:             }
15770:             close($config);
15771:         }
15772:     }
15773: }
15774: 
15775: # ------------- set up temporary directory
15776: {
15777:     $tmpdir = LONCAPA::tempdir();
15778: 
15779: }
15780: 
15781: # ------------- set default texengine (domain default overrides this)
15782: {
15783:     $deftex = LONCAPA::texengine();
15784: }
15785: 
15786: # ------------- set default minimum length for passwords for internal auth users
15787: {
15788:     $passwdmin = LONCAPA::passwd_min();
15789: }
15790: 
15791: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15792: 				'compress_threshold'=> 20_000,
15793:  			        });
15794: 
15795: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15796: $dumpcount=0;
15797: $locknum=0;
15798: 
15799: &logtouch();
15800: &logthis('<font color="yellow">INFO: Read configuration</font>');
15801: $readit=1;
15802:     {
15803: 	use integer;
15804: 	my $test=(2**32)+1;
15805: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15806: 	&logthis(" Detected 64bit platform ($_64bit)");
15807:     }
15808: }
15809: }
15810: 
15811: 1;
15812: __END__
15813: 
15814: =pod
15815: 
15816: =head1 NAME
15817: 
15818: Apache::lonnet - Subroutines to ask questions about things in the network.
15819: 
15820: =head1 SYNOPSIS
15821: 
15822: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15823: 
15824:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15825: 
15826: Common parameters:
15827: 
15828: =over 4
15829: 
15830: =item *
15831: 
15832: $uname : an internal username (if $cname expecting a course Id specifically)
15833: 
15834: =item *
15835: 
15836: $udom : a domain (if $cdom expecting a course's domain specifically)
15837: 
15838: =item *
15839: 
15840: $symb : a resource instance identifier
15841: 
15842: =item *
15843: 
15844: $namespace : the name of a .db file that contains the data needed or
15845: being set.
15846: 
15847: =back
15848: 
15849: =head1 OVERVIEW
15850: 
15851: lonnet provides subroutines which interact with the
15852: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15853: about classes, users, and resources.
15854: 
15855: For many of these objects you can also use this to store data about
15856: them or modify them in various ways.
15857: 
15858: =head2 Symbs
15859: 
15860: To identify a specific instance of a resource, LON-CAPA uses symbols
15861: or "symbs"X<symb>. These identifiers are built from the URL of the
15862: map, the resource number of the resource in the map, and the URL of
15863: the resource itself. The latter is somewhat redundant, but might help
15864: if maps change.
15865: 
15866: An example is
15867: 
15868:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15869: 
15870: The respective map entry is
15871: 
15872:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15873:   title="Problem 2">
15874:  </resource>
15875: 
15876: Symbs are used by the random number generator, as well as to store and
15877: restore data specific to a certain instance of for example a problem.
15878: 
15879: =head2 Storing And Retrieving Data
15880: 
15881: X<store()>X<cstore()>X<restore()>Three of the most important functions
15882: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15883: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15884: is is the non-critical message twin of cstore. These functions are for
15885: handlers to store a perl hash to a user's permanent data space in an
15886: easy manner, and to retrieve it again on another call. It is expected
15887: that a handler would use this once at the beginning to retrieve data,
15888: and then again once at the end to send only the new data back.
15889: 
15890: The data is stored in the user's data directory on the user's
15891: homeserver under the ID of the course.
15892: 
15893: The hash that is returned by restore will have all of the previous
15894: value for all of the elements of the hash.
15895: 
15896: Example:
15897: 
15898:  #creating a hash
15899:  my %hash;
15900:  $hash{'foo'}='bar';
15901: 
15902:  #storing it
15903:  &Apache::lonnet::cstore(\%hash);
15904: 
15905:  #changing a value
15906:  $hash{'foo'}='notbar';
15907: 
15908:  #adding a new value
15909:  $hash{'bar'}='foo';
15910:  &Apache::lonnet::cstore(\%hash);
15911: 
15912:  #retrieving the hash
15913:  my %history=&Apache::lonnet::restore();
15914: 
15915:  #print the hash
15916:  foreach my $key (sort(keys(%history))) {
15917:    print("\%history{$key} = $history{$key}");
15918:  }
15919: 
15920: Will print out:
15921: 
15922:  %history{1:foo} = bar
15923:  %history{1:keys} = foo:timestamp
15924:  %history{1:timestamp} = 990455579
15925:  %history{2:bar} = foo
15926:  %history{2:foo} = notbar
15927:  %history{2:keys} = foo:bar:timestamp
15928:  %history{2:timestamp} = 990455580
15929:  %history{bar} = foo
15930:  %history{foo} = notbar
15931:  %history{timestamp} = 990455580
15932:  %history{version} = 2
15933: 
15934: Note that the special hash entries C<keys>, C<version> and
15935: C<timestamp> were added to the hash. C<version> will be equal to the
15936: total number of versions of the data that have been stored. The
15937: C<timestamp> attribute will be the UNIX time the hash was
15938: stored. C<keys> is available in every historical section to list which
15939: keys were added or changed at a specific historical revision of a
15940: hash.
15941: 
15942: B<Warning>: do not store the hash that restore returns directly. This
15943: will cause a mess since it will restore the historical keys as if the
15944: were new keys. I.E. 1:foo will become 1:1:foo etc.
15945: 
15946: Calling convention:
15947: 
15948:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15949:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15950: 
15951: For more detailed information, see lonnet specific documentation.
15952: 
15953: =head1 RETURN MESSAGES
15954: 
15955: =over 4
15956: 
15957: =item * B<con_lost>: unable to contact remote host
15958: 
15959: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15960: when the connection is brought back up
15961: 
15962: =item * B<con_failed>: unable to contact remote host and unable to save message
15963: for later delivery
15964: 
15965: =item * B<error:>: an error a occurred, a description of the error follows the :
15966: 
15967: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15968: that was requested
15969: 
15970: =back
15971: 
15972: =head1 PUBLIC SUBROUTINES
15973: 
15974: =head2 Session Environment Functions
15975: 
15976: =over 4
15977: 
15978: =item * 
15979: X<appenv()>
15980: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15981: the user envirnoment file, and will be restored for each access this
15982: user makes during this session, also modifies the %env for the current
15983: process. Optional rolesarrayref - if defined contains a reference to an array
15984: of roles which are exempt from the restriction on modifying user.role entries 
15985: in the user's environment.db and in %env.    
15986: 
15987: =item *
15988: X<delenv()>
15989: B<delenv($delthis,$regexp)>: removes all items from the session
15990: environment file that begin with $delthis. If the 
15991: optional second arg - $regexp - is true, $delthis is treated as a 
15992: regular expression, otherwise \Q$delthis\E is used. 
15993: The values are also deleted from the current processes %env.
15994: 
15995: =item * get_env_multiple($name) 
15996: 
15997: gets $name from the %env hash, it seemlessly handles the cases where multiple
15998: values may be defined and end up as an array ref.
15999: 
16000: returns an array of values
16001: 
16002: =back
16003: 
16004: =head2 User Information
16005: 
16006: =over 4
16007: 
16008: =item *
16009: X<queryauthenticate()>
16010: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16011: authentication scheme
16012: 
16013: =item *
16014: X<authenticate()>
16015: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16016: authenticate user from domain's lib servers (first use the current
16017: one). C<$upass> should be the users password.
16018: $checkdefauth is optional (value is 1 if a check should be made to
16019:    authenticate user using default authentication method, and allow
16020:    account creation if username does not have account in the domain).
16021: $clientcancheckhost is optional (value is 1 if checking whether the
16022:    server can host will occur on the client side in lonauth.pm).   
16023: 
16024: =item *
16025: X<homeserver()>
16026: B<homeserver($uname,$udom)>: find the server which has
16027: the user's directory and files (there must be only one), this caches
16028: the answer, and also caches if there is a borken connection.
16029: 
16030: =item *
16031: X<idget()>
16032: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16033: a list of student/employee IDs or clicker IDs
16034: (student/employee IDs are a unique resource in a domain, there must be 
16035: only 1 ID per username, and only 1 username per ID in a specific domain).
16036: clickerIDs are not necessarily unique, as students might share clickers.
16037: (returns hash: id=>name,id=>name)
16038: 
16039: =item *
16040: X<idrget()>
16041: B<idrget($udom,@unames)>: find the IDs behind a list of
16042: usernames (returns hash: name=>id,name=>id)
16043: 
16044: =item *
16045: X<idput()>
16046: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16047: names and associated student/employee IDs or clicker IDs.
16048: 
16049: =item *
16050: X<iddel()>
16051: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16052: student/employee ID or clicker ID username look-ups from domain.
16053: The homeserver ($uhome) and namespace ($namespace) are optional.
16054: If no $uhome is provided, it will be determined usig &homeserver()
16055: for each user.  If no $namespace is provided, the default is ids.
16056: 
16057: =item *
16058: X<updateclickers()>
16059: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16060: clicker ID-to-username look-ups in clickers.db on library server.
16061: Permitted actions are add or del (i.e., add or delete). The 
16062: clickers.db contains clickerID as keys (escaped), and each corresponding
16063: value is an escaped comma-separated list of usernames (for whom the
16064: library server is the homeserver), who registered that particular ID.
16065: If $critical is true, the update will be sent via &critical, otherwise
16066: &reply() will be used.
16067: 
16068: =item *
16069: X<rolesinit()>
16070: B<rolesinit($udom,$username)>: get user privileges.
16071: returns user role, first access and timer interval hashes
16072: 
16073: =item *
16074: X<privileged()>
16075: B<privileged($username,$domain)>: returns a true if user has a
16076: privileged and active role (i.e. su or dc), false otherwise.
16077: 
16078: =item *
16079: X<getsection()>
16080: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16081: course $cname, return section name/number or '' for "not in course"
16082: and '-1' for "no section"
16083: 
16084: =item *
16085: X<userenvironment()>
16086: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16087: passed in @what from the requested user's environment, returns a hash
16088: 
16089: =item * 
16090: X<userlog_query()>
16091: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16092: activity.log file. %filters defines filters applied when parsing the
16093: log file. These can be start or end timestamps, or the type of action
16094: - log to look for Login or Logout events, check for Checkin or
16095: Checkout, role for role selection. The response is in the form
16096: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16097: escaped strings of the action recorded in the activity.log file.
16098: 
16099: =back
16100: 
16101: =head2 User Roles
16102: 
16103: =over 4
16104: 
16105: =item *
16106: 
16107: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16108: returns codes for allowed actions.
16109: 
16110: The first argument is required, all others are optional.
16111: 
16112: $priv is the privilege being checked.
16113: $uri contains additional information about what is being checked for access (e.g.,
16114: URL, course ID etc.). 
16115: $symb is the unique resource instance identifier in a course; if needed,
16116: but not provided, it will be retrieved via a call to &symbread(). 
16117: $role is the role for which a priv is being checked (only used if priv is evb). 
16118: $clientip is the user's IP address (only used when checking for access to portfolio 
16119: files).
16120: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16121: prevents recursive calls to &allowed.
16122: 
16123:  F: full access
16124:  U,I,K: authentication modes (cxx only)
16125:  '': forbidden
16126:  1: user needs to choose course
16127:  2: browse allowed
16128:  A: passphrase authentication needed
16129:  B: access temporarily blocked because of a blocking event in a course.
16130:  D: access blocked because access is required via session initiated via deep-link 
16131: 
16132: =item *
16133: 
16134: constructaccess($url,$setpriv) : check for access to construction space URL
16135: 
16136: See if the owner domain and name in the URL match those in the
16137: expected environment.  If so, return three element list
16138: ($ownername,$ownerdomain,$ownerhome).
16139: 
16140: Otherwise return the null string.
16141: 
16142: If second argument 'setpriv' is true, it assigns the privileges,
16143: and returns the same three element list, unless the owner has
16144: blocked "ad hoc" Domain Coordinator access to the Author Space,
16145: in which case the null string is returned.
16146: 
16147: =item *
16148: 
16149: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16150: define a custom role rolename set privileges in format of lonTabs/roles.tab
16151: for system, domain, and course level. $uname and $udom are optional (current
16152: user's username and domain will be used when either of $uname or $udom are absent.
16153: 
16154: =item *
16155: 
16156: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16157: (rolesplain.tab); plain text explanation of a user role term.
16158: $type is Course (default) or Community.
16159: If $forcedefault evaluates to true, text returned will be default 
16160: text for $type. Otherwise, if this is a course, the text returned 
16161: will be a custom name for the role (if defined in the course's 
16162: environment).  If no custom name is defined the default is returned.
16163:    
16164: =item *
16165: 
16166: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16167: All arguments are optional. Returns a hash of a roles, either for
16168: co-author/assistant author roles for a user's Construction Space
16169: (default), or if $context is 'userroles', roles for the user himself,
16170: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16171: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16172: For each key, value is set to colon-separated start and end times for
16173: the role.  If no username and domain are specified, will default to
16174: current user/domain. Types, roles, and roledoms are references to arrays
16175: of role statuses (active, future or previous), roles 
16176: (e.g., cc,in, st etc.) and domains of the roles which can be used
16177: to restrict the list of roles reported. If no array ref is 
16178: provided for types, will default to return only active roles.
16179: 
16180: =item *
16181: 
16182: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16183: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16184: 
16185: Additional optional arguments are: $type (if role checking is to be restricted 
16186: to certain user status types -- previous (expired roles), active (currently
16187: available roles) or future (roles available in the future), and
16188: $hideprivileged -- if true will not report course roles for users who
16189: have active Domain Coordinator role in course's domain or in additional
16190: domains (specified in 'Domains to check for privileged users' in course
16191: environment -- set via:  Course Settings -> Classlists and staff listing).
16192: 
16193: =item *
16194: 
16195: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16196: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16197: $possdomains and $possroles are optional array refs -- to domains to check and
16198: roles to check.  If $possdomains is not specified, a dump will be done of the
16199: users' roles.db to check for a dc or su role in any domain. This can be
16200: time consuming if &privileged is called repeatedly (e.g., when displaying a
16201: classlist), so in such cases, supplying a $possdomains array is preferred, as
16202: this then allows &privileged_by_domain() to be used, which caches the identity
16203: of privileged users, eliminating the need for repeated calls to &dump().
16204: 
16205: =item *
16206: 
16207: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16208: where the outer hash keys are domains specified in the $possdomains array ref,
16209: next inner hash keys are privileged roles specified in the $roles array ref,
16210: and the innermost hash contains key = value pairs for username:domain = end:start
16211: for active or future "privileged" users with that role in that domain. To avoid
16212: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16213: innerhash are cached using priv_$role and $dom as the identifiers.
16214: 
16215: =back
16216: 
16217: =head2 User Modification
16218: 
16219: =over 4
16220: 
16221: =item *
16222: 
16223: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16224: user for the level given by URL.  Optional start and end dates (leave empty
16225: string or zero for "no date")
16226: 
16227: =item *
16228: 
16229: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16230: change a users, password, possible return values are: ok,
16231: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16232: refused
16233: 
16234: =item *
16235: 
16236: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16237: 
16238: =item *
16239: 
16240: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16241:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16242: 
16243: will update user information (firstname,middlename,lastname,generation,
16244: permanentemail), and if forceid is true, student/employee ID also.
16245: A user's institutional affiliation(s) can also be updated.
16246: User information fields will not be overwritten with empty entries 
16247: unless the field is included in the $candelete array reference.
16248: This array is included when a single user is modified via "Manage Users",
16249: or when Autoupdate.pl is run by cron in a domain.
16250: 
16251: =item *
16252: 
16253: modifystudent
16254: 
16255: modify a student's enrollment and identification information.
16256: The course id is resolved based on the current user's environment.  
16257: This means the invoking user must be a course coordinator or otherwise
16258: associated with a course.
16259: 
16260: This call is essentially a wrapper for lonnet::modifyuser and
16261: lonnet::modify_student_enrollment
16262: 
16263: Inputs: 
16264: 
16265: =over 4
16266: 
16267: =item B<$udom> Student's loncapa domain
16268: 
16269: =item B<$uname> Student's loncapa login name
16270: 
16271: =item B<$uid> Student/Employee ID
16272: 
16273: =item B<$umode> Student's authentication mode
16274: 
16275: =item B<$upass> Student's password
16276: 
16277: =item B<$first> Student's first name
16278: 
16279: =item B<$middle> Student's middle name
16280: 
16281: =item B<$last> Student's last name
16282: 
16283: =item B<$gene> Student's generation
16284: 
16285: =item B<$usec> Student's section in course
16286: 
16287: =item B<$end> Unix time of the roles expiration
16288: 
16289: =item B<$start> Unix time of the roles start date
16290: 
16291: =item B<$forceid> If defined, allow $uid to be changed
16292: 
16293: =item B<$desiredhome> server to use as home server for student
16294: 
16295: =item B<$email> Student's permanent e-mail address
16296: 
16297: =item B<$type> Type of enrollment (auto or manual)
16298: 
16299: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16300: 
16301: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16302: 
16303: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16304: 
16305: =item B<$context> role change context (shown in User Management Logs display in a course)
16306: 
16307: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16308: 
16309: =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.
16310: 
16311: =back
16312: 
16313: =item *
16314: 
16315: modify_student_enrollment
16316: 
16317: Change a student's enrollment status in a class.  The environment variable
16318: 'role.request.course' must be defined for this function to proceed.
16319: 
16320: Inputs:
16321: 
16322: =over 4
16323: 
16324: =item $udom, student's domain
16325: 
16326: =item $uname, student's name
16327: 
16328: =item $uid, student's user id
16329: 
16330: =item $first, student's first name
16331: 
16332: =item $middle
16333: 
16334: =item $last
16335: 
16336: =item $gene
16337: 
16338: =item $usec
16339: 
16340: =item $end
16341: 
16342: =item $start
16343: 
16344: =item $type
16345: 
16346: =item $locktype
16347: 
16348: =item $cid
16349: 
16350: =item $selfenroll
16351: 
16352: =item $context
16353: 
16354: =item $credits, number of credits student will earn from this class
16355: 
16356: =item $instsec, institutional course section code for student
16357: 
16358: =back
16359: 
16360: 
16361: =item *
16362: 
16363: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16364: custom role; give a custom role to a user for the level given by URL.  Specify
16365: name and domain of role author, and role name
16366: 
16367: =item *
16368: 
16369: revokerole($udom,$uname,$url,$role) : revoke a role for url
16370: 
16371: =item *
16372: 
16373: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16374: 
16375: =back
16376: 
16377: =head2 Course Infomation
16378: 
16379: =over 4
16380: 
16381: =item *
16382: 
16383: coursedescription($courseid,$options) : returns a hash of information about the
16384: specified course id, including all environment settings for the
16385: course, the description of the course will be in the hash under the
16386: key 'description'
16387: 
16388: $options is an optional parameter that if supplied is a hash reference that controls
16389: what how this function works.  It has the following key/values:
16390: 
16391: =over 4
16392: 
16393: =item freshen_cache
16394: 
16395: If defined, and the environment cache for the course is valid, it is 
16396: returned in the returned hash.
16397: 
16398: =item one_time
16399: 
16400: If defined, the last cache time is set to _now_
16401: 
16402: =item user
16403: 
16404: If defined, the supplied username is used instead of the current user.
16405: 
16406: 
16407: =back
16408: 
16409: =item *
16410: 
16411: resdata($name,$domain,$type,@which) : request for current parameter
16412: setting for a specific $type, where $type is either 'course' or 'user',
16413: @what should be a list of parameters to ask about. This routine caches
16414: answers for 10 minutes.
16415: 
16416: =item *
16417: 
16418: get_courseresdata($courseid, $domain) : dump the entire course resource
16419: data base, returning a hash that is keyed by the resource name and has
16420: values that are the resource value.  I believe that the timestamps and
16421: versions are also returned.
16422: 
16423: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16424: supplemental content area. This routine caches the number of files for 
16425: 10 minutes.
16426: 
16427: =back
16428: 
16429: =head2 Course Modification
16430: 
16431: =over 4
16432: 
16433: =item *
16434: 
16435: writecoursepref($courseid,%prefs) : write preferences (environment
16436: database) for a course
16437: 
16438: =item *
16439: 
16440: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16441: 
16442: =item *
16443: 
16444: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16445: 
16446: =item *
16447: 
16448: is_course($courseid), is_course($cdom, $cnum)
16449: 
16450: Accepts either a combined $courseid (in the form of domain_courseid) or the
16451: two component version $cdom, $cnum. It checks if the specified course exists.
16452: 
16453: Returns:
16454:     undef if the course doesn't exist, otherwise
16455:     in scalar context the combined courseid.
16456:     in list context the two components of the course identifier, domain and 
16457:     courseid.    
16458: 
16459: =back
16460: 
16461: =head2 Bubblesheet Configuration
16462: 
16463: =over 4
16464: 
16465: =item *
16466: 
16467: get_scantron_config($which)
16468: 
16469: $which - the name of the configuration to parse from the file.
16470: 
16471: Parses and returns the bubblesheet configuration line selected as a
16472: hash of configuration file fields.
16473: 
16474: 
16475: Returns:
16476:     If the named configuration is not in the file, an empty
16477:     hash is returned.
16478: 
16479:     a hash with the fields
16480:       name         - internal name for the this configuration setup
16481:       description  - text to display to operator that describes this config
16482:       CODElocation - if 0 or the string 'none'
16483:                           - no CODE exists for this config
16484:                      if -1 || the string 'letter'
16485:                           - a CODE exists for this config and is
16486:                             a string of letters
16487:                      Unsupported value (but planned for future support)
16488:                           if a positive integer
16489:                                - The CODE exists as the first n items from
16490:                                  the question section of the form
16491:                           if the string 'number'
16492:                                - The CODE exists for this config and is
16493:                                  a string of numbers
16494:       CODEstart   - (only matter if a CODE exists) column in the line where
16495:                      the CODE starts
16496:       CODElength  - length of the CODE
16497:       IDstart     - column where the student/employee ID starts
16498:       IDlength    - length of the student/employee ID info
16499:       Qstart      - column where the information from the bubbled
16500:                     'questions' start
16501:       Qlength     - number of columns comprising a single bubble line from
16502:                     the sheet. (usually either 1 or 10)
16503:       Qon         - either a single character representing the character used
16504:                     to signal a bubble was chosen in the positional setup, or
16505:                     the string 'letter' if the letter of the chosen bubble is
16506:                     in the final, or 'number' if a number representing the
16507:                     chosen bubble is in the file (1->A 0->J)
16508:       Qoff        - the character used to represent that a bubble was
16509:                     left blank
16510:       PaperID     - if the scanning process generates a unique number for each
16511:                     sheet scanned the column that this ID number starts in
16512:       PaperIDlength - number of columns that comprise the unique ID number
16513:                       for the sheet of paper
16514:       FirstName   - column that the first name starts in
16515:       FirstNameLength - number of columns that the first name spans
16516:       LastName    - column that the last name starts in
16517:       LastNameLength - number of columns that the last name spans
16518:       BubblesPerRow - number of bubbles available in each row used to
16519:                       bubble an answer. (If not specified, 10 assumed).
16520: 
16521: 
16522: =item *
16523: 
16524: get_scantronformat_file($cdom)
16525: 
16526: $cdom - the course's domain (optional); if not supplied, uses
16527: domain for current $env{'request.course.id'}.
16528: 
16529: Returns an array containing lines from the scantron format file for
16530: the domain of the course.
16531: 
16532: If a url for a custom.tab file is listed in domain's configuration.db,
16533: lines are from this file.
16534: 
16535: Otherwise, if a default.tab has been published in RES space by the
16536: domainconfig user, lines are from this file.
16537: 
16538: Otherwise, fall back to getting lines from the legacy file on the
16539: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16540: 
16541: =back
16542: 
16543: =head2 Resource Subroutines
16544: 
16545: =over 4
16546: 
16547: =item *
16548: 
16549: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16550: 
16551: =item *
16552: 
16553: repcopy($filename) : subscribes to the requested file, and attempts to
16554: replicate from the owning library server, Might return
16555: 'unavailable', 'not_found', 'forbidden', 'ok', or
16556: 'bad_request', also attempts to grab the metadata for the
16557: resource. Expects the local filesystem pathname
16558: (/home/httpd/html/res/....)
16559: 
16560: =back
16561: 
16562: =head2 Resource Information
16563: 
16564: =over 4
16565: 
16566: =item *
16567: 
16568: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16569: and returns the value of a variety of different possible values,
16570: $varname should be a request string, and the other parameters can be
16571: used to specify who and what one is asking about. Ordinarily, $cid 
16572: does not need to be specified, as it is retrived from 
16573: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16574: within lonuserstate::loadmap() when initializing a course, before
16575: $env{'request.course.id'} has been set, so it needs to be provided
16576: in that one case.
16577: 
16578: Possible values for $varname are environment.lastname (or other item
16579: from the envirnment hash), user.name (or someother aspect about the
16580: user), resource.0.maxtries (or some other part and parameter of a
16581: resource)
16582: 
16583: =item *
16584: 
16585: directcondval($number) : get current value of a condition; reads from a state
16586: string
16587: 
16588: =item *
16589: 
16590: condval($condidx) : value of condition index based on state
16591: 
16592: =item *
16593: 
16594: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16595: resource's metadata, $what should be either a specific key, or either
16596: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16597: packages that this resource currently uses, the last 3 arguments are 
16598: only used internally for recursive metadata.
16599: 
16600: the toolsymb is only used where the uri is for an external tool (for which
16601: the uri as well as the symb are guaranteed to be unique).
16602: 
16603: this function automatically caches all requests except any made recursively
16604: to retrieve a list of metadata keys for an imported library file ($liburi is 
16605: defined).
16606: 
16607: =item *
16608: 
16609: metadata_query($query,$custom,$customshow) : make a metadata query against the
16610: network of library servers; returns file handle of where SQL and regex results
16611: will be stored for query
16612: 
16613: =item *
16614: 
16615: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16616: return symbolic list entry (all arguments optional). 
16617: 
16618: Args: filename is the filename (including path) for the file for which a symb 
16619: is required; donotrecurse, if true will prevent calls to allowed() being made 
16620: to check access status if more than one resource was found in the bighash 
16621: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16622: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16623: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16624: cause possible symbs to be checked to determine if they are subject to content
16625: blocking, if so they will not be included as possible symbs; possibles is a
16626: ref to a hash, which, as a side effect, will be populated with all possible 
16627: symbs (content blocking not tested).
16628:  
16629: returns the data handle
16630: 
16631: =item *
16632: 
16633: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16634: and is a possible symb for the URL in $thisfn, and if is an encrypted
16635: resource that the user accessed using /enc/ returns a 1 on success, 0
16636: on failure, user must be in a course, as it assumes the existence of
16637: the course initial hash, and uses $env('request.course.id'}.  The third
16638: arg is an optional reference to a scalar.  If this arg is passed in the 
16639: call to symbverify, it will be set to 1 if the symb has been set to be 
16640: encrypted; otherwise it will be null.  
16641: 
16642: =item *
16643: 
16644: symbclean($symb) : removes versions numbers from a symb, returns the
16645: cleaned symb
16646: 
16647: =item *
16648: 
16649: is_on_map($uri) : checks if the $uri is somewhere on the current
16650: course map, user must be in a course for it to work.
16651: 
16652: =item *
16653: 
16654: numval($salt) : return random seed value (addend for rndseed)
16655: 
16656: =item *
16657: 
16658: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16659: a random seed, all arguments are optional, if they aren't sent it uses the
16660: environment to derive them. Note: if symb isn't sent and it can't get one
16661: from &symbread it will use the current time as its return value
16662: 
16663: =item *
16664: 
16665: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16666: unfakeable, receipt
16667: 
16668: =item *
16669: 
16670: receipt() : API to ireceipt working off of env values; given out to users
16671: 
16672: =item *
16673: 
16674: countacc($url) : count the number of accesses to a given URL
16675: 
16676: =item *
16677: 
16678: 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
16679: 
16680: =item *
16681: 
16682: 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)
16683: 
16684: =item *
16685: 
16686: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16687: 
16688: =item *
16689: 
16690: devalidate($symb) : devalidate temporary spreadsheet calculations,
16691: forcing spreadsheet to reevaluate the resource scores next time.
16692: 
16693: =item * 
16694: 
16695: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16696: when viewing in course context.
16697: 
16698:  input: six args -- filename (decluttered), course number, course domain,
16699:                     url, symb (if registered) and group (if this is a 
16700:                     group item -- e.g., bulletin board, group page etc.).
16701: 
16702:  output: array of five scalars --
16703:          $cfile -- url for file editing if editable on current server
16704:          $home -- homeserver of resource (i.e., for author if published,
16705:                                           or course if uploaded.).
16706:          $switchserver --  1 if server switch will be needed.
16707:          $forceedit -- 1 if icon/link should be to go to edit mode 
16708:          $forceview -- 1 if icon/link should be to go to view mode
16709: 
16710: =item *
16711: 
16712: is_course_upload($file,$cnum,$cdom)
16713: 
16714: Used in course context to determine if current file was uploaded to 
16715: the course (i.e., would be found in /userfiles/docs on the course's 
16716: homeserver.
16717: 
16718:   input: 3 args -- filename (decluttered), course number and course domain.
16719:   output: boolean -- 1 if file was uploaded.
16720: 
16721: =back
16722: 
16723: =head2 Storing/Retreiving Data
16724: 
16725: =over 4
16726: 
16727: =item *
16728: 
16729: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16730: permanently for this url; hashref needs to be given and should be a \%hashname;
16731: the remaining args aren't required and if they aren't passed or are '' they will
16732: be derived from the env (with the exception of $laststore, which is an 
16733: optional arg used when a user's submission is stored in grading).
16734: $laststore is $version=$timestamp, where $version is the most recent version
16735: number retrieved for the corresponding $symb in the $namespace db file, and
16736: $timestamp is the timestamp for that transaction (UNIX time).
16737: $laststore is currently only passed when cstore() is called by 
16738: structuretags::finalize_storage().
16739: 
16740: =item *
16741: 
16742: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16743: but uses critical subroutine
16744: 
16745: =item *
16746: 
16747: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16748: all args are optional
16749: 
16750: =item *
16751: 
16752: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16753: dumps the complete (or key matching regexp) namespace into a hash
16754: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16755: normally &store()ed into
16756: 
16757: $range should be either an integer '100' (give me the first 100
16758:                                            matching records)
16759:               or be  two integers sperated by a - with no spaces
16760:                  '30-50' (give me the 30th through the 50th matching
16761:                           records)
16762: 
16763: 
16764: =item *
16765: 
16766: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16767: replaces a &store() version of data with a replacement set of data
16768: for a particular resource in a namespace passed in the $storehash hash 
16769: reference. If $tolog is true, the transaction is logged in the courselog
16770: with an action=PUTSTORE.
16771: 
16772: =item *
16773: 
16774: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16775: works very similar to store/cstore, but all data is stored in a
16776: temporary location and can be reset using tmpreset, $storehash should
16777: be a hash reference, returns nothing on success
16778: 
16779: =item *
16780: 
16781: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16782: similar to restore, but all data is stored in a temporary location and
16783: can be reset using tmpreset. Returns a hash of values on success,
16784: error string otherwise.
16785: 
16786: =item *
16787: 
16788: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16789: deltes all keys for $symb form the temporary storage hash.
16790: 
16791: =item *
16792: 
16793: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16794: reference filled in from namesp ($udom and $uname are optional)
16795: 
16796: =item *
16797: 
16798: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16799: namesp ($udom and $uname are optional)
16800: 
16801: =item *
16802: 
16803: dump($namespace,$udom,$uname,$regexp,$range) : 
16804: dumps the complete (or key matching regexp) namespace into a hash
16805: ($udom, $uname, $regexp, $range are optional)
16806: 
16807: $range should be either an integer '100' (give me the first 100
16808:                                            matching records)
16809:               or be  two integers sperated by a - with no spaces
16810:                  '30-50' (give me the 30th through the 50th matching
16811:                           records)
16812: =item *
16813: 
16814: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16815: $store can be a scalar, an array reference, or if the amount to be 
16816: incremented is > 1, a hash reference.
16817: 
16818: ($udom and $uname are optional)
16819: 
16820: =item *
16821: 
16822: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16823: ($udom and $uname are optional)
16824: 
16825: =item *
16826: 
16827: cput($namespace,$storehash,$udom,$uname) : critical put
16828: ($udom and $uname are optional)
16829: 
16830: =item *
16831: 
16832: newput($namespace,$storehash,$udom,$uname) :
16833: 
16834: Attempts to store the items in the $storehash, but only if they don't
16835: currently exist, if this succeeds you can be certain that you have 
16836: successfully created a new key value pair in the $namespace db.
16837: 
16838: 
16839: Args:
16840:  $namespace: name of database to store values to
16841:  $storehash: hashref to store to the db
16842:  $udom: (optional) domain of user containing the db
16843:  $uname: (optional) name of user caontaining the db
16844: 
16845: Returns:
16846:  'ok' -> succeeded in storing all keys of $storehash
16847:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16848:                         least <key> already existed in the db (other
16849:                         requested keys may also already exist)
16850:  'error: <msg>' -> unable to tie the DB or other error occurred
16851:  'con_lost' -> unable to contact request server
16852:  'refused' -> action was not allowed by remote machine
16853: 
16854: 
16855: =item *
16856: 
16857: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16858: reference filled in from namesp (encrypts the return communication)
16859: ($udom and $uname are optional)
16860: 
16861: =item *
16862: 
16863: log($udom,$name,$home,$message) : write to permanent log for user; use
16864: critical subroutine
16865: 
16866: =item *
16867: 
16868: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16869: array reference filled in from namespace found in domain level on either
16870: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16871: 
16872: =item *
16873: 
16874: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16875: domain level either on specified domain server ($uhome) or primary domain 
16876: server ($udom and $uhome are optional)
16877: 
16878: =item * 
16879: 
16880: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16881: for: authentication, language, quotas, timezone, date locale, and portal URL in
16882: the target domain.
16883: 
16884: May also include additional key => value pairs for the following groups:
16885: 
16886: =over
16887: 
16888: =item
16889: disk quotas (MB allocated by default to portfolios and authoring spaces).
16890: 
16891: =over
16892: 
16893: =item defaultquota, authorquota
16894: 
16895: =back
16896: 
16897: =item
16898: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16899: portfolio for users).
16900: 
16901: =over
16902: 
16903: =item
16904: aboutme, blog, webdav, portfolio
16905: 
16906: =back
16907: 
16908: =item
16909: requestcourses: ability to request courses, and how requests are processed.
16910: 
16911: =over
16912: 
16913: =item
16914: official, unofficial, community, textbook, placement
16915: 
16916: =back
16917: 
16918: =item
16919: inststatus: types of institutional affiliation, and order in which they are displayed.
16920: 
16921: =over
16922: 
16923: =item
16924: inststatustypes, inststatusorder, inststatusguest
16925: 
16926: =back
16927: 
16928: =item
16929: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16930: for course's uploaded content.
16931: 
16932: =over
16933: 
16934: =item
16935: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16936: communityquota, textbookquota, placementquota
16937: 
16938: =back
16939: 
16940: =item
16941: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16942: on your servers.
16943: 
16944: =over
16945: 
16946: =item 
16947: remotesessions, hostedsessions
16948: 
16949: =back
16950: 
16951: =back
16952: 
16953: In cases where a domain coordinator has never used the "Set Domain Configuration"
16954: utility to create a configuration.db file on a domain's primary library server 
16955: only the following domain defaults: auth_def, auth_arg_def, lang_def
16956: -- corresponding values are authentication type (internal, krb4, krb5,
16957: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16958: will be available. Values are retrieved from cache (if current), unless the
16959: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16960: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16961: 
16962: Typical usage:
16963: 
16964: %domdefaults = &get_domain_defaults($target_domain);
16965: 
16966: =back
16967: 
16968: =head2 Network Status Functions
16969: 
16970: =over 4
16971: 
16972: =item *
16973: 
16974: dirlist() : return directory list based on URI (first arg).
16975: 
16976: Inputs: 1 required, 5 optional.
16977: 
16978: =over
16979: 
16980: =item 
16981: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16982: 
16983: =item
16984: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16985: 
16986: =item
16987: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16988: 
16989: =item
16990: $getpropath - boolean: 1 if prepend path using &propath(). 
16991: 
16992: =item
16993: $getuserdir - boolean: 1 if prepend path for "userfiles".
16994: 
16995: =item 
16996: $alternateRoot - path to prepend in place of path from $uri.
16997: 
16998: =back
16999: 
17000: Returns: Array of up to two items.
17001: 
17002: =over
17003: 
17004: a reference to an array of files/subdirectories
17005: 
17006: =over
17007: 
17008: Each element in the array of files/subdirectories is a & separated list of
17009: item name and the result of running stat on the item.  If dirlist was requested
17010: for a file instead of a directory, the item name will be ''. For a directory 
17011: listing, if the item is a metadata file, the element will end &N&M 
17012: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17013: default copyright set (1).  
17014: 
17015: =back
17016: 
17017: a scalar containing error condition (if encountered).
17018: 
17019: =over
17020: 
17021: =item 
17022: no_host (no homeserver identified for $username:$domain).
17023: 
17024: =item 
17025: no_such_host (server contacted for listing not identified as valid host).
17026: 
17027: =item 
17028: con_lost (connection to remote server failed).
17029: 
17030: =item 
17031: refused (invalid $username:$domain received on lond side).
17032: 
17033: =item 
17034: no_such_dir (directory at specified path on lond side does not exist). 
17035: 
17036: =item 
17037: empty (directory at specified path on lond side is empty).
17038: 
17039: =over
17040: 
17041: This is currently not encountered because the &ls3, &ls2, 
17042: &ls (_handler) routines on the lond side do not filter out
17043: . and .. from a directory listing. 
17044: 
17045: =back
17046: 
17047: =back
17048: 
17049: =back
17050: 
17051: =item *
17052: 
17053: spareserver() : find server with least workload from spare.tab
17054: 
17055: 
17056: =item *
17057: 
17058: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17059: if there is no corresponding loncapa host.
17060: 
17061: =back
17062: 
17063: 
17064: =head2 Apache Request
17065: 
17066: =over 4
17067: 
17068: =item *
17069: 
17070: ssi($url,%hash) : server side include, does a complete request cycle on url to
17071: localhost, posts hash
17072: 
17073: =back
17074: 
17075: =head2 Data to String to Data
17076: 
17077: =over 4
17078: 
17079: =item *
17080: 
17081: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17082: and '&' separators, supports elements that are arrayrefs and hashrefs
17083: 
17084: =item *
17085: 
17086: hashref2str($hashref) : convert a hashref into a string complete with
17087: escaping and '=' and '&' separators, supports elements that are
17088: arrayrefs and hashrefs
17089: 
17090: =item *
17091: 
17092: arrayref2str($arrayref) : convert an arrayref into a string complete
17093: with escaping and '&' separators, supports elements that are arrayrefs
17094: and hashrefs
17095: 
17096: =item *
17097: 
17098: str2hash($string) : convert string to hash using unescaping and
17099: splitting on '=' and '&', supports elements that are arrayrefs and
17100: hashrefs
17101: 
17102: =item *
17103: 
17104: str2array($string) : convert string to hash using unescaping and
17105: splitting on '&', supports elements that are arrayrefs and hashrefs
17106: 
17107: =back
17108: 
17109: =head2 Logging Routines
17110: 
17111: 
17112: These routines allow one to make log messages in the lonnet.log and
17113: lonnet.perm logfiles.
17114: 
17115: =over 4
17116: 
17117: =item *
17118: 
17119: logtouch() : make sure the logfile, lonnet.log, exists
17120: 
17121: =item *
17122: 
17123: logthis() : append message to the normal lonnet.log file, it gets
17124: preiodically rolled over and deleted.
17125: 
17126: =item *
17127: 
17128: logperm() : append a permanent message to lonnet.perm.log, this log
17129: file never gets deleted by any automated portion of the system, only
17130: messages of critical importance should go in here.
17131: 
17132: 
17133: =back
17134: 
17135: =head2 General File Helper Routines
17136: 
17137: =over 4
17138: 
17139: =item *
17140: 
17141: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17142: (a) files in /uploaded
17143:   (i) If a local copy of the file exists - 
17144:       compares modification date of local copy with last-modified date for 
17145:       definitive version stored on home server for course. If local copy is 
17146:       stale, requests a new version from the home server and stores it. 
17147:       If the original has been removed from the home server, then local copy 
17148:       is unlinked.
17149:   (ii) If local copy does not exist -
17150:       requests the file from the home server and stores it. 
17151:   
17152:   If $caller is 'uploadrep':  
17153:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17154:     for request for files originally uploaded via DOCS. 
17155:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17156:   
17157:   Otherwise:
17158:      This indicates a call from the content generation phase of the request.
17159:      -  returns the entire contents of the file or -1.
17160:      
17161: (b) files in /res
17162:    - returns the entire contents of a file or -1; 
17163:    it properly subscribes to and replicates the file if neccessary.
17164: 
17165: 
17166: =item *
17167: 
17168: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17169:                   reference
17170: 
17171: returns either a stat() list of data about the file or an empty list
17172: if the file doesn't exist or couldn't find out about it (connection
17173: problems or user unknown)
17174: 
17175: =item *
17176: 
17177: filelocation($dir,$file) : returns file system location of a file
17178: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17179: directory that relative $file lookups are to looked in ($dir of /a/dir
17180: and a file of ../bob will become /a/bob)
17181: 
17182: =item *
17183: 
17184: hreflocation($dir,$file) : returns file system location or a URL; same as
17185: filelocation except for hrefs
17186: 
17187: =item *
17188: 
17189: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17190: also removes beginning /home/httpd/html unless /priv/ follows it.
17191: 
17192: =back
17193: 
17194: =head2 Usererfile file routines (/uploaded*)
17195: 
17196: =over 4
17197: 
17198: =item *
17199: 
17200: userfileupload(): main rotine for putting a file in a user or course's
17201:                   filespace, arguments are,
17202: 
17203:  formname - required - this is the name of the element in $env where the
17204:            filename, and the contents of the file to create/modifed exist
17205:            the filename is in $env{'form.'.$formname.'.filename'} and the
17206:            contents of the file is located in $env{'form.'.$formname}
17207:  context - if coursedoc, store the file in the course of the active role
17208:              of the current user; 
17209:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17210:            if 'canceloverwrite': delete file in tmp/overwrites directory
17211:  subdir - required - subdirectory to put the file in under ../userfiles/
17212:          if undefined, it will be placed in "unknown"
17213: 
17214:  (This routine calls clean_filename() to remove any dangerous
17215:  characters from the filename, and then calls finuserfileupload() to
17216:  complete the transaction)
17217: 
17218:  returns either the url of the uploaded file (/uploaded/....) if successful
17219:  and /adm/notfound.html if unsuccessful
17220: 
17221: =item *
17222: 
17223: clean_filename(): routine for cleaing a filename up for storage in
17224:                  userfile space, argument is:
17225: 
17226:  filename - proposed filename
17227: 
17228: returns: the new clean filename
17229: 
17230: =item *
17231: 
17232: finishuserfileupload(): routine that creates and sends the file to
17233: userspace, probably shouldn't be called directly
17234: 
17235:   docuname: username or courseid of destination for the file
17236:   docudom: domain of user/course of destination for the file
17237:   formname: same as for userfileupload()
17238:   fname: filename (including subdirectories) for the file
17239:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17240:           if hashref, and context is scantron, will convert csv format to standard format
17241:   allfiles: reference to hash used to store objects found by parser
17242:   codebase: reference to hash used for codebases of java objects found by parser
17243:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17244:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17245:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17246:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17247:   context: if 'overwrite', will move the uploaded file from its temporary location to
17248:             userfiles to facilitate overwriting a previously uploaded file with same name.
17249:   mimetype: reference to scalar to accommodate mime type determined
17250:             from File::MMagic if $parser = parse.
17251: 
17252:  returns either the url of the uploaded file (/uploaded/....) if successful
17253:  and /adm/notfound.html if unsuccessful (or an error message if context 
17254:  was 'overwrite').
17255:  
17256: 
17257: =item *
17258: 
17259: renameuserfile(): renames an existing userfile to a new name
17260: 
17261:   Args:
17262:    docuname: username or courseid of destination for the file
17263:    docudom: domain of user/course of destination for the file
17264:    old: current file name (including any subdirs under userfiles)
17265:    new: desired file name (including any subdirs under userfiles)
17266: 
17267: =item *
17268: 
17269: mkdiruserfile(): creates a directory is a userfiles dir
17270: 
17271:   Args:
17272:    docuname: username or courseid of destination for the file
17273:    docudom: domain of user/course of destination for the file
17274:    dir: dir to create (including any subdirs under userfiles)
17275: 
17276: =item *
17277: 
17278: removeuserfile(): removes a file that exists in userfiles
17279: 
17280:   Args:
17281:    docuname: username or courseid of destination for the file
17282:    docudom: domain of user/course of destination for the file
17283:    fname: filname to delete (including any subdirs under userfiles)
17284: 
17285: =item *
17286: 
17287: removeuploadedurl(): convience function for removeuserfile()
17288: 
17289:   Args:
17290:    url:  a full /uploaded/... url to delete
17291: 
17292: =item * 
17293: 
17294: get_portfile_permissions():
17295:   Args:
17296:     domain: domain of user or course contain the portfolio files
17297:     user: name of user or num of course contain the portfolio files
17298:   Returns:
17299:     hashref of a dump of the proper file_permissions.db
17300:    
17301: 
17302: =item * 
17303: 
17304: get_access_controls():
17305: 
17306: Args:
17307:   current_permissions: the hash ref returned from get_portfile_permissions()
17308:   group: (optional) the group you want the files associated with
17309:   file: (optional) the file you want access info on
17310: 
17311: Returns:
17312:     a hash (keys are file names) of hashes containing
17313:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17314:         values are XML containing access control settings (see below) 
17315: 
17316: Internal notes:
17317: 
17318:  access controls are stored in file_permissions.db as key=value pairs.
17319:     key -> path to file/file_name\0uniqueID:scope_end_start
17320:         where scope -> public,guest,course,group,domains or users.
17321:               end -> UNIX time for end of access (0 -> no end date)
17322:               start -> UNIX time for start of access
17323: 
17324:     value -> XML description of access control
17325:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17326:             <start></start>
17327:             <end></end>
17328: 
17329:             <password></password>  for scope type = guest
17330: 
17331:             <domain></domain>     for scope type = course or group
17332:             <number></number>
17333:             <roles id="">
17334:              <role></role>
17335:              <access></access>
17336:              <section></section>
17337:              <group></group>
17338:             </roles>
17339: 
17340:             <dom></dom>         for scope type = domains
17341: 
17342:             <users>             for scope type = users
17343:              <user>
17344:               <uname></uname>
17345:               <udom></udom>
17346:              </user>
17347:             </users>
17348:            </scope> 
17349:               
17350:  Access data is also aggregated for each file in an additional key=value pair:
17351:  key -> path to file/file_name\0accesscontrol 
17352:  value -> reference to hash
17353:           hash contains key = value pairs
17354:           where key = uniqueID:scope_end_start
17355:                 value = UNIX time record was last updated
17356: 
17357:           Used to improve speed of look-ups of access controls for each file.  
17358:  
17359:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17360: 
17361: =item *
17362: 
17363: modify_access_controls():
17364: 
17365: Modifies access controls for a portfolio file
17366: Args
17367: 1. file name
17368: 2. reference to hash of required changes,
17369: 3. domain
17370: 4. username
17371:   where domain,username are the domain of the portfolio owner 
17372:   (either a user or a course) 
17373: 
17374: Returns:
17375: 1. result of additions or updates ('ok' or 'error', with error message). 
17376: 2. result of deletions ('ok' or 'error', with error message).
17377: 3. reference to hash of any new or updated access controls.
17378: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17379:    key = integer (inbound ID)
17380:    value = uniqueID
17381: 
17382: =item *
17383: 
17384: get_timebased_id():
17385: 
17386: Attempts to get a unique timestamp-based suffix for use with items added to a 
17387: course via the Course Editor (e.g., folders, composite pages, 
17388: group bulletin boards).
17389: 
17390: Args: (first three required; six others optional)
17391: 
17392: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17393:    docssequence, or name of group
17394: 
17395: 2. keyid (alphanumeric): name of temporary locking key in hash,
17396:    e.g., num, boardids
17397: 
17398: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17399:    file will be named nohist_namespace.db
17400: 
17401: 4. cdom: domain of course; default is current course domain from %env
17402: 
17403: 5. cnum: course number; default is current course number from %env
17404: 
17405: 6. idtype: set to concat if an additional digit is to be appended to the 
17406:    unix timestamp to form the suffix, if the plain timestamp is already
17407:    in use.  Default is to not do this, but simply increment the unix 
17408:    timestamp by 1 until a unique key is obtained.
17409: 
17410: 7. who: holder of locking key; defaults to user:domain for user.
17411: 
17412: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17413:    retrying); default is 3.
17414: 
17415: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17416: 
17417: Returns:
17418: 
17419: 1. suffix obtained (numeric)
17420: 
17421: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17422: 
17423: 3. error: contains (localized) error message if an error occurred.
17424: 
17425: 
17426: =back
17427: 
17428: =head2 HTTP Helper Routines
17429: 
17430: =over 4
17431: 
17432: =item *
17433: 
17434: escape() : unpack non-word characters into CGI-compatible hex codes
17435: 
17436: =item *
17437: 
17438: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17439: 
17440: =back
17441: 
17442: =head1 PRIVATE SUBROUTINES
17443: 
17444: =head2 Underlying communication routines (Shouldn't call)
17445: 
17446: =over 4
17447: 
17448: =item *
17449: 
17450: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17451: 
17452: =item *
17453: 
17454: reply() : uses subreply to send a message to remote machine, logs all failures
17455: 
17456: =item *
17457: 
17458: critical() : passes a critical message to another server; if cannot
17459: get through then place message in connection buffer directory and
17460: returns con_delayed, if incapable of saving message, returns
17461: con_failed
17462: 
17463: =item *
17464: 
17465: reconlonc() : tries to reconnect lonc client processes.
17466: 
17467: =back
17468: 
17469: =head2 Resource Access Logging
17470: 
17471: =over 4
17472: 
17473: =item *
17474: 
17475: flushcourselogs() : flush (save) buffer logs and access logs
17476: 
17477: =item *
17478: 
17479: courselog($what) : save message for course in hash
17480: 
17481: =item *
17482: 
17483: courseacclog($what) : save message for course using &courselog().  Perform
17484: special processing for specific resource types (problems, exams, quizzes, etc).
17485: 
17486: =item *
17487: 
17488: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17489: as a PerlChildExitHandler
17490: 
17491: =back
17492: 
17493: =head2 Other
17494: 
17495: =over 4
17496: 
17497: =item *
17498: 
17499: symblist($mapname,%newhash) : update symbolic storage links
17500: 
17501: =back
17502: 
17503: =cut
17504: 

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